模板方法:定義一個操作中的算法的骨架,而將一些步驟延遲到子類中。模板方法使得子類可以不改變一個算法的結構即可重定義改算法的某些特定步驟。
namespace TemplateMethod { public abstract class AbstractClass { public abstract void PrimitiveOperation1(); public abstract void PrimitiveOperation2(); public void TemplateMethod() { PrimitiveOperation1(); PrimitiveOperation2(); Console.WriteLine(""); } } public class ConcreteClassA:AbstractClass { public override void PrimitiveOperation1() { Console.WriteLine("具體類A方法1實現"); } public override void PrimitiveOperation2() { Console.WriteLine("具體類A方法2實現"); } } public class ConcreteClassB : AbstractClass { public override void PrimitiveOperation1() { Console.WriteLine("具體類B方法1實現"); } public override void PrimitiveOperation2() { Console.WriteLine("具體類B方法2實現"); } } }View Code
測試代碼:
AbstractClass ac; ac = new ConcreteClassA(); ac.TemplateMethod(); ac = new ConcreteClassB(); ac.TemplateMethod();View Code