在模板模式中,一个抽象类公开定义了执行它的方法的方式或方法
模板模式属于行为型模式,通过将相似的业务行为抽离出来放到抽象类中暴露给上层,然后在自己子类中实现具体的业务行为,通过模板类来约束上层的业务调用。
1、定义抽象基类
public abstract class game { public abstract void initialize(); public abstract void startplay(); public abstract void endplay(); public void play() { initialize(); startplay(); endplay(); } }
2、定义业务子类
public class cricket : game { public override void endplay() { console.writeline("cricket game finished"); } public override void initialize() { console.writeline("cricket game initialized!start palying"); } public override void startplay() { console.writeline("cricket game started.enjoy the game"); } } public class football : game { public override void startplay() { console.writeline("football game started.enjog the game"); } public override void initialize() { console.writeline("football game initialized.start playing."); } public override void endplay() { console.writeline("football game finished."); } }
3、上层调用
class program { static void main(string[] args) { game game = new cricket(); game.play(); game = new football(); game.play(); console.readkey(); } }
模板方法类似在建造房子时先将房子的整体框架搭建后,然后具体的建筑细节放到建筑这个地方的时候再具体考虑,延迟的业务的构造。
如对本文有疑问, 点击进行留言回复!!
荐 厉害了!阿里P8架构师用4大技术文档带你深入解读爆火的中台战略
FlowableException: Error initialising dmn data model报错问题
网友评论