提供一个接口,让该接口负责创建一系列的”相关或者相互依赖的对象“,无需指定他们具体的类。封装变化点》》
一个游戏:需要路,建筑物,隧道,丛林(这些对象不能再增加,否则不是抽象工厂模式,先看例子,后面解释),这些东西有两个风格1:modern 2:classic抽象工厂应用
abstract class Road{ abstract AAA();}
abstract class Building{abstract BBB(Road r);}
abstract class Tunnel{abstract CCC();}
abstract class Jungle{abstract DDD(Tunnel t);}
abstract class FecilitiesFactory{//
public abstract Road CreatRoad();
public abstract Building CreatBuilding();
public abstract Tunnel CreatTunnel();
public abstract Jungle CreatJungle();
}
面向接口编程;
客户端程序:不涉及具体的代码,全是抽象的
class GameManager {
private FecilitiesFactory fecilitiesFactory;
Road road;
Buieding building;
Tunnel tunnel;
Jungle jungle ;
public GameManger( FecilitiesFactory fecilitiesFactory){ this. fecilitiesFactory= fecilitiesFactory;}
public void BuildFecilities(){
road=fecilitiesFactory.CreatRoad();
building= fecilitiesFactory.CreatBuilding();
tunnel = fecilitiesFactory.CreatTunnel();
jungle = fecilitiesFactory.CreatJungle();
}
public run(){
road.AAA();
building.BBB(road);
tunnel.CCC();
jungle.DDD(tunnel);
}
}
class APP{
GameManager g= new GameManager( 有两种选择1: new ModernFecilitiesFactory() 2 :new ClassicFecilitiesFactory() );
g.BuildFecilities();
g.run();
}
//现代风格具体实现
class ModernRoad extends Road{ AAA(){}; }
class ModernBuilding extends Building{ BBB(Road r){}; }
class ModernTunnel extends Tunnel{ CCC(){}; }
class ModernJungle extends Jungle{ DDD(Tunnel t){}; }
class ModernFecilitiesFactory extends FecilitiesFactory{//
public Road CreatRoad(){ return new ModernRoad(); };
public Building CreatBuilding(){ return new ModernBuilding(); };
public Tunnel CreatTunnel(){ return new ModernTunnel(); };
public Jungle CreatJungle(){ return new ModernJungle(); };
}
//古典风格具体实现
class ClassicRoad extends Road{ AAA(){}; }
class ClassicBuilding extends Building{ BBB(Road r){}; }
class ClassicTunnel extends Tunnel{ CCC(){}; }
class ClassicJungle extends Jungle{ DDD(Tunnel t){}; }
class ClassicFecilitiesFactory extends FecilitiesFactory{//
public Road CreatRoad(){ return new ClassicRoad(); };
public Building CreatBuilding(){ return new ClassicBuilding(); };
public Tunnel CreatTunnel(){ return new ClassicTunnel(); };
public Jungle CreatJungle(){ return new ClassicJungle(); };
}
复杂的代码在GameManager里,当风格发生变化后,不会影响到GameManager里的代码,但如果你的系统变化点在各种物体上,比如又要添加沙漠,就不能再用这个模式啦,要根据你的系统变化的点在哪里,之后决定使用哪种模式。
模式要点:
1:如果没有应对“多系列对象构建”的需求变化,则没有必要使用Abstract Factory模式,这时候使用简单的静态工厂完全可以。
2:“系列对象”指的是这些对象之间有相互依赖,或者作用的关系,例子如游戏开发场景中的道路与房屋的依赖,道路与地道的依赖。
3:Abstract Factory模式主要在于应对“新系列”的需求变动。其缺点在于难以应对“新对象”的需求变动。
4:Abstract Factory模式经常和Abstract Method模式共同组合来应对”对象创建“的需求变化。