设计模式-模板方法模式

public abstract class Moban
    {
        public string name;
        public Moban(string _name)
        {
            this.name = _name;
        }
        private void showSiteName()
        {
            Console.WriteLine("这是{0}网站",this.name);
        }
        private void createHead()
        {
            Console.WriteLine("这里是页头");
        }
        private void createFoot()
        {
            Console.WriteLine("这里是页脚");
        }
        public abstract void createContent();//内容区

        public void createHtml()
        {
            showSiteName();
            createHead();
            createContent();
            createFoot();
            Console.ReadLine();
        }
    }
    public class SiteA : Moban
    {
        public SiteA(string _name) : base(_name)
        {
        }

        public override void createContent()
        {
            Console.WriteLine("我是{0}网站的内容区:阿里巴巴和腾讯今天合并了",this.name);
        }
    }
    public class SiteB : Moban
    {
        public SiteB(string _name) : base(_name)
        {
        }

        public override void createContent()
        {
            Console.WriteLine("我是{0}网站的内容区:马云和马化腾不得不说的故事", this.name);
        }
    }
        //前端:
        static void Main(string[] args)
        {
            Moban sa = new SiteA("百家论坛");
            Moban sb = new SiteB("天涯论坛");
            sa.createHtml();
            sb.createHtml();
        }

总结:模板方法模式貌似最常用,没什么好说的,貌似可以用原型模式改造下。
public class MobanPrototype:ICloneable
{
public string name { get; set; }
public MobanPrototype()
{
}
private void showSiteName()
{
Console.WriteLine("这是{0}网站", this.name);
}
private void createHead()
{
Console.WriteLine("这里是页头");
}
private void createFoot()
{
Console.WriteLine("这里是页脚");
}
private void createContent(string content)//内容区
{
Console.WriteLine(content);
}

    public void createHtml(string content)
    {
        showSiteName();
        createHead();
        createContent(content);
        createFoot();
        Console.ReadLine();
    }

    public object Clone()
    {
        return (MobanPrototype)this.MemberwiseClone();
    }
}
    //前端
    static void Main(string[] args)
    {
        //Moban sa = new SiteA("百家论坛");
        //Moban sb = new SiteB("天涯论坛");
        //sa.createHtml();
        //sb.createHtml();

        MobanPrototype mobanPrototype = new MobanPrototype();
        MobanPrototype siteA = (MobanPrototype)mobanPrototype.Clone();
        MobanPrototype siteB = (MobanPrototype)mobanPrototype.Clone();

        siteA.name = "百家论坛";            
        siteB.name = "天涯论坛";
        siteA.createHtml(string.Format("我是{0}网站的内容区:阿里巴巴和腾讯今天合并了", siteA.name));
        siteB.createHtml(string.Format("我是{0}网站的内容区:马云和马化腾不得不说的故事", siteB.name));

    }

猜你喜欢

转载自blog.51cto.com/5591787/2114944