zoukankan      html  css  js  c++  java
  • 设计模式系列:简单工厂模式(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();
            }
        }
  • 相关阅读:
    【Python】小技巧
    【Python】内置函数清单
    【Python】序列的方法
    【Python】异常处理
    【Python】函数的参数对应
    【Python】函数对象
    redhat7安装jdk1.7报错/home/renqiwei/jdk1.7/bin/java: /lib/ld-linux.so.2: bad ELF interpreter: No such file or directory
    redhat更换yum源
    python3降级为python2(linux)
    centos安装apt命令
  • 原文地址:https://www.cnblogs.com/vic-tory/p/12147350.html
Copyright © 2011-2022 走看看