桥接模式,按书上的定义是:将抽象部分(手机品牌)和它的实现部分(手机软件)分离,使它们可以独立地变化,也即是手机品牌和软件应该可以独立扩展,互不影响。
例外,把书中的Handsoft改成了接口
UML图
代码结构
public class Client {
public static void main(String[] args) {
HandsetBrand ab = new HandsetBrandN();
ab.setSoft(new HandsetGame());
ab.run();
ab.setSoft(new HandsetAddressList());
ab.run();
ab = new HandsetBrandM();
ab.setSoft(new HandsetGame());
ab.run();
ab.setSoft(new HandsetAddressList());
ab.run();
}
}
public class HandsetAddressList implements HandsetSoft {
@Override
public void run() {
System.out.println("运行手机通讯录");
}
}
public abstract class HandsetBrand {
protected HandsetSoft soft;
public HandsetBrand() {
}
public HandsetBrand(HandsetSoft soft) {
super();
this.soft = soft;
}
public abstract void run();
public HandsetSoft getSoft() {
return soft;
}
public void setSoft(HandsetSoft soft) {
this.soft = soft;
}
}
public class HandsetBrandM extends HandsetBrand {
public HandsetBrandM() {
super();
}
public HandsetBrandM(HandsetSoft soft) {
super(soft);
}
@Override
public void run() {
soft.run();
}
}
public class HandsetBrandN extends HandsetBrand {
public HandsetBrandN() {
super();
}
public HandsetBrandN(HandsetSoft soft) {
super(soft);
}
@Override
public void run() {
soft.run();
}
}
public class HandsetGame implements HandsetSoft {
@Override
public void run() {
System.out.println("运行手机游戏");
}
}
public interface HandsetSoft {
void run();
}
运行结果