【23种GOF设计模式】C#代码完整案例详解--工厂方法

来自:CCNetCore社区,一个关注.Netcore领域的社区团队。

工厂方法FactoryMethod

工厂方法FactoryMethod 创建型设计模式

是简单工厂的进阶,单纯将简单工厂一个类分开成多给类,将之前的一个类的耦合进行解耦。
每一个类中都有创建实例的方法,而不是通过枚举进行判断。通过调用不同工厂来返回不同的对象即可。

Program.cs

using FactoryPattern.War3.Interface;
using FactoryPattern.War3.Service;
using FactoryPattern.War3.ServiceExtend;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryMethodPattern
{
   /// <summary>
   /// 1 对比简单工厂,建立工厂方法(FactoryMethod)
   /// 2 工厂方法的优缺点和应用
   /// </summary>
   class Program
   {
       static void Main(string[] args)
       {
           try
           {
               {
                   Human human = new Human();
                   Undead undead = new Undead();
                   NE ne = new NE();
                   ORC orc = new ORC();

                   //Six six=new Six()//参数信息很麻烦

               }
               {
                   IRace human = new Human();
                   IRace undead = new Undead();
                   IRace ne = new NE();
                   IRace orc = new ORC();
               }
               {
                   IFactory humanFactory = new HumanFactory();
                   IRace human = humanFactory.CreateInstance();

                   IFactory fiveFactory = new FiveFactory();
                   IRace five = fiveFactory.CreateInstance();

                   IFactory sixFactory = new SixFactoryExtend();// new SixFactory();

                   IRace six = sixFactory.CreateInstance();
               }
           }
           catch (Exception ex)
           {
               Console.WriteLine(ex.Message);
           }
           Console.Read();
       }
   }
}

SixFactory.cs

using FactoryPattern.War3.Interface;
using FactoryPattern.War3.Service;
using