设计模式系列:简单工厂模式(Simple Factory Pattern)

1.介绍

简单工厂模式是属于创建型模式,又叫做静态工厂方法(Static Factory Method)模式,但不属于23种GOF设计模式之一。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。简单工厂模式是工厂模式家族中最简单实用的模式,可以理解为是不同工厂模式的一个特殊实现。 

2.示例

    public interface IRace
    {
        void ShowKing();
    }
    public class Human : IRace
    {
        public void ShowKing()
        {
            Console.WriteLine("The king of Human is Sky");
        }
    }
    public class NE : IRace
    {
        public void ShowKing()
        {
            Console.WriteLine("The king of NE is Moon");
        }
    }
    public class Orc : IRace
    {
        public void ShowKing()
        {
            Console.WriteLine("The king of Orc is Grubby");
        }
    }
    public class Undead : IRace
    {
        public void ShowKing()
        {
            Console.WriteLine("The king of Undead is Gostop");
        }
    }
    public enum RaceType
    {
        Human,
        Orc,
        Undead,
        NE
    }
    public class Factory
    {
        public static IRace CreateInstance(RaceType raceType)
        {
            switch (raceType)
            {
                case RaceType.Human:
                    return new Human();
                case RaceType.Orc:
                    return new Orc();
                case RaceType.NE:
                    return new NE();
                case RaceType.Undead:
                    return new Undead();

                default:
                    throw new Exception("wrong raceType");

            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {

            Human human2 = new Human();
            human2.ShowKing();

            IRace human1 = new Human();
            
            IRace human = Factory.CreateInstance(Factory.RaceType.Human);
            human.ShowKing();

            //Orc orc = new Orc();
            //IRace orc = new Orc();
            IRace orc = Factory.CreateInstance(Factory.RaceType.Orc);
            orc.ShowKing();

            IRace undead = Factory.CreateInstance(Factory.RaceType.Undead);
            undead.ShowKing();
        }
    }
原文地址:https://www.cnblogs.com/vic-tory/p/12147350.html