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();
            }
        }
  • 相关阅读:
    register变量
    register变量
    const和volatile是否可以同时修饰一个变量?有什么特殊含义?
    关于多态性和虚函数的理解
    static全局变量与普通的全局变量有什么区别
    《c专家编程》学习笔记
    正则表达式入门学习
    mvc ActionResult
    ASP.NET MVC:通过 FileResult 向 浏览器 发送文件(传)
    Asp.net mvc 中的HttpContext
  • 原文地址:https://www.cnblogs.com/vic-tory/p/12147350.html
Copyright © 2011-2022 走看看