zoukankan      html  css  js  c++  java
  • 设计模式系列:工厂方法模式(Factory Method Pattern)

    1.介绍

    工厂方法模式是一种常用的类创建型设计模式,此模式的核心精神是封装类中变化的部分,

    提取其中个性化善变的部分为独立类,通过依赖注入以达到解耦、复用和方便后期维护拓展的目的。

    它的核心结构有四个角色,分别是抽象工厂;具体工厂;抽象产品;具体产品

    2.示例

        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");
            }
        }

    3.工厂方法接口

        public interface IFactoryMethod
        {
            IRace CreateInstance();
        }
        public class HumanFactory : IFactoryMethod
        {
            public IRace CreateInstance()
            {
                return new Human();
            }
        }
        public class NEFactory : IFactoryMethod
        {
            public IRace CreateInstance()
            {
                return new NE();
            }
        }
        public class OrcFactory : IFactoryMethod
        {
            public IRace CreateInstance()
            {
                return new Orc();
            }
        }
        public class UndeadFactory : IFactoryMethod
        {
            public IRace CreateInstance()
            {
                return new Undead();
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
    
                Human human2 = new Human();
                human2.ShowKing();
                //IRace human1 = new Human();
    
                IFactoryMethod humanFactory = new HumanFactory();
                IRace human = humanFactory.CreateInstance();
                human.ShowKing();
                Console.Read();
            }
        }
  • 相关阅读:
    关于TNS_ADMIN环境变量
    Oracle Instant Client的安装和使用
    oracle 网络访问配置tnsnames.ora文件的路径
    sql优化(2)
    sql优化(1)
    mybatis的dao的注解
    配置nginx php上传大文件
    给Linux增加swap内存
    MQ选型之RabbitMQ
    Golang并发模型之Context详解
  • 原文地址:https://www.cnblogs.com/vic-tory/p/12147355.html
Copyright © 2011-2022 走看看