您的位置:首页 > 其它

设计模式 - Factory 模式

2016-02-03 14:20 253 查看
1 问题

1 为了提高内聚(Cohesion)和松耦合(Coupling),我们经常会抽象出一些类的公共 接口以形成抽象基类或者接口。
2 父类中并不知道具体要实例化哪一个具体的子类。


2 功能

1 定义创建对象的接口,封装了对象的创建;
2 使得具体化类的工作延迟到了子类中。


3 代码

不用关心MonoBehaviout,只是在unity引擎的脚本验证的该模式,Start()方法可以看做main()函数

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum ProductType{
A,
B
}

public abstract class Product{
public ProductType type;
public int id;

public abstract void OnUsed();
}

public class ConcreteProductA : Product{

public ConcreteProductA(){
type = ProductType.A;
}

public override void OnUsed ()
{
Debug.Log("..A Is On Useing");
}
}

public class ConcreteProductB : Product{

public ConcreteProductB(){
type = ProductType.B;
}

public override void OnUsed ()
{
Debug.Log("..B Is On Useing");
}

public void OnCustomFunction(){
Debug.Log("..B : this is my special function");
}
}

public interface Factory{

Product OnCreate(ProductType type);
}

public class ConcreteFactory : Factory{

public Product OnCreate(ProductType type){
switch(type){
case ProductType.A:
return new ConcreteProductA();
break;
case ProductType.B:
return new ConcreteProductB();
break;
default:
return null;
break;
}
}
}

public class FactoryDemo : MonoBehaviour {

void Awake(){
Factory factory = new ConcreteFactory();
Product product = factory.OnCreate(ProductType.B);
product.OnUsed();

//      Factory factory = new ConcreteFactory();
//      Product product = factory.OnCreate(ProductType.B);
//      ((ConcreteProductB)product).OnCustomFunction();
}
}


4 总结

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  设计模式