欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

设计模式之工厂方法模式

程序员文章站 2024-01-05 17:10:25
...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AbstractFactoryPattern
{
    public class Pizza
    {
        public string name;
        internal void Prepare()
        {
            Console.WriteLine("准备"+name);
        }

        internal void Bake()
        {
            Console.WriteLine("烘焙" + name);
        }

        internal void Cut()
        {
            Console.WriteLine("切片" + name);
        }

        internal void Box()
        {
            Console.WriteLine("装盒" + name);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AbstractFactoryPattern
{
    public abstract class PizzaStore
    {

        public Pizza OrderPizza(string type)
        {
            Pizza pizza;
            pizza = this.CreatePizza(type);
            pizza.Prepare();
            pizza.Bake();
            pizza.Cut();
            pizza.Box();
            return pizza;
        }

        public abstract Pizza CreatePizza(string type);

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AbstractFactoryPattern
{
//必胜客Pizza店
    class PizzaHut:PizzaStore
    {
        Pizza pizza;
        public override Pizza CreatePizza(string type)
        {
            if (type == "芝士烤肉Pizza")
            {
                pizza = new Pizza();
                pizza.name = type;
            }
            else if (type == "蔬菜Pizza")
            {
                pizza = new Pizza();
                pizza.name = type;
            }
            else if (type == "海鲜Pizza")
            {
                pizza = new Pizza();
                pizza.name = type;
            }
            return pizza;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AbstractFactoryPattern
{
//来一家Pizza店
    class MrPizza:PizzaStore
    {
        Pizza pizza;
        public override Pizza CreatePizza(string type)
        {
            if (type == "MrPizza1号")
            {
                pizza = new Pizza();
                pizza.name = type;
            }
            else if (type == "MrPizza2号")
            {
                pizza = new Pizza();
                pizza.name = type;
            }
            else if (type == "MrPizza3号")
            {
                pizza = new Pizza();
                pizza.name = type;
            }
            return pizza;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AbstractFactoryPattern
{
    class Program
    {
    //开吃,生产Pizza
        static void Main(string[] args)
        {
            PizzaStore ps = new PizzaHut();
            ps.OrderPizza("芝士烤肉Pizza");
            Console.ReadLine();
        }
    }
}


转载于:https://my.oschina.net/love404/blog/413301