# 模板模式
属于行为型模式。
一个抽象类公开定义了执行它的方法的方式 / 模板。它的子类可以按需要重写方法实现,但调用将以抽象类中定义的方式进行。
# 类图
# 代码
# 抽象类及其子类
| namespace BehavioralPatterns_TemplatePattern |
| { |
| |
| |
| |
| public abstract class Shape |
| { |
| |
| |
| |
| public void MyShape() |
| { |
| Console.WriteLine("Shape: " + ShapeName()); |
| } |
| |
| |
| |
| |
| |
| protected abstract string ShapeName(); |
| } |
| } |
| namespace BehavioralPatterns_TemplatePattern |
| { |
| |
| |
| |
| public class Square : Shape |
| { |
| protected override string ShapeName() |
| { |
| return "Square"; |
| } |
| } |
| } |
| namespace BehavioralPatterns_TemplatePattern |
| { |
| |
| |
| |
| public class Triangle : Shape |
| { |
| protected override string ShapeName() |
| { |
| return "Triangle"; |
| } |
| } |
| } |
# 测试
| namespace BehavioralPatterns_TemplatePattern |
| { |
| public class Program |
| { |
| private static void Main() |
| { |
| Shape shape_0 = new Square(); |
| Shape shape_1 = new Triangle(); |
| |
| shape_0.MyShape(); |
| shape_1.MyShape(); |
| } |
| } |
| } |
运行结果:
Shape: Square
Shape: Triangle