【Unity3D与23种设计模式】工厂方法模式(Factory Method)

GoF中定义:

“定义一个可以产生对象的接口,但是让子类决定要产生哪一个类的对象。工厂方法模式让类的实例化程序延迟到子类中实施”

当类的对象产生时,若出现下列情况:

1.需要复杂的流程

2.需要加载外部资源,如从网络、存储设备、数据库

3.有对象上限

4.可重复利用

建议使用工厂方法模式来实现一个工厂类。

public abstract class Product { }

public class ConcreteProductA : Product {
    public ConcreteProductA() {
        Debug.Log("生成对象类A");
    }
}

public class ConcreteProductB : Product {
    public ConcreteProductB() {
        Debug.Log("生成对象类B");
    }
}
interface Creator_GenericMethod {
    Product FactoryMethod<T>() where T : Product,new();
}

public class ConcreteCreator_GenericMethod : Creator_GenericMethod {
    public ConcreteCreator_GenericMethod() {
        Debug.Log("产生工厂:ConcreteCreator_GenericMethod");
    }

    public Product FactoryMethod<T>() where T : Product,new() {
        return new T();
    }
}
//测试类
public class FactoryMethodTest {
    Product theProduct = null;

    void UnitTest() {
        Creator_GenericMethod theCreatorGM = new ConcreteCreator_GenericMethod();
        theProduct = theCreatorGM.FactoryMethod<ConcreteProductA>();
        theProduct = theCreatorGM.FactoryMethod<ConcreteProductB>();
    }
}
//执行结果
产生工厂:ConcreteCreator_MethodType
生成对象类A
生成对象类B

工厂方法模式的优点是

将类群组对线的产生流程整合与同一个类下实现

并提供唯一的方法,让项目内的“对象产生流程”更加独立

文章整理自书籍《设计模式与游戏完美开发》 菜升达 著

原文地址:https://www.cnblogs.com/fws94/p/7218590.html