CS-Notes/docs/notes/设计模式 - 抽象工厂.md
2019-11-02 22:11:39 +08:00

105 lines
3.0 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 4. 抽象工厂Abstract Factory
### Intent
提供一个接口用于创建 **相关的对象家族**
### Class Diagram
抽象工厂模式创建的是对象家族也就是很多对象而不是一个对象并且这些对象是相关的也就是说必须一起创建出来而工厂方法模式只是用于创建一个对象这和抽象工厂模式有很大不同
抽象工厂模式用到了工厂方法模式来创建单一对象AbstractFactory 中的 createProductA() createProductB() 方法都是让子类来实现这两个方法单独来看就是在创建一个对象这符合工厂方法模式的定义
至于创建对象的家族这一概念是在 Client 体现Client 要通过 AbstractFactory 同时调用两个方法来创建出两个对象在这里这两个对象就有很大的相关性Client 需要同时创建出这两个对象
从高层次来看抽象工厂使用了组合 Cilent 组合了 AbstractFactory而工厂方法模式使用了继承
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/e2190c36-8b27-4690-bde5-9911020a1294.png"/> </div><br>
### Implementation
```java
public class AbstractProductA {
}
```
```java
public class AbstractProductB {
}
```
```java
public class ProductA1 extends AbstractProductA {
}
```
```java
public class ProductA2 extends AbstractProductA {
}
```
```java
public class ProductB1 extends AbstractProductB {
}
```
```java
public class ProductB2 extends AbstractProductB {
}
```
```java
public abstract class AbstractFactory {
abstract AbstractProductA createProductA();
abstract AbstractProductB createProductB();
}
```
```java
public class ConcreteFactory1 extends AbstractFactory {
AbstractProductA createProductA() {
return new ProductA1();
}
AbstractProductB createProductB() {
return new ProductB1();
}
}
```
```java
public class ConcreteFactory2 extends AbstractFactory {
AbstractProductA createProductA() {
return new ProductA2();
}
AbstractProductB createProductB() {
return new ProductB2();
}
}
```
```java
public class Client {
public static void main(String[] args) {
AbstractFactory abstractFactory = new ConcreteFactory1();
AbstractProductA productA = abstractFactory.createProductA();
AbstractProductB productB = abstractFactory.createProductB();
// do something with productA and productB
}
}
```
### JDK
- [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html)
- [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--)
- [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--)
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>