首页 > 代码库 > 模板方法模式(Template Method)c#简单例子

模板方法模式(Template Method)c#简单例子

模板方法模式(Template Method)c#简单例子

要点:骨架、步骤延迟到子类

例子建立玩家骨架部分,具体动作由延迟到子类去做

namespace adapterpattern
{
    public partial class TemplateMethodForm : Form
    {
        public TemplateMethodForm()
        {
            InitializeComponent();
        }

        private void btndisplay_Click(object sender, EventArgs e)
        {
            Play p1 = new play1();
            p1.Run();
            listBox1.Items.Add(BaseData.DisplayString);
            Play p2 = new play2();
            BaseData.DisplayString = "";
            p2.Run();
            listBox1.Items.Add(BaseData.DisplayString);
        }
    }
    public static class BaseData//数据中转站
    {
        public static string DisplayString { get; set; }
        public static int EnemyNumber { get; set; }
    }
    public abstract class Play//模板
    {
        //骨架
        protected abstract void start();
        protected abstract void move();
        protected abstract void stop();
        public void Run()
        {
            start();//延迟到子类
            move();
            stop();
        }
    }
    public class play1 : Play//实现模板方法1
    {

        protected override void start()
        {
            BaseData.DisplayString += "玩家1开始运行....";
        }
        protected override void move()
        {
            BaseData.DisplayString += "移动.......";
        }
        protected override void stop()
        {
            BaseData.DisplayString += "停止运行.....";
        }
    }
    public class play2 : Play//实现模板方法1
    {
        protected override void start()
        {
            BaseData.DisplayString += "玩家2开始运行....";
        }
        protected override void move()
        {
            BaseData.DisplayString += "移动.......";
        }
        protected override void stop()
        {
            BaseData.DisplayString += "停止运行.....";
        }
    }
}





模板方法模式(Template Method)c#简单例子