1.1 模式概念:
- 创建型模式。
- 封装和管理对象的创建。
- 创建过程一一对应。
1.2 模式结构:
-
IProduct(抽象产品)
-
CubeProduct,SphereProduct,CapsuleProduct等(具体产品)
-
IFactory(抽象工厂)
-
CubeFactory,SphereFactory,CapsuleFactory等(具体工厂)
1.3 代码示例:
public interface IProductMethod
{
/// <summary>
/// 实例化
/// </summary>
object InstantiateObject();
}
public class CubeProduct : IProductMethod
{
public object InstantiateObject()
{
GameObject prefab = LoadAssetBundleManager.LoadAssetBundle(Application.streamingAssetsPath + "/prefab", "Cube");
return prefab;
}
}
public class SphereProduct : IProductMethod
{
public object InstantiateObject()
{
GameObject prefab = LoadAssetBundleManager.LoadAssetBundle(Application.streamingAssetsPath + "/prefab", "Sphere");
return prefab;
}
}
public class CapsuleProduct : IProductMethod
{
public object InstantiateObject()
{
GameObject prefab = LoadAssetBundleManager.LoadAssetBundle(Application.streamingAssetsPath + "/prefab", "Capsule");
return prefab;
}
}
public class CylinderProduct : IProductMethod
{
public object InstantiateObject()
{
GameObject prefab = LoadAssetBundleManager.LoadAssetBundle(Application.streamingAssetsPath + "/prefab", "Cylinder");
return prefab;
}
}
public interface IFactoryMethod
{
IProductMethod CreateProduct();
}
public class CubeFactory : IFactoryMethod
{
public IProductMethod CreateProduct()
{
return new CubeProduct();
}
}
public class SphereFactory : IFactoryMethod
{
public IProductMethod CreateProduct()
{
return new SphereProduct();
}
}
public class CapsuleFactory : IFactoryMethod
{
public IProductMethod CreateProduct()
{
return new CapsuleProduct();
}
}
public class CylindereFactory : IFactoryMethod
{
public IProductMethod CreateProduct()
{
return new CylinderProduct();
}
}
public class FactoryMethodDemo : MonoBehaviour
{
void Start()
{
//生成Cube
GameObject Cube = new CubeFactory().CreateProduct().InstantiateObject() as GameObject;
GameObjectPool.Instance.CreateObject(Cube.name, Cube, null, new Vector3(-3, 0, 0));
//生成Sphere
//GameObject Sphere = new SphereFactory().CreateProduct().InstantiateObject() as GameObject;
//GameObjectPool.Instance.CreateObject(Sphere.name, Sphere, null, new Vector3(-1, 0, 0));
//生成Capsule
//GameObject Capsule = new CapsuleFactory().CreateProduct().InstantiateObject() as GameObject;
//GameObjectPool.Instance.CreateObject(Capsule.name, Capsule, null, new Vector3(1, 0, 0));
//生成Cylinder
//GameObject Cylinder = new CylindereFactory().CreateProduct().InstantiateObject() as GameObject;
//GameObjectPool.Instance.CreateObject(Cylinder.name, Cylinder, null, new Vector3(3, 0, 0));
}
}
1.4 模式分析:
- 产品的增加或者删除不会影响到其他产品。
- 职责明确,快速定位。
- 符合开闭原则。
1.5 应用场景:
- 创建繁多种类的物品。
1.6 总结:
- 用户只需要知道具体工厂的名称就可得到所要的产品,无须知道产品的具体创建过程。
- 灵活性增强,对于新产品的创建,只需多写一个相应的工厂类。
- 典型的解耦框架。高层模块只需要知道产品的抽象类,无须关心其他实现类,满足迪米特法则、依赖倒置原则和里氏替换原则。