1.工厂方法模式

  第一了一个用于创建对象的接口,让子类自己决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。

(C#)工厂方法模式

*工厂方法模式即克服了简单工厂模式违反开放-封闭原则的缺点,又保留了封装对象创建过程的优点。


2.实例

namespace 工厂方法模式
{
    class Program
    {
        static void Main(string[] args)
        {
            IFactory factory = new CUnderGraduate();
            Leifeng student = factory.CreateLeiFeng();
            student.Sweep();
            student.Wash();
            student.BuyRice();

            Console.ReadLine();
        }
    }

    /// <summary>
    /// 所有工厂中公共执行的操作的类
    /// </summary>
    class Leifeng
    {
        public void Sweep()
        {
            Console.WriteLine("扫地");
        }
        public void Wash()
        {
            Console.WriteLine("洗衣");
        }
        public void BuyRice()
        {
            Console.WriteLine("买米");
        }
    }

    /// <summary>
    /// 创建工厂接口
    /// </summary>
    interface  IFactory
    {
        Leifeng CreateLeiFeng();
    }

    /// <summary>
    /// 工厂需要实例化的类
    /// </summary>
    class UnderGraduate : Leifeng
    {}

    /// <summary>
    /// 工厂需要实例化的类
    /// </summary>
    class Voluteers:Leifeng
    { }


    /// <summary>
    /// 工厂,用来实例化类
    /// </summary>
    class CUnderGraduate:IFactory
    {
        public Leifeng CreateLeiFeng()
        {
            return new UnderGraduate();
        }
    }

    /// <summary>
    /// 工厂,用来实例化类
    /// </summary>
    class CVoluteers : IFactory
    {
        public Leifeng CreateLeiFeng()
        {
            return new Voluteers();
        }
    }

}

 

相关文章:

  • 2021-11-17
  • 2022-12-23
  • 2021-07-30
  • 2021-12-14
  • 2022-01-26
  • 2021-07-11
  • 2021-05-20
  • 2021-11-25
猜你喜欢
  • 2022-12-23
  • 2021-05-31
  • 2021-06-01
  • 2021-08-15
  • 2022-01-04
  • 2021-10-16
  • 2021-10-23
相关资源
相似解决方案