提供一个接口,让该接口负责创建一系列“相关或都相互依赖的对象”,无需指定它们具体的类。
1、如果没有应对“多系列对象构建”的需求变化,则没有必要使用Abstract Factory模式,这时候使用简单静态工厂完全可以。
2、“系列对象”指的是这些对象之间有相互依赖、或作用的关系,例如游戏开发场景中的“道路”与“房屋”的依赖,“道路”与“地道”的依赖。
3、Abstract Factory模式主要在于应对“新系统”的需求变动。其缺点在于难以应对“新对象”的需求变动。
4、Abstract Factory模式经常和Abstract Method模式共同组合来应对“对象创建”的需求变化。
//==============================================
//道路
abstract class Road
{
}
//房屋
abstract class Building
{
}
//地道
abstract class Tunnel
{
}
//丛林
abstract class Jungle
{
}
//场景工厂
abstract class FacilitiesFactory
{
public abstract Road CreateRoad();
public abstract Building CreateBuilding();
public abstract Tunnel CreateTunnel();
public abstract Jungle CreateJungle();
}
//==============================================
//一组场景,可以根据系统实际的扩展需要,扩展出多组场景;变化点;
class ModernRoad : Road
{
}
class ModernBuilding : Building
{
}
class ModernTunnel : Tunnel
{
}
class ModernJungle : Jungle
{
}
class ModernFacilities : FacilitiesFactory
{
public override Road CreateRoad()
{
return(new ModernRoad());
}
public override Building CreateBuilding()
{
return(new ModernBuilding());
}
public override Tunnel CreateTunnel()
{
return(new ModernTunnel());
}
public override Jungle CreateJungle()
{
return(new ModernJungle());
}
}
//==============================================
//客户程序;稳定点
class GameManager
{
private FacilitiesFactory facilitiesFactory;
private Road road;
private Building building;
private Tunnel tunnel;
private Jungle jungle;
public GameManager(FacilitiesFactory facilitiesFactory)
{
this.facilitiesFactory = facilitiesFactory;
}
public void BuildGameFacilities()
{
road = facilitiesFactory.CreateRoad();
building = facilitiesFactory.CreateBuilding();
tunnel = facilitiesFactory.CreateTunnel();
jungle = facilitiesFactory.CreateJungle();
}
public void Run()
{
//相关操作
}
}
class Test
{
public static void GameMain()
{
GameManager g = new GameManager(new ModernFacilities());
g.BuildGameFacilities();
g.Run();
}
}