Java设计模式-模板设计

问题:什么时候可以用这设计模式?

答:用一种场景来比喻,小明要打印黑白照片,小红要打印彩色照片,那么打印机就是个模板分别刻印出黑白和彩色,等于说一个东西经过不同的改造既可使用模板设计。

开始设计:

先封装一个实体类。


设计一个模板  我们使用print代表打印,使用TemplateBean来代表要打印的是什么风格照片


黑白打印机:


彩色打印机:


写上main函数开始打印就是了。

public static void main(String[] args) {
TemplateBean define = new TemplateBean();
define.setName("Neacy");
define.setType("黑白照片");
DefaultPrint defaultPrint = new DefaultPrint(define);
defaultPrint.print(define);


TemplateBean color = new TemplateBean();
color.setName("Jayu");
color.setType("彩色照片");
ColorsPrint colorPrint = new ColorsPrint(color);
colorPrint.print(color);
}


模板设计起到的作用就是 分类来处理同一件事情既可。

你可能感兴趣的:(java设计模式)