Bridge模式
意图:将一组实现部分从另一组使用它们的对象中分离出来。
问题:一个抽象类的派生类必须使用多种实现部分,但又并不能引起数量的爆炸。
解决方案:为所有的实现部分定义一个接口,让抽象类的所有派生类使用这个接口。
参与者与协作者:Abstraction为正在实现的对象定义接口。Implementor为特定的实现部分类定义接口。Abstraction的派生类使用Implementor的派生类,而不必知道自己使用的特定ConcreteImplementor。
效果:“实现部分与使用它的对象的分离”增加了灵活性。客户对象不需要了解实现问题。
实现:
1.将实现部分封装在一个抽象类。
2.在被实现的抽象类部分基类中包含一个实现部分基类的句柄
注意:在Java中,你可以在实现部分使用接口来代替抽象类。
桥模式其实就是将多对多关系的通过桥联系起来,而这个桥就是用两个abstract连接,再分别实现子类的过程
注意,这里一直使用的implement interface实现,其实用abstract就可以了,只是implement暴露的更少
这里举的例子是,交通工具与发动机类型的一种多对多关系,汽车飞机都可以用汽油机或者电机,这里使用的就是桥模式
通过两个抽象的Vehicle 和 Engine链接
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package bridge;
/**
*
* @author blacklaw
*/
public class Bridge {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
new Car(0).Go();
new Car(1).Go();
new Plane(0).Go();
new Plane(1).Go();
}
}
/**
* 交通工具的一种,汽车
* @author blacklaw
*/
class Car extends Vehicle{
public Car(int engineID) {
super.init(engineID);
}
public void Go(){
System.out.print("I'm a car ");
super.Go();
}
}
/**
* 交通工具的一种,飞机
* @author blacklaw
*/
class Plane extends Vehicle{
public Plane(int engineID) {
super.init(engineID);
}
public void Go(){
System.out.print("I'm a plane ");
super.Go();
}
}
/**
* 交通工具,抽象类
* @author blacklaw
*/
abstract class Vehicle{
//用abstract和interface的效果一样,只是interface暴露的更少
private EngineInterface engine;
//private Engine engine2;
public void init(int engineID){
switch(engineID){
case 0:engine = new petrolEngine();break;
case 1:engine = new electroEngine();break;
}
}
public void Go(){
engine.Go();
}
}
/**
* 发动机接口
* @author blacklaw
*/
interface EngineInterface{
public void Go();
}
/**
* 发动机抽象类
* @author blacklaw
*/
abstract class Engine implements EngineInterface{
@Override
public void Go() {
}
}
/**
* 汽油发动机
* @author blacklaw
*/
class petrolEngine extends Engine{
@Override
public void Go() {
System.out.println("with petrolEngine go");
}
}
/**
* 电动发动机
* @author blacklaw
*/
class electroEngine extends Engine{
@Override
public void Go() {
System.out.println("with electroEngine go");
}
}