作用:将抽象部分与它的实现部分分离,使他们都可以独立地变化。注意这里并不是说让抽象类和其派生类分离,实际上是抽象类和它的派生类用来实现自己的对象。在实际的开发系统中,可能有多角度分类,每一种分类都有可能变化,那么就把这种多角度分离出来让他们独立变化,减少他们之间的耦合。
1、桥接模式
1、Implementor(实施者)抽象类
abstract class Implementor{
public abstract void operation();
}
2、Implementor的实现类
class ConcreteImplementorA extends Implementor{
public void operation(){
System.out.println("具体实现A的方法执行");
}
}
class ConcreteImplementorB extends Implementor{
public void operation(){
System.out.println("具体实现B的方法执行");
}
}
3、Abstraction(抽象)抽象类
abstract class Abstraction{
protected Implementor implementor;
public void setImplementor(Implementor implementor){
this.implementor = implementor;
}
public abstract void operation();
}
4、Abstraction的实现类
class RefinedAbstraction extends Abstraction{
public void operation(){
System.out.print("具体的Abstraction");
implementor.operation();
}
}
5、测试和结果
public class Test {
public static void main(String[] args) {
System.out.println("**********************************************");
System.out.println("《大话设计模式》代码样例");
System.out.println();
Abstraction ab;
ab = new RefinedAbstraction();
ab.setImplementor(new ConcreteImplementorA());
ab.operation();
ab.setImplementor(new ConcreteImplementorB());
ab.operation();
System.out.println();
System.out.println("**********************************************");
}
}
结果
2、桥接模式使用
1、软件类型Implementor(实施者)抽象类
//手机软件
abstract class HandsetSoft{
//运行
public abstract void run();
}
2、软件类型Implementor的实现类
//手机游戏
class HandsetGame extends HandsetSoft{
public void run(){
System.out.println("手机游戏");
}
}
//手机通讯录
class HandsetAddressList extends HandsetSoft{
public void run(){
System.out.println("通讯录");
}
}
//手机音乐播放
class HandsetMusicPlay extends HandsetSoft{
public void run(){
System.out.print("音乐播放");
}
}
3、品牌Implementor(实施者)抽象类
//手机品牌
abstract class HandsetBrand{
protected HandsetSoft soft;
//设置手机软件
public void setHandsetSoft(HandsetSoft soft){
this.soft=soft;
}
//运行
public abstract void run();
}
[点击并拖拽以移动]
4、品牌Implementor的实现类
//手机品牌M
class HandsetBrandM extends HandsetBrand{
public void run(){
System.out.print("品牌M");
soft.run();
}
}
//手机品牌N
class HandsetBrandN extends HandsetBrand{
public void run(){
System.out.print("品牌N");
soft.run();
}
}
//手机品牌S
class HandsetBrandS extends HandsetBrand{
public void run(){
System.out.print("品牌S");
soft.run();
}
}
5、测试和结果
public class Test {
public static void main(String[] args) {
System.out.println("**********************************************");
System.out.println("《大话设计模式》代码样例");
System.out.println();
HandsetBrand ab;
ab = new HandsetBrandM();
ab.setHandsetSoft(new HandsetGame());
ab.run();
ab.setHandsetSoft(new HandsetAddressList());
ab.run();
HandsetBrand ab2;
ab2 = new HandsetBrandN();
ab2.setHandsetSoft(new HandsetGame());
ab2.run();
ab2.setHandsetSoft(new HandsetAddressList());
ab2.run();
//向扩展开放,增加的功能
HandsetBrand ab3;
ab3 = new HandsetBrandS();
ab3.setHandsetSoft(new HandsetMusicPlay());
ab3.run();
System.out.println();
System.out.println("**********************************************");
}
}
结果