工厂模式主要是对对象的创建进行控制。
一、简单工厂模式:
根据条件取工厂类
二、工厂方法:定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
public class test : MonoBehaviour
{
// Use this for initialization
void Awake()
{
IFactory operFactory = new AddFactory();
Operation oper = operFactory.CreateOperation();
oper.a = 5;
oper.b = 2;
var result = oper.GetResult();
Debug.Log(result);
}
}
abstract class Operation
{
public double a;
public double b;
public abstract double GetResult();
}
class OperationAdd : Operation
{
public override double GetResult()
{
return a + b;
}
}
class OperationSub : Operation
{
public override double GetResult()
{
return a - b;
}
}
class OperationMul : Operation
{
public override double GetResult()
{
return a * b;
}
}
class OperationDiv : Operation
{
public override double GetResult()
{
return a / b;
}
}
interface IFactory
{
Operation CreateOperation();
}
class AddFactory : IFactory
{
public Operation CreateOperation()
{
return new OperationAdd();
}
}
class SubFactory : IFactory
{
public Operation CreateOperation()
{
return new OperationSub();
}
}
class MulFactory : IFactory
{
public Operation CreateOperation()
{
return new OperationMul();
}
}
class DivFactory : IFactory
{
public Operation CreateOperation()
{
return new OperationDiv();
}
}
三、抽象工厂模式:类似抽象工厂方法,提供一个创建一系列相关或相互依赖对象的接口,无需指定具体的类。
网友评论