抽象工厂 学习手记

概述:

     提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。 

 模型图:

     

代码二个抽象接口:


    internal interface FemaleShoes
    {
         String Name { getset; }

         String Style { getset; }

         void Display();
    }



    internal interface FemaleClothes
    {
         String Name { getset; }

         String Code { getset; }

         void Display();
        
    }

 具体实现类:

    internal class FemaleClothShoes:FemaleShoes
    {
        private String name="布鞋";

        public String Name
        {
            get { return name="布鞋"; }
            set { name="布鞋" ; }
        }

        private String style="均码";

        public String Style
        {
            get { return style="均码"; }
            set { style="均码"; }
        }

        public void Display()
        {
            Console.WriteLine("鞋子名称:"+Name+" 款式:"+Style);
        }
        
        
    }


    internal class FemaleBoardShoes : FemaleShoes
    {
        private String name = "女装板鞋";

        public String Name
        {
            get { return name = "女装板鞋"; }
            set { name = "女装板鞋"; }
        }

        private String style = "均码";

        public String Style
        {
            get { return style = "均码"; }
            set { style = "均码"; }
        }

        public void Display()
        {
            Console.WriteLine("鞋子名称:" + Name + " 款式:" + Style);
        }
        
    }

 

抽象工厂接口:

    internal interface FemaleStoreFactory
    {
        FemaleClothes CreateClothes();

        FemaleShoes CreateShoes();
    }

 具体工厂类A:

    internal class FemaleStoreOneFactory : FemaleStoreFactory
    {
        public FemaleClothes CreateClothes()
        {
            return new FemaleShirtClothes();
        }

        public FemaleShoes CreateShoes()
        {
            return new FemaleClothShoes();
        }
    }

 具体工厂类B:

    internal class FemaleStoreTwoFactory:FemaleStoreFactory
    {
        public FemaleClothes CreateClothes()
        {
            return new FemaleTshirtsClothes();
        }

        public FemaleShoes CreateShoes()
        {
            return new FemaleBoardShoes();
        }
    }

 实现实例化的类

    internal class CreateStore
    {
        private FemaleShoes shoes;

        private FemaleClothes clothes;
 
        public CreateStore(FemaleStoreFactory store){
            shoes = store.CreateShoes();
            clothes = store.CreateClothes();
        }

        public void ShowDisplay()
        {
            shoes.Display();
            clothes.Display();
        }
    }

 

 客户端:

    class Program
    {
        static void Main(string[] args)
        {
            CreateStore store = new CreateStore(new FemaleStoreOneFactory());

            store.ShowDisplay();

            Console.ReadLine();
        }
    }

 

   抽象工厂模式分离了具体的类,同时克服“开放-关闭”原则。抽象工厂模式通过接口实现了产品的分离,由工厂封装创建产品,使得他们不会出现在客户代码中。

posted @ 2012-01-18 18:08  Nopcn  阅读(281)  评论(0编辑  收藏  举报