1、简介
使抽象和实现进行解耦,使得二者可以独立变化。通过抽象化和实现化之间的桥接结构实现解耦。
核心代码: 抽象类依赖实现类
一个简单的例子就是轮渡,轮渡公司可以过江,你也要过江,但你又不会游泳,这时就需要有个具体干事的东西,让轮渡公司去选择,你是要乘快艇、小船、还是游艇过江。
这里的游艇就相当于一个桥梁,抽象类和实现类都通过游艇进行关联,由游客选择游艇类型、选择游艇级别和价位。然后游艇由父类游艇管理,游客仅供使用[调用].
2、实现
/**
* 轮船公司接口
* @author Administrator
*/
public abstract class ShippingCompany {
protected Shipping shipping;
public ShippingCompany(Shipping shipping) {
this.shipping = shipping;
}
public abstract void travel();
}
/**
* 轮船接口
* @author Administrator
*/
public interface Shipping {
public void travelRiver(int level, double money);
}
/**
* 邮轮类
* @author Administrator
*/
public class Cruise implements Shipping{
@Override
public void travelRiver(int level, double money) {
System.out.println();
System.out.println(String.format("I'm Cruise level: %d, cost: %f", level, money));
}
}
/**
* 游艇类
* @author Administrator
*/
public class SpeedBoat implements Shipping{
@Override
public void travelRiver(int level, double money) {
System.out.println(String.format("I'm SpeedBoat level: %d, cost: %f", level, money));
}
}
/**
*游客类
*/
public class MrLiu extends ShippingCompany{
private int level;
private double money;
public MrLiu(int level, double money, Shipping shipping) {
super(shipping);
this.level = level;
this.money = money;
}
@Override
public void travel() {
shipping.travelRiver(level, money);
}
}
// Test
int level = 3;
double money = 88888888;
Shipping cruise = new Cruise();
MrLiu liu1 = new MrLiu(level, money, cruise);
Shipping speedBoat = new SpeedBoat();
MrLiu liu2 = new MrLiu(level, money, speedBoat);
liu1.travel();
liu2.travel();