C#模板方法模式(Template Method Pattern)实例教程
本文以一个简单的实例形式讲述了C#模板方法模式的实现方法,分享给大家供大家参考。具体实现方法如下:
这里假设要做一道红烧肉,做法有很多,在不同的做法中都有相同的部分,比如都要放油、放肉、放调料等。也有不同之处,比如有些做法放可乐,有些做法放甜蜜酱,等等。
先提炼出一个抽象类,该类不仅有制作红烧肉的各个步骤,而且还把各个步骤归纳到另一个方法,我们把这个方法称作模版方法。另外,在模版方法中,对于一些不确定的方面先用抽象方法。
publicabstractclassHongShaoRou { publicvoidMakeHongShaoRou() { You(); Rou(); Others(); TiaoLiao(); } publicvoidYou() { Console.WriteLine("放入油"); } publicvoidRou() { Console.WriteLine("放入肉"); } publicabstractvoidOthers(); publicvoidTiaoLiao() { Console.WriteLine("放入调料"); } }
假如,有一种"四川红烧肉"是放芝麻酱的。
publicclassSiChuangHongShaoRou:HongShaoRou { publicoverridevoidOthers() { Console.WriteLine("放入芝麻酱"); } }
客户端只要调用抽象类的模版方法就可以。
classProgram { staticvoidMain(string[]args) { HongShaoRouhongShaoRou=newSiChuangHongShaoRou(); hongShaoRou.MakeHongShaoRou(); Console.ReadKey(); } }
希望本文所述对大家C#程序设计的学习有所帮助。