创建型设计模式-抽象工厂方法模式
模式简介
为创建一组相关或者是相互依赖的对象提供一个接口,而不需要指定他们的具体类
使用场景
一个对象族有相同的约束时就可以使用抽象工厂模式。例如:Android、iOS、Windows phone 下都有打电话、发短信功能软件,但是它们所处的操作系统不一样,即便是同一家公司出品的软件,其代码所实现的逻辑也是不同的,这个时候就可以考虑使用抽象工厂方法模式来产生Android、iOS、Windows phone 下的短信软件和电话软件
简单实现
抽象车场类
1
2
3
4
5
6
7
8
9
|
/* 抽象车场类*/
public abstract class CarFactory {
//生产轮胎
public abstract ITire creatTire();
//生产发动机
public abstract IEngine creatEngine();
//生产制动系统
public abstract IBrake creatBrake();
}
|
轮胎相关类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public interface ITire {
//轮胎
void tire();
}
public class NormalTire implements ITire {
public void tire() {
System.out.println("普通轮胎");
}
}
public class SUVTire implements ITire {
public void tire() {
System.out.println("越野轮胎");
}
}
|
制动系统相关类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public interface IBrake {
//制动系统
void brake();
}
public class NomalBrake implements IBrake {
public void brake() {
System.out.println("普通制动");
}
}
public class SeriorBrake implements IBrake {
public void brake() {
System.out.println("高级制动");
}
}
|
发动机相关类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public interface IEngine {
//发动机
void engine();
}
public class DomesticEngine implements IEngine {
public void engine() {
System.out.println("国产发动机");
}
}
public class ImportEngine implements IEngine {
public void engine() {
System.out.println("进口发动机");
}
}
|
Q3工厂类
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class Q3Factory extends CarFactory {
public ITire creatTire() {
return new NormalTire();
}
public IEngine creatEngine() {
return new DomesticEngine();
}
public IBrake creatBrake() {
return new NomalBrake();
}
}
|
Q7工厂类
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class Q7Factory extends CarFactory {
public ITire creatTire() {
return new SUVTire();
}
public IEngine creatEngine() {
return new ImportEngine();
}
public IBrake creatBrake() {
return new SeriorBrake();
}
}
|
测试主函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public class Client {
public static void main(String[] args) {
//构造一个生产Q3的工厂
CarFactory factoryQ3=new Q3Factory();
factoryQ3.creatTire().tire();
factoryQ3.creatBrake().brake();
factoryQ3.creatEngine().engine();
System.out.println("--------------------------");
//构造一个生产Q7的工厂
CarFactory factoryQ7=new Q7Factory();
factoryQ7.creatEngine().engine();
factoryQ7.creatBrake().brake();
factoryQ7.creatTire().tire();
}
}
|
执行结果

小结
上面我们只是模拟了2款车型,如果我们此时再增加车型的话,就要增加相应的发动机、制动系统和轮胎类。这里其实就是抽象工厂方法模式的弊端,那就是类的陡增,如果工厂类过多,势必导致类文件增多。权衡使用~
优点
分离接口与实现,客户端使用抽象工厂来创建需要的对象,而客户端根本就不知道具体的实现是谁,客户端只是面向产品的接口编程而已,使其从具体的产品实现中解耦,同时基于接口与实现的分离,使抽象该工厂方法模式在切换产品类是更加灵活、容易
缺点
- 类文件的大量增加
- 不太容易拓展新的产品类:因为每拓展一次都要修改抽象工厂,那么全部的具体实现类都要进行更改
Android源码中的应用:mediaplayer 类
实际开发中的应用:主题更改