文章目录
  1. 桥接模式

桥接模式

  • 抽象部分与实现部分分离,使他们可以各自独立的变化
    Bridge
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
//手机抽象类
public abstract class AbstractPhone {
protected OperatingSystem os;
public OperatingSystem getOs() {
return os;
}
public void setOs(OperatingSystem os) {
this.os = os;
}
/**
* 开机
*/
public abstract void startUp();
}
//操作系统接口
public interface OperatingSystem {
void loadCore();
void loadMoudleTree();
void done();
}
//IOS实现
public class IOS implements OperatingSystem {
@Override
public void loadCore() {
System.out.println("加载IOS内核");
}
@Override
public void loadMoudleTree() {
System.out.println("加载IOS核心模块树");
}
@Override
public void done() {
System.out.println("Welcome-Assembled in China.Designed by Apple in California!");
}
}
//TouchWiz实现
public class TouchWizAndroid implements OperatingSystem {
@Override
public void loadCore() {
System.out.println("Samsung加载C4核心");
}
@Override
public void loadMoudleTree() {
System.out.println("Samsung预热雷管模块");
}
@Override
public void done() {
System.out.println("Samsung随身Bomb加载完毕");
}
}
//操作系统工厂
public class OSFactory {
private OSFactory(){};
private static class OSFactoryImpl{
static OSFactory factory=new OSFactory();
}
public static OSFactory instance(){
return OSFactoryImpl.factory;
}
public OperatingSystem getOS(String osKey){
if(osKey.equalsIgnoreCase("ios")){
return new IOS();
}
if(osKey.equalsIgnoreCase("samsung")){
return new TouchWizAndroid();
}
return null;
}
}
//IPhone子类实现
public class IPhone extends AbstractPhone{
@Override
public void startUp() {
setOs(OSFactory.instance().getOS("ios"));
System.out.println("硬件自检");
os.loadCore();
os.loadMoudleTree();
os.done();
System.out.println("enjoy!");
}
}
//SamsungPhone子类实现
public class SamsungPhone extends AbstractPhone {
@Override
public void startUp() {
setOs(OSFactory.instance().getOS("samsung"));
System.out.println("检测炸弹状态");
os.loadCore();
os.loadMoudleTree();
os.done();
System.out.println("炸弹启动完毕");
}
}
//客户端
public class App {
public static void main(String[] args) {
/**
* 桥接模式:适用于多个维度的互相变化(本例中:手机的启动,不同操作系统的启动)
* 抽象部分与实现部分分离,使他们可以各自独立的变化
*/
AbstractPhone iphone=new IPhone();
AbstractPhone samsung=new SamsungPhone();
iphone.startUp();
samsung.startUp();
}
}
文章目录
  1. 桥接模式