工厂方法

Posted wskxy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了工厂方法相关的知识,希望对你有一定的参考价值。

1.简介

  相比于简单工厂,工厂方法是使用一个工厂类去创建一个对象

  IRace接口和Human类都和上文简单工厂一样

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryMethod
{
    public interface IRace
    {
        void ShowKing();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryMethod
{
    class Human : IRace
    {
        public void ShowKing()
        {
            Console.WriteLine("这里是人类的国王");
        }
    }
}

  然后我们添加一个Human工厂HumanFactory,用这个类来实例化Human

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryMethod
{
    public class HumanFactory
    {
        public IRace CreateInstance()
        {
            return new Human();
        }
    }
}

  Program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            HumanFactory humanFactory = new HumanFactory();
            IRace race1 = humanFactory.CreateInstance();
            race1.ShowKing();
            Console.Read();
        }
    }
}

  从这里看,我们可能会觉得工厂方法只是   

 

以上是关于工厂方法的主要内容,如果未能解决你的问题,请参考以下文章

一. 抽象工厂&工厂方法&简单工厂方法

设计模式之工厂方法和抽象工厂

C++工厂模式(简单工厂工厂方法抽象工厂)

C++工厂模式(简单工厂工厂方法抽象工厂)

VSCode自定义代码片段—— 数组的响应式方法

工厂方法与抽象工厂