You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
125 lines
2.8 KiB
125 lines
2.8 KiB
6 years ago
|
---
|
||
|
工厂方法模式
|
||
|
---
|
||
|
|
||
|
#### 目录
|
||
|
|
||
|
1. 思维导图
|
||
|
2. 概述
|
||
|
3. 三种实现方式
|
||
|
- 简单工厂模式
|
||
|
- 工厂方法模式
|
||
|
- 抽象工厂模式
|
||
|
|
||
|
#### 思维导图
|
||
|
|
||
|
#### 概述
|
||
|
|
||
|
工厂模式,也是创建型设计模式之一,它提供了一种创建对象的最佳方式。
|
||
|
|
||
|
在任何需要生成复杂对象的地方,都可以使用工厂模式。复杂对象适用工厂模式,用 new 就可以完成创建的对象无需使用工厂模式。
|
||
|
|
||
|
#### 实现方式
|
||
|
|
||
|
##### 简单工厂模式
|
||
|
|
||
|
```java
|
||
|
//定义抽象产品类
|
||
|
public abstract class Product {
|
||
|
public abstract void method();
|
||
|
}
|
||
|
```
|
||
|
|
||
|
```java
|
||
|
//定义具体产品
|
||
|
public class ProductA extends Product {
|
||
|
@Override
|
||
|
public void method() {
|
||
|
System.out.println("产品A");
|
||
|
}
|
||
|
}
|
||
|
public class ProductB extends Product {
|
||
|
@Override
|
||
|
public void method() {
|
||
|
System.out.println("产品B");
|
||
|
}
|
||
|
}
|
||
|
```
|
||
|
|
||
|
```java
|
||
|
//定义一个工厂用来生产产品
|
||
|
public class Factory {
|
||
|
public static Product createProduct(String type) {
|
||
|
switch (type) {
|
||
|
case "A":
|
||
|
return new ProductA();
|
||
|
case "B":
|
||
|
return new ProductB();
|
||
|
default:
|
||
|
return null;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
```
|
||
|
|
||
|
```java
|
||
|
//客户端根据传入的参数生成不同的产品
|
||
|
public class Client {
|
||
|
public static void main(String[] args) {
|
||
|
ProductA productA = (ProductA) Factory.createProduct("A");
|
||
|
if (productA != null) {
|
||
|
productA.method();
|
||
|
} else {
|
||
|
System.out.println("不存在产品A");
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
```
|
||
|
|
||
|
这种写法很简单,但是问题也是显而易见的,每当增加新产品时就得改代码,违反了开闭原则。
|
||
|
|
||
|
##### 工厂方法模式
|
||
|
|
||
|
将具体产品的创建延迟到具体工厂中完成,即由子类来决定应该实例化哪一个类。
|
||
|
|
||
|
```java
|
||
|
//定义一个抽象工厂类
|
||
|
public abstract class Factory {
|
||
|
public abstract Product createProduct();
|
||
|
}
|
||
|
```
|
||
|
|
||
|
```java
|
||
|
//具体的工厂,生产不同的产品
|
||
|
public class FactoryA extends Factory {
|
||
|
@Override
|
||
|
public Product createProduct() {
|
||
|
return new ProductA();
|
||
|
}
|
||
|
}
|
||
|
public class FactoryB extends Factory {
|
||
|
@Override
|
||
|
public Product createProduct() {
|
||
|
return new ProductB();
|
||
|
}
|
||
|
}
|
||
|
```
|
||
|
|
||
|
```java
|
||
|
//用户决定要生产哪个产品
|
||
|
public class Client {
|
||
|
public static void main(String[] args) {
|
||
|
Factory factory = new FactoryA();
|
||
|
ProductA productA = (ProductA) factory.createProduct();
|
||
|
productA.method();
|
||
|
|
||
|
new FactoryB().createProduct().method();
|
||
|
}
|
||
|
}
|
||
|
```
|
||
|
|
||
|
缺点也是显而易见的,一个工厂只能生产一种产品,而且每一个产品都必须对应一个工厂,系统类成对增加,在一定程度上增加了系统的复杂度。
|
||
|
|
||
|
##### 抽象工厂模式
|
||
|
|