1.What is Abstract Factory Pattern
Abstract Factory pattern is a super-factory which creates other factories. We also called as factory of factories. It’s’ very much like the Factory Pattern.
2.Simple implement of Abstract Factory Pattern
In Abstract Factory Pattern, an interface is responsible(负责) for creating a factory of related objects without explicitly(明确的) specifying(指定) their classes. Each generated factory can give the objects as per the Factory Pattern.
Now, we will try do create a simple demo to demonstrate(演示) the use of this pattern. We added a new color factory to our last shape factory.
-
Create a class as factory of factories, called it FactoryProducer.
-
Specific factories are the same as before.
UML:
This is my demo’s structure, part of source code and running result: Structure:
Demo code:
package com.yinvoker.simple;
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
//get shape factory
FactoryProducer factoryProducer = new FactoryProducer();
AbstractFactory shapeFactory = factoryProducer.getFactory("shape");
//get shape
Shape shape = shapeFactory.getShape("circle");
shape.draw();
//get color factory
AbstractFactory colorFactory = factoryProducer.getFactory("color");
//get color
Color color = colorFactory.getColor("green");
color.fill();
}
}
Running result:
circle is build
green is filled
Tips: you can get the complete source code and a complex implement from my github, and if you feel it is useful, please star it ?
3.Key Points
- Abstract Factory classes diagram
-
Limitations
-
It isolates(隔离) concrete(具体) classes, and makes exchanging product families easy.
It also promotes consistency among products. But supporting new kinds of products is difficult.
-
-
Applicability
-
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.
-
还想要了解其他设计模式 ?戳这里!
创建模式 | 结构模式 | 行为模式 |
---|---|---|
抽象工厂模式 (Abstract Factory) | 适配器模式 (Adapter) | 责任链模式 (Chain of Responsibility) |
生成器模式 (Builder) | 桥接模式 (Bridge) | 命令模式 (Command) |
工厂方法模式 (Factory Method) | 组合模式 (Composite) | 解释器模式 (Interpreter) |
原型模式 (Prototype) | 修饰模式 (Decorator) | 迭代器模式 (Iterator) |
单例模式 (Singleton) | 外观模式 (Facade) | 中介者模式 (Mediator) |
享元模式 (Flyweight) | 备忘录模式 (Memento) | |
代理模式(Proxy) | 观察者模式(Observer) | |
状态模式 (State) | ||
策略模式 (Strategy) | ||
模板方法模式(Template Method) | ||
访问者模式 (Visitor) |