工厂模式

雷锋类

    class LeiFeng
    {
        public void Sweep()
        {
            System.Windows.Forms.MessageBox.Show("扫地");
        }

        public void Wash()
        {
            System.Windows.Forms.MessageBox.Show("洗衣");
        }
    }

    class Undergraduate : LeiFeng
    { }

    class Volunteer : LeiFeng
    { }

雷锋工厂

    interface IFactory
    {
        LeiFeng CreateLeiFeng();
    }

    class UndergraduateFactory : IFactory
    {
        public LeiFeng CreateLeiFeng()
        {
            return new Undergraduate();
        }
    }

    class VolunteerFactory : IFactory
    {
        public LeiFeng CreateLeiFeng()
        {
            return new Volunteer();
        }
    }

客户端代码

            IFactory factory = new UndergraduateFactory();
            LeiFeng student = factory.CreateLeiFeng();

            student.Sweep();
            student.Wash();

总结:

1、工厂模式,定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。

2、工厂模式克服了简单工厂违背开放-封闭原则的缺点,又保持了封闭对象创建过程的优点。

原文地址:https://www.cnblogs.com/baiqjh/p/2843635.html