源码学习 java-design-patterns
抽象工厂模式是普通工厂模式的扩展,普通工厂模式只生产一种产品,而抽象工厂模式支持多种具有相关联系的产品线,如下图Orc (兽人)和Elf (精灵) 都具有相同组成,由King ,Castle,Army组成.
这张图很明确的表示了各个类和接口之间的关系,首先,有三个基本抽象接口King,Castle,Army.定义了王国的组成的基础,然后KingdomFactory抽象工厂定义了创造王国的方法,具体工厂类通过继承这个接口来创造王国,其中的具体逻辑代码在具体产品类中实现
在什么时候使用抽象工厂模式:
你系统里的产品需要被独立的创造,组装和表现的时候;
你系统里的需要配置许多类型的产品的产品的时候;
属于同一个家族的产品被设计在一起使用,并且你需要去约束他的时候;
你想要把一些产品做成一个公共库类,并且只想对外提供接口,而不提供具体他们的具体实现的时候;
我只是尝试翻译,还是看英文原版比较清晰
-
Applicability: Use the Abstract Factory pattern when
- a system should be independent of how its products are created, composed and represented
- a system should be configured with one of multiple families of products
- a family of related product objects is designed to be used together, and you need to enforce this constraint
- you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations
参考github 地址 https://github.com/keygod/java-design-patterns/tree/master/abstract-factory/src/main/java/com/iluwatar/abstractfactory