C# 设计模式(4)抽象工厂模式

抽象工厂模式

1. 倾斜的可扩展性设计:产品簇扩展方便,工厂职责不能扩展

代码实现:

三国服务:

namespace AbstractFactory.SanGuoService
{
    public interface ILord
    {
        void ShowLord();
    }
    public class LordWei:ILord
    {
        public void ShowLord()
        {
            Console.WriteLine($"{this.GetType().Name} is 曹操");
        }
    }
    public class LordShu:ILord
    {
        public void ShowLord()
        {
            Console.WriteLine($"{this.GetType().Name} is 刘备");
        }
    }
    public class LordWu:ILord
    {
        public void ShowLord()
        {
            Console.WriteLine($"{this.GetType().Name} is 孙权");
        }
    }
    public interface IGeneral
    {
        void ShowGenerals();
    }
    public class GeneralWei:IGeneral
    {
        public void ShowGenerals()
        {
            Console.WriteLine($"{this.GetType().Name} is 许褚 典韦 夏侯渊 张辽 徐晃");
        }
    }
    public class GeneralShu:IGeneral
    {
        public void ShowGenerals()
        {
            Console.WriteLine($"{this.GetType().Name} is 关羽 张飞 赵云 黄忠 马超");
        }
    }
    public class GeneralWu:IGeneral
    {
        public void ShowGenerals()
        {
            Console.WriteLine($"{this.GetType().Name} is 黄盖 甘宁 太史慈 韩当 凌统");
        }
    }
}

抽象工厂:

namespace AbstractFactoryPattern.AbstractFactory
{
    public abstract class AbstractSanGuoFactory
    {
      public abstract ILord GetLord();
      public abstract IGeneral GetGenerals();
    }
    public  class FactoryWei:AbstractSanGuoFactory
    {
        public override ILord GetLord()
        {
            return new LordWei();
        }

        public override IGeneral GetGenerals()
        {
            return new GeneralWei();
        }
    }
    public  class FactoryShu:AbstractSanGuoFactory
    {
        public override ILord GetLord()
        {
            return new LordShu();
        }

        public override IGeneral GetGenerals()
        {
            return new GeneralShu();
        }
    }
    public  class FactoryWu:AbstractSanGuoFactory
    {
        public override ILord GetLord()
        {
            return new LordWu();
        }

        public override IGeneral GetGenerals()
        {
            return new GeneralWu();
        }
    }
}

代码调用:

    class Program
    {
        static void Main(string[] args)
        {
            AbstractSanGuoFactory abstractShuFactory = new FactoryShu();
            abstractShuFactory.GetLord().ShowLord();
            abstractShuFactory.GetGenerals().ShowGenerals();

            AbstractSanGuoFactory abstractWeiFactory = new FactoryWei();
            abstractWeiFactory.GetLord().ShowLord();
            abstractWeiFactory.GetGenerals().ShowGenerals();

            AbstractSanGuoFactory abstractWuFactory = new FactoryWu();
            abstractWuFactory.GetLord().ShowLord();
            abstractWuFactory.GetGenerals().ShowGenerals();
        }
    }

结果:

 

posted @ 2020-12-01 10:49  NiKaFace  阅读(160)  评论(0编辑  收藏  举报