设计模式之模板方法模式(Template Method)
?图2-1:Template模式结构图???
///?<summary>
????///?Benchmark
????///?</summary>
????public?abstract?class?AbstractClass
????{
????????public?void?TemplateMethod()
????????{
????????????this.Primitive1();
????????????this.Primitive2();
????????}
????????protected?abstract?void?Primitive1();
????????protected?abstract?void?Primitive2();
????}
????public?class?ConcreteClass1?:?AbstractClass
????{
????????public?ConcreteClass1()
????????{
????????}
????????protected?override?void?Primitive1()
????????{
????????????Console.WriteLine("ConcreteClass1μ?Operation1");
????????}
????????protected?override?void?Primitive2()
????????{
????????????Console.WriteLine("ConcreteClass1μ?Operation2");
????????}
????}
????public?class?ConcreteClass2?:?AbstractClass
????{
????????public?ConcreteClass2()
????????{
????????}
????????protected?override?void?Primitive1()
????????{
????????????Console.WriteLine("ConcreteClass2μ?Operation1");
????????}
????????protected?override?void?Primitive2()
????????{
????????????Console.WriteLine("ConcreteClass2μ?Operation2");
????????}
????}
///?<summary>
????///?Class1
????///?</summary>
????class?Class1
????{
????????///?<summary>
????????///
????????///?</summary>
????????[STAThread]
????????static?void?Main(string[]?args)
????????{
????????????//
????????????//?TODO:
????????????//
????????????AbstractClass?tmp1?=?new?ConcreteClass1();
????????????tmp1.TemplateMethod();
????????????tmp1?=?new?ConcreteClass2();
????????????tmp1.TemplateMethod();
????????????Console.Read();
????????}
????}
???Template Method模式暴露的问题也正是继承所固有的问题,Strategy模式则通过组合(委托)来达到和Template Method模式类似的效果,其代价就是空间和时间上的代价。
作者:洞庭散人
出处:http://phinecos.cnblogs.com/