设计模式-模板方法模式

来源:互联网 发布:增值税开票软件安装 编辑:程序博客网 时间:2024/06/05 20:43
一、模板方法模式
定义:定义一个操作中的算法骨架,而将一些步骤延迟到子类。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
类型:行为型模式
特点:通过把不变的行为搬移到超类,去除子类中的重复代码来体现它的优势,提供了一个很好的代码复用平台。
二、UML类图

模板抽象类AbstractClass实现了一个模板方法,定义了算法的骨架,如顺序执行PrimitiveOperation1()、PrimitiveOperation2(),但这些方法的具体实现是在子类中定义。


三、具体案例
参考大话设计模式-抄写试卷和答题,试卷对每个人而言都是一样的,而答案因人而异,因此可用模板方法模式实现。
java代码实现:
public class TemplateMethodDesign {public static void main(String[] args) {TestPaper studentA=new TestPaperA();System.out.println("第一个学生答卷:");studentA.testQuestion1();studentA.testQuestion2();studentA.testQuestion3();TestPaper studentB=new TestPaperB();System.out.println("第二个学生答卷:");studentB.testQuestion1();studentB.testQuestion2();studentB.testQuestion3();}}abstract class TestPaper{public void testQuestion1(){System.out.println("杨过得到,后来给了郭靖,可能是[] a.铁 b.铜 c.钢 d.纤维");System.out.println("答案: "+answer1());}public abstract String answer1();public void testQuestion2(){System.out.println("杨过铲除了情花,造成[]  a.植物不再害人 b.珍稀物种灭绝 c.破坏生态平衡 d.沙漠化");System.out.println("答案: "+answer2());}public abstract String answer2();public void testQuestion3(){System.out.println("蓝凤凰致使华山师徒呕吐不止,大夫会给开什么药[] a.阿司匹林 b.牛黄解毒片 c.福尿酸 d.生牛奶");System.out.println("答案: "+answer3());}public abstract String answer3();}class TestPaperA extends TestPaper{@Overridepublic String answer1() {return "a";}@Overridepublic String answer2() {return "b";}@Overridepublic String answer3() {return "c";}}class TestPaperB extends TestPaper{@Overridepublic String answer1() {return "d";}@Overridepublic String answer2() {return "b";}@Overridepublic String answer3() {return "a";}}
实现结果:

第一个学生答卷:
杨过得到,后来给了郭靖,可能是[] a.铁 b.铜 c.钢 d.纤维
答案: a
杨过铲除了情花,造成[]  a.植物不再害人 b.珍稀物种灭绝 c.破坏生态平衡 d.沙漠化
答案: b
蓝凤凰致使华山师徒呕吐不止,大夫会给开什么药[] a.阿司匹林 b.牛黄解毒片 c.福尿酸 d.生牛奶
答案: c
第二个学生答卷:
杨过得到,后来给了郭靖,可能是[] a.铁 b.铜 c.钢 d.纤维
答案: d
杨过铲除了情花,造成[]  a.植物不再害人 b.珍稀物种灭绝 c.破坏生态平衡 d.沙漠化
答案: b
蓝凤凰致使华山师徒呕吐不止,大夫会给开什么药[] a.阿司匹林 b.牛黄解毒片 c.福尿酸 d.生牛奶
答案: a

参考:大话设计模式

原创粉丝点击