C#设计模式之---模板方法模式

模板方法模式(Template Method Pattern)

模板方法模式(Template Method Pattern)定义了一个算法的步骤,并允许子类为一个或多个步骤提供其实现方式。让子类别在不改变算法架构的情况下,重新定义算法中的某些步骤。模板方法模式是比较简单的一种设计模式,作为模板的方法要定义在父类中,在方法的定义中使用到抽象方法,而只看父类的抽象方法是根本不知道怎样处理的,实际做具体处理的是子类,在子类中实现具体功能,因此不同的子类执行将会得出不同的实现结果,但是处理流程还是按照父类定制的方式。这就是模板方法的要义所在,制定算法骨架,让子类具体实现。模板方法设计模式是一种行为型模式。

using System;
using System.Text;
namespace ConsoleApplication
{
   //一般每个接口或类都写在单独的.cs文件中
    //本示例为了执行查看方便才写在一起  
    public abstract class Player//模板
    {
        //骨架
        protected abstract void Start();
        protected abstract void Move();
        protected abstract void Stop();
        public void Run()
        {
            Start();//延迟到子类
            Move();
            Stop();
        }
    }
    public class PlayerA : Player//实现模板方法1
    {
        protected override void Start()
        {
            Console.WriteLine("玩家A开始运行....");
        }
        protected override void Move()
        {
            Console.WriteLine("移动.......");
        }
        protected override void Stop()
        {
            Console.WriteLine("停止运行.....");
        }
    }
    public class PlayerB : Player//实现模板方法1
    {
        protected override void Start()
        {
            Console.WriteLine("玩家B开始运行....");
        }
        protected override void Move()
        {
            Console.WriteLine("移动.......");
        }
        protected override void Stop()
        {
            Console.WriteLine("停止运行.....");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Player p1 = new PlayerA();
            p1.Run();
            Player p2 = new PlayerB();
            p2.Run();
            Console.ReadKey();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/lwf3115841/article/details/131727279