将对象的创建方法封装在专门的工厂类中。比如中国坦克、美国坦克继承自坦克, 中国飞机、美国飞机继承自飞机,但是在实例化的时候想根据阵营来实例化,这时候创建一个中国武器工厂和美国武器工厂,用工厂类中的方法去返回对象,中国工厂返回中国武器,美国工厂返回美国武器。
工厂模式能很好的帮助我们实现从类爆炸到只需几个关键类
细讲:https://www.youtube.com/watch?v=EcFVTgRHJLM&list=PLrhzvIcii6GNjpARdnO4ueTUAVR9eMBpc&index=5
问题背景
在策略模式等模式中,我们注入对象到其中进行处理,换句话说,策略模式等是依赖注入的。
而工厂模式便是创建/实例化注入对象。
换句话说,当我们不知道实例化什么对象 需要一些逻辑来决定实例化对象的时候,就可以用工厂模式。
例子
1.假设有一个生态系统,里面有三个动物:Dog,Cat,Duck.
开始一段时间,三种动物随机生成,即RandomlyCreate()
当生态系统破坏时,三种动物有规律的生成,即RegularlyCreate()
- 从上面例子得出,我们创建的对象是相同的,只是创建的逻辑(算法)不同。
2.假设你在开发一个飞机大战的游戏,现在需要根据关卡等级生成许多的陨石,它们有属性:VelocityX,VelocityY,Size等
当关卡越高,陨石相应属性越大。
- 从上面例子得出,我们创建的对象是相同的,只是创建的子类(或属性)不同。
工厂模式
定义:定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行。
何时使用:我们明确地计划不同条件下创建不同实例时。
如何解决:让其子类实现工厂接口,返回的也是一个抽象的产品。
关键代码:创建过程在其子类执行。
应用实例: 1、您需要一辆汽车,可以直接从工厂里面提货,而不用去管这辆汽车是怎么做出来的,以及这个汽车里面的具体实现。 2、Hibernate 换数据库只需换方言和驱动就可以。
回到第一个例子,它的伪UML应该是这样的:
右边负责创建 How to creat something
左边 what we want to creat
不同场景下你需要不同的逻辑决定实例化什么 这个逻辑可以封装成工厂
换句话说,工厂负责封装逻辑
客户端不必知道怎么构造 为什么构造或需要传递什么参数来构造这个对象
板子
using System;
using System.Collections.Generic;
namespace FactoryMethodPattern
{
//抽象工厂
interface IAbstractAnimalFactory
{
public List<IAbstractAnimal> CreateAnimals();
}
class RandomFactory : IAbstractAnimalFactory
{
public RandomFactory()
{
Console.WriteLine("随机化工厂实例化。");
}
public List<IAbstractAnimal> CreateAnimals()
{
List<IAbstractAnimal> animal = new List<IAbstractAnimal>();
animal.Add(new Dog());
animal.Add(new Duck());
animal.Add(new Dog());
animal.Add(new Cat());
return animal;
}
}
class RegularlyFactory : IAbstractAnimalFactory
{
int a, b, c;
public RegularlyFactory(int dog,int cat,int duck)
{
Console.WriteLine("规律化工厂实例化。");
a = dog;
b = cat;
c = duck;
}
public List<IAbstractAnimal> CreateAnimals()
{
List<IAbstractAnimal> animal = new List<IAbstractAnimal>();
for (int i = 0; i < a; i++) animal.Add(new Dog());
for (int i = 0; i < b; i++) animal.Add(new Cat());
for (int i = 0; i < c; i++) animal.Add(new Duck());
return animal;
}
}
//抽象产品
interface IAbstractAnimal
{
public string show();
}
//具体产品
class Dog : IAbstractAnimal
{
public Dog()
{
Console.WriteLine("生成一条狗");
}
public string show()
{
return "这是一条狗";
}
}
class Cat : IAbstractAnimal
{
public Cat()
{
Console.WriteLine("生成一只猫。");
}
public string show()
{
return "这是一只猫";
}
}
class Duck : IAbstractAnimal
{
public Duck()
{
Console.WriteLine("生成一只鸭。");
}
public string show()
{
return "这是一只鸭";
}
}
class Program
{
static void Main(string[] args)
{
List<IAbstractAnimal> zoo = new List<IAbstractAnimal>();
IAbstractAnimalFactory factory;
factory = new RandomFactory();
zoo.AddRange(factory.CreateAnimals());
factory = new RegularlyFactory(3,3,3);
zoo.AddRange(factory.CreateAnimals());
for(int i= 0; i < zoo.Count; i++)
{
Console.WriteLine("第" + i + "只动物:" + zoo[i].show());
}
}
}
}
根据描述自己写的 希望没有错🙏
游戏实例——角色工厂类
From: 《设计模式与游戏完美开发》