C#设计模式:模板方法模式(Template Method)

一,咱们为何须要模板设计模式?设计模式

在程序设计中,可能每一个对象都有共同的地方,而此时若是每一个对象定义一次,以下例子,每一个对象都写Stay()方法,这样在每一个类中都有不少相同的代码,此时,咱们须要用到模板设计模式,来解决这个问题ide

二,模板设计模式思路:是把相同的部分抽象出来到抽象类中去定义,具体子类来继承抽象类,并实现抽象类中的抽象方法,从而达到具体实现的不一样部分,这个思路也正式模板方法的实现精髓所在。spa

三,以下例子:设计

复制代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _13.模板方法模式
{
    //模板设计模式
    //在程序设计中,可能每一个对象都有共同的地方,而此时若是每一个对象定义一次,以下,每一个对象都写Stay方法,这样在每一个类中都有不少相同的代码
    //此时,咱们须要用到模板设计模式,来解决这个问题
    //模板设计模式思路:是把相同的部分抽象出来到抽象类中去定义,具体子类来继承抽象类,并实现抽象类中的抽象方法,从而达到具体实现的不一样部分,这个思路也正式模板方法的实现精髓所在
    class Program
    {
        static void Main(string[] args)
        {
            People p = new Chinese();
            People p2 = new English();
        }
    }
    public abstract class People
    {
        public People()
        {
            Stay();
            Console.WriteLine("咱们是人类");
            Country();
            Say();
        }

        protected void Stay()
        {
            Console.WriteLine("我住在地球");
        }

        public abstract void Country();

        public abstract void Say();
    }
    public class Chinese : People
    {
        public override void Country()
        {
            Console.WriteLine("我是中国人");
        }
        public override void Say()
        {
            Console.WriteLine("咱们说中文");
        }
    }
    public class English : People
    {
        public override void Country()
        {
            Console.WriteLine("We are English");
        }
        public override void Say()
        {
            Console.WriteLine("We speak English");
        }
    }
}

复制代码

三,咱们将共用定义为protected,这样只有继承时才能够调用这个共用模板代码对象

相关文章
相关标签/搜索