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();
            }
        }
  • 相关阅读:
    kafka常见命令
    hive创建分区表
    java正则表达式过滤html标签
    Jquery 获取地址位置
    时间插件之My97DatePickerBeta
    Idea根据表自动生成实体
    验证码图片(个性化+)
    QQ第三方登录
    生成二维码
    Ehcache 的简单实用 及配置
  • 原文地址:https://www.cnblogs.com/vic-tory/p/12147355.html
Copyright © 2011-2022 走看看