C# 设计模式(2)简单工厂模式

简单工厂模式

1. 运用倒置原则:依赖于抽象,不依赖于细节

2. 简单工厂+配置文件 + 反射 设计可扩展的应用

代码实现 :

背景:War3 有多个种族 HUM ORC NE UD

// HUM ORC NE UD
namespace SimpleModule.Warcraft3Service
{
    public interface IRace
    {
        void InterWar();
    }

    public class Human:IRace
    {
        public void InterWar()
        {
            Console.WriteLine($"I'm Sky, using Human");
        }
    }

    public class NE:IRace
    {
        public void InterWar()
        {
            Console.WriteLine($"I'm Moon, using NE");
        }
    }
}

配置文件内容:

如何读取配置文件参考:C# .Net Core读取AppSettings

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="RaceType" value="SimpleModule.Warcraft3Service.ORC,SimpleModule.Warcraft3Service"/>
  </appSettings>
</configuration>

玩家工厂 :

使用反射获取种族类型-->创建实列

    public class PlayerFactory
    {
        private static readonly string RaceType = System.Configuration.ConfigurationManager.AppSettings["RaceType"];

        public static IRace GetRaceTypeByConfigurationReflection()
        {
            IRace race = null;
            try
            {
                var assembly = Assembly.Load(RaceType.Split(',')[1]);
                var type = assembly.GetType(RaceType.Split(',')[0]);
                race = (IRace) Activator.CreateInstance(type);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            return race;
        }
    }

程序调用:

    class Program
    {
        static void Main(string[] args)
        {
            PlayerFactory.GetRaceTypeByConfigurationReflection()?.InterWar();
        }
    }

结果:

如果使用其他种族:只需要修改Appconfig,不需要修改代码。

原文地址:https://www.cnblogs.com/YourDirection/p/14062642.html