将抽象部分与它的实现部分分离,使它们都可以独立地变化。
桥接模式 Bridge
问题:
“Hardening of the software arteries” has occurred by using subclassing of an abstract base class to provide alternative implementations. This locks in compile-time binding between interface and implementation. The abstraction and implementation cannot be independently extended or composed..
意图:
- Decouple an abstraction from its implementation so that the two can vary independently.
- Publish interface in an inheritance hierarchy, and bury implementation in its own inheritance hierarchy.
- Beyond encapsulation, to insulation.
例:比如我想举办一个抽奖活动,奖品分为两类,一类是积分虚拟奖,一类是实体大奖,
两种奖在后台的验证规则一同,实体奖可能会针对用户的中奖记录,合法性,奖池等等进行多项验证,虚拟奖则比较松
对用户来说,只需要抽奖即可,服务端用个连接器,把这两种验证桥接在一起,来看看
代码1:如果是用户只想抽奖,则奖品则是抽象化的东西,先定义奖品
package com.xdnote.DesignPattern.structural.bridge;
public abstract class Prize {
private String name = "";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract boolean validate();
@Override
public String toString() {
return this.name.equals("")?"哎,什么都没中":"恭喜您中得";+this.name;
}
}
代码二:分别定义小奖品与大奖品,以代表服务器对两种不同的奖品有不同的处理方式
public class SmallPrize extends Prize{
@Override
public boolean validate() {
double d=Math.floor(Math.random()*100);
if(d<5){
this.setName("优惠券10元");
return true;
}else if(d>30){
this.setName("金币10个");
return true;
}else if(d>80){
this.setName("金币1个");
return true;
}
return false;
}
}
public class BigPrize extends Prize{
@Override
public boolean validate() {
//大奖来了,这里面验证奖品是否还有
double d=Math.floor(Math.random()*100);
if(d>5){
this.setName("5000000000元");
return true;
}else if(d<30){
this.setName("宝马车");
return true;
}else if(d<80){
this.setName("5块小钱");
return true;
}
return false;
}
}
代码三:桥接-摇奖
public class PrizeBridge {
public static Prize getPrize(){
Prize prize = null;
//这个数本应该是客户端获取之后再传过来的,原始模式DEMO对由于场景对模式稍作改进,
//发挥下思考,真正的摇奖程序,还要载入用户信息,奖项配置等。
double d=Math.floor(Math.random()*100);
if(d<10){
prize = new BigPrize();
}else{
prize = new SmallPrize();
}
prize.validate();
return prize;
}
}
代码四:客户端调用
//对客户端来说,只需要抽奖即可,服务端用个连接器
public static void main(String[] args) {
System.out.println(PrizeBridge.getPrize());
System.out.println(PrizeBridge.getPrize());
System.out.println(PrizeBridge.getPrize());
System.out.println(PrizeBridge.getPrize());
System.out.println(PrizeBridge.getPrize());
System.out.println(PrizeBridge.getPrize());
System.out.println(PrizeBridge.getPrize());
}
小结
桥接模式 Bridge
这个也算不上模式了,实际上就是通过条件判断走到各自的流程,再返回同类型的对象
- 使用频率:
中
使用频率还是蛮高的,就比如例中的抽奖活动。
- 利弊影响:
低
基本上新手都能看的懂,写的出
- 小评:
用前先想想没更好的方案,没有的话才使用。能不用就不用。后期可能会不够灵活。