桥接模式,重点在于“分组抽象”,将两组抽象以聚合/组合的方式联系在一起。这两组抽象都可以有各自的变化
而不会相互干扰。
实现系统可能有多角度分类,每一种分类都有可能变化,那么就把这种多角度分离出来让它们独立变化,减少
它们之间的耦合。————摘自《大话设计模式》
基本结构如下:
①、A组:#########################################
超类 A
A的派生类 a1
A的派生类 a2
……
②、B组:#########################################
超类 B——B中有“超类 A”的对象引用
B的派生类 b1
B的派生类 b2
……
示例代码:
以“手机品牌和手机软件”的关系为例(一种手机可安装好多种软件,一种软件可应用于好多种手机)
①、手机软件组#########################################
/**
* “A组”
* 超类A,手机软件
*/
public abstract class HandsetSoft {
public abstract void run(); //运行软件
}
/**
* “A组”
* A的派生类 a1,手机软件Mp3
*/
public class Mp3 extends HandsetSoft {
@Override
public void run() {
System.out.println("运行Mp3,音乐播放中……");
}
}
/**
* “A组”
* A的派生类 a2,手机游戏
*/
public class Game extends HandsetSoft {
@Override
public void run() {
System.out.println("运行游戏,选择您的职业:1.术士\t2.战士\t3.剑客……");
}
}
②、手机品牌组#########################################
/**
* “B组”
* 超类B,手机品牌
*/
public abstract class HandsetBrand {
protected HandsetSoft soft; //手机软件
public void setSoft(HandsetSoft soft){ //植入软件
this.soft = soft;
}
public abstract void run(); //运行植入的软件
}
/**
* “B组”
* B的派生类 b1,手机品牌Nokia
*/
public class Nokia extends HandsetBrand {
@Override
public void run() {
System.out.println("Nokia手机:");
this.soft.run();
}
}
/**
* “B组”
* B的派生类 b2,手机品牌Appale
*/
public class Apple extends HandsetBrand {
@Override
public void run() {
System.out.println("Apple手机:");
this.soft.run();
}
}
测试方法:
public class Test {
public static void main(String[] args) throws Exception {
HandsetBrand brand;
brand = new Nokia(); //Nokia手机
brand.setSoft(new Mp3());
brand.run();
System.out.println();//换行
brand = new Apple(); //Apple手机
brand.setSoft(new Game());
brand.run();
}
}
运行结果:
Nokia手机:
运行Mp3,音乐播放中……
Apple手机:
运行游戏,选择您的职业:1.术士 2.战士 3.剑客……