# 工厂方法模式

属于创建型模式。
定义一个用于创建对象的接口,让子类决定实例化哪一个类,使一个类的实例化延迟到其子类。
如果新增一个产品,只需要在原有的基础上进行扩展就可以了。

# 类图

  1. 创建抽象类和具体的类
  2. 创建工厂接口,由具体的工厂类实现接口

img

# 代码

# 需要实例化的类

namespace CreationalPatterns_FactoryMethodPattern
{
    public abstract class Shape
    {
        /// <summary>
        /// 形状
        /// </summary>
        public abstract void MyShape();
    }
}
namespace CreationalPatterns_FactoryMethodPattern
{
    public class Square : Shape
    {
        public override void MyShape()
        {
            Console.WriteLine("Square");
        }
    }
}
namespace CreationalPatterns_FactoryMethodPattern
{
    public class Triangle : Shape
    {
        public override void MyShape()
        {
            Console.WriteLine("Triangle");
        }
    }
}

# 工厂接口

namespace CreationalPatterns_FactoryMethodPattern
{
    public interface IShapeFactory
    {
        /// <summary>
        /// 创建形状
        /// </summary>
        public Shape CreateShape();
    }
}

# 具体的工厂

namespace CreationalPatterns_FactoryMethodPattern
{
    public class SquareFactory : IShapeFactory
    {
        public Shape CreateShape()
        {
            return new Square();
        }
    }
}
namespace CreationalPatterns_FactoryMethodPattern
{
    public class TriangleFectory : IShapeFactory
    {
        public Shape CreateShape()
        {
            return new Triangle();
        }
    }
}

# 测试

namespace CreationalPatterns_FactoryMethodPattern
{
    public class Program
    {
        private static void Main()
        {
            IShapeFactory squareFactory = new SquareFactory();
            IShapeFactory triangleFectory = new TriangleFectory();
            Shape square = squareFactory.CreateShape();
            Shape triangle = triangleFectory.CreateShape();
            square.MyShape();
            triangle.MyShape();
        }
    }
}

运行结果:
Square
Triangle