【设计模式】2.抽象工厂

说明:跟工厂一样,就是面向对象式的解耦new这个关键词,感觉像个嵌套工厂,比如一套衣服包括外套,衬衫,裤子,鞋子。然后又分西装套装、运动套装、休闲套装等,为了保证一系列的完整;

注意:套装易扩展,但产品难扩展,比如要加多个眼镜,那所有套装都要加一遍;

场景:QQ皮肤,商品的规格和颜色信息

实现:

   //将汽车分为车型,颜色
    //汽车是抽象工厂,车型是工厂,颜色是工厂

    public class test
    {
        public test() {
            //宝马
            carFactory baoma = new baomaFactory();
            chexing baoma_chexing = baoma.getchexing();
            yanse baoma_yanse = baoma.getyanse();

            baoma_chexing.diandong();
            baoma_yanse.hongse();

            //奥迪
            carFactory aodi = new aodiFactory();
            chexing aodi_chexing = aodi.getchexing();
            yanse aodi_yanse = aodi.getyanse();
        }
    }

    public abstract class carFactory
    {
        public abstract chexing getchexing();
        public abstract yanse getyanse();
    }

    public class baomaFactory : carFactory
    {
        public override chexing getchexing()
        {
            return new baomachexing();
        }
        public override yanse getyanse()
        {
            return new baomayanse();
        }
    }
    public class aodiFactory : carFactory
    {
        public override chexing getchexing()
        {
            return new aodichexing();
        }
        public override yanse getyanse()
        {
            return new aodiyanse();
        }
    }


    public interface chexing { void diandong(); void qiyou(); }
    public class baomachexing : chexing
    {
        public void diandong() {
            //宝马的电动车型
        }
        public void qiyou()
        {
            //宝马的汽油车型
        }
    }
    public class aodichexing : chexing
    {
        public void diandong()
        {
            //奥迪的电动车型
        }
        public void qiyou()
        {
            //奥迪的汽油车型
        }
    }

    public interface yanse { void hongse(); void baise(); }
    public class baomayanse : yanse
    {
        public void hongse() {
            //红色宝马
        }
        public void baise() { }
    }
    public class aodiyanse : yanse
    {
        public void hongse()
        {
            //红色奥迪
        }
        public void baise() { }
    }
原文地址:https://www.cnblogs.com/laokchen/p/13532821.html