模式定义
Bridge模式将对象的抽象和行为剥离开来,实现两者之间的松耦合,以便抽象与行为的自由组装。
使用范围
- 不希望抽象和行为有太多的耦合或关联
- 对象或类的抽象与行为可以无限制地通过各自的子类来扩充
使用方法
将对象的属性抽象出来为一个abstract的类,同时将它的行为同属性剥离,作为一个自由的接口或抽象类。当客户方需要实现一个对象的属性和行为的时候,可以根据条件自由装配是何种属性、行为。如下图所示,客户类通过调用abstraction类,来实现某个实际对象的某个ConcreteImplementor的行为。
![](http://www.zigzagsoft.net/main/designpattern_image/bridge-pattern.jpg)
举例说明
假设我们需要玩一个电脑游戏,可以是简单的也可以是复杂的游戏,SimpleGame/BigGame,玩家也可以是Linux或者Windows上的用户。此时,就有多种组合的机会,Linux上的 SimpleGame,Linux上的BigGame,Windows上的SimpleGame,以及Windows上的BigGame。因此,只要将 Game这个对象抽象出来,同时,将Linux和Windows上的行为剥离出来,就能实现自由组合。
public abstract class Game {
protected String gameName;
protected Player playImp = null;
public void setPlayer(Player player) {
this.playImp = player;
}
public void start() {
playImp.beginPlay(this);
}
}
具体的Game有如下两种:
public class SmallGame extends Game {
public void start() {
gameName = "small game";
super.start();
}
}
和
public class BigGame extends Game {
public void start() {
gameName = "small game";
super.start();
}
}
同时,剥离行为Player:
public abstract class Player {
public abstract void beginPlay(Game game);
}
同样,在Linux和Windows上的Concrete行为,可以定义如下:
public class LinuxPlayer extends Player {
public LinuxPlayer() {
System.out.println("Linux player is playing ");
}
public void beginPlay(Game game) {
System.out.println(game.gameName);
}
}
public class WindowsPlay extends Player {
public WindowsPlay() {
System.out.println("Windows player is playing ");
}
public void beginPlay(Game game) {
System.out.println(game.gameName);
}
}
最后,客户类可以自由组合对象的属性和行为,比如:
public class Client {
public static void main(String args[]) {
Game gm = new SmallGame();
gm.setPlayer(new LinuxPlayer());
gm.start();
}
}
同样道理,只要继承或实现各自的属性类以及行为类,可以创造出更多的组合,比如Apple机上的联机游戏等等。
类结构示意
该样例的类结构如下:
![](http://www.zigzagsoft.net/main/designpattern_image/bridge-example.jpg)
下载示例