简单的工厂模式实例
//抽象产品类
public interface IOperation  {
    int Cal(int a, int b);
}
//具体产品1
public class AddOperation : IOperation
{
    public int Cal(int a, int b)
    {
        return a + b;
    }
}
//具体产品2
public class MulOperation : IOperation
{
    public int Cal(int a, int b)
    {
        return a * b;
    }
}
//工厂类
public class OperationFactory {

    public IOperation GetOperation(string name)
    {
        switch (name)
        {
            case "add":
                return new AddOperation();
            case "mul":
                return new MulOperation();
            default:
                return null;
        }
    }

}
//使用测试
using UnityEngine;

public class testEasyFactory : MonoBehaviour {

    private IOperation operation;

	void Start () {
        OperationFactory operationFactory = new OperationFactory();
        operation = operationFactory.GetOperation("add");
        int result = operation.Cal(10, 20);
        Debug.Log(result);

        operation = operationFactory.GetOperation("mul");
        result = operation.Cal(10, 20);
        Debug.Log(result);
	}
}

使用工厂类来负责提供给外界需要的具体产品的实例,只需要外界提供需要产品的类型,工厂类维护了所有的产品,从其中找出并提供它的实例出来。


首页 我的博客
粤ICP备17103704号