抽象工厂模式

故事:

  以前有个定制鞋子的工厂,客户满意度很高,后来有的客户来的时候想定制套装(包括鞋子和衬衫)。

 

建模:

  工厂前台接待处。

  工厂套装协调部门。

  生产线。

  鞋。

  很多喜欢个性和变化人的都成了这个定制工厂的客户。

 

类图:

实现:

HelpDesk

namespace AbstractFactory
{
    class HelpDesk
    {
        SuitDepartment sd;
        
        public HelpDesk()
        {
            sd = new SuitDepartment();
            
        }

        public void produceSuit(string shoesType, string shirtType)
        {
            sd.produceShoes(shoesType);
            sd.produceShirt(shirtType);
        }
    }
}

AbstractFactory

namespace AbstractFactory
{
    public abstract class AbstractFactory
    {
        public abstract Shoes produceShoes(string shoesType);
        public abstract Shirt produceShirt(string shirtType);        
    }
}

SuitDepartment

namespace AbstractFactory
{
    class SuitDepartment:AbstractFactory
    {
        public override Shoes produceShoes(string shoesType)
        {
            switch(shoesType)
            {
                case "Sport":
                    return new SportShoes();
                case "Leisure":
                    return new LeisureShoes();
                default:
                    return null;
            }
        }
        public override Shirt produceShirt(string shirtType)
        {
            switch(shirtType)
            {
                case "Sport":
                    return new SportShirt();
                case "Leisure":
                    return new LeisureShirt();
                default:
                    return null;
            }

        }
    }
}

Program

namespace AbstractFactory
{
    class Program
    {
        static void Main(string[] args)
        {
            HelpDesk helpDesk = new HelpDesk();

            Console.WriteLine("请输入你想要的鞋子:Sport/Leisure");
            string shoesType = Console.ReadLine();
            Console.WriteLine("请输入你想要的衬衫:Sport/Leisure");
            string shirtType = Console.ReadLine();

            Console.WriteLine("\n------进厂定制套装---------\n");
            helpDesk.produceSuit(shoesType, shirtType);
            Console.WriteLine("\n-------套装出厂--------\n");
            
        }
    }
}

 

效果:

posted on 2012-10-04 20:44  caigen  阅读(239)  评论(0编辑  收藏  举报