Bridge 桥接模式

模式定义
Bridge模式将对象的抽象和行为剥离开来,实现两者之间的松耦合,以便抽象与行为的自由组装。

使用范围

  • 不希望抽象和行为有太多的耦合或关联
  • 对象或类的抽象与行为可以无限制地通过各自的子类来扩充

使用方法
将对象的属性抽象出来为一个abstract的类,同时将它的行为同属性剥离,作为一个自由的接口或抽象类。当客户方需要实现一个对象的属性和行为的时候,可以根据条件自由装配是何种属性、行为。如下图所示,客户类通过调用abstraction类,来实现某个实际对象的某个ConcreteImplementor的行为。

举例说明
假设我们需要玩一个电脑游戏,可以是简单的也可以是复杂的游戏,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机上的联机游戏等等。

类结构示意
该样例的类结构如下:

下载示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值