文章目录
  1. 抽象工厂模式

抽象工厂模式

  • 提供一个创建一系列的相关或相互依赖对象的接口,而无需指定他们具体的类
    Abstract Factory
  • 这就是那个”抽象工厂”,一个手机工厂,创建耳机和屏幕
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public interface PhoneFactory {
EarPhone createEarPhone();
Screen createScreen();
}
public class AppleFactory implements PhoneFactory{
@Override public EarPhone createEarPhone() {
return new LightingPointEar();
}
@Override public Screen createScreen() {
return new FourPointSevenScreen();
}
}
public class SamsungFactory implements PhoneFactory {
@Override public EarPhone createEarPhone() {
return new ThreePointFiveEar();
}
@Override public Screen createScreen() {
return new FivePointFiveScreen();
}
}
  • 相关的产品类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* 屏幕接口
*/
public interface Screen {
float size();
}
public class FivePointFiveScreen implements Screen {
//5.5寸
@Override public float size() {
return 5.5F;
}
}
public class FourPointSevenScreen implements Screen {
//4.7寸
@Override public float size() {
return 4.7F;
}
}
/**
* 耳机接口
*/
public interface EarPhone {
String showInterfaceType();
}
public class LightingPointEar implements EarPhone {
@Override public String showInterfaceType() {
return "Lighting接口的耳机";
}
}
public class ThreePointFiveEar implements EarPhone {
@Override public String showInterfaceType() {
return "3.5mm接口的耳机";
}
}
  • 客户端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class App {
public static void main(String[] args) {
// 抽象工厂模式:提供一个一系列相关或者相互依赖对象的接口,而无需指定他们具体的类
// 比如此例中,苹果手机的工厂返回的耳机与屏幕是相关的lighting与4.7寸
// 增加具体产品工厂较为容易,如XiaomiFactory,而增加一个相关产品较为难,比如增加手机的摄像头这个产品,需要改很多类
PhoneFactory apple=new AppleFactory();
System.out.println(apple.createEarPhone().showInterfaceType());
System.out.println(apple.createScreen().size());
PhoneFactory samsung=new SamsungFactory();
System.out.println(samsung.createEarPhone().showInterfaceType());
System.out.println(samsung.createScreen().size());
}
}
文章目录
  1. 抽象工厂模式