java中23种设计模式之10-桥梁模式(bridge pattern)

      【GOF95】在提出桥梁模式的时候指出,桥梁模式的用意是"将抽象化(Abstraction)与实现化(Implementation)脱耦,使得二者可以独立地变化"。这句话有三个关键词,也就是抽象化、实现化和脱耦。

抽象化:

       存在于多个实体中的共同的概念性联系,就是抽象化。作为一个过程,抽象化就是忽略一些信息,从而把不同的实体当做同样的实体对待【LISKOV94】。

实现化:

       抽象化给出的具体实现,就是实现化。

脱耦:     

    所谓耦合,就是两个实体的行为的某种强关联。而将它们的强关联去掉,就是耦合的解脱,或称脱耦。在这里,脱耦是指将抽象化和实现化之间的耦合解脱开,或者说是将它们之间的强关联改换成弱关联。

       将两个角色之间的继承关系改为聚合关系,就是将它们之间的强关联改换成为弱关联。因此,桥梁模式中的所谓脱耦,就是指在一个软件系统的抽象化和实现化之间使用组合/聚合关系而不是继承关系,从而使两者可以相对独立地变化。这就是桥梁模式的用意。

 

以车辆为例,车子分为小车火车,又可分为是运货还是运人。

两两组合就有四种车辆类型。

把一维的继承关系,改为了多维的组合关系,使创建对象更为灵活

 

 

abstract class Vehicle
{
VehicleImpl aVehicleImpl=null;
public Vehicle(VehicleImpl vehicleImpl)
{
aVehicleImpl=vehicleImpl;
}
void transport()
{
aVehicleImpl.transportImpl();
}
}
interface VehicleImpl
{
void transportImpl();
}
class TransportPeople implements VehicleImpl
{
public void transportImpl()
{
System.out.println("people");
}
}

class TransportGoods implements VehicleImpl
{
public void transportImpl()
{
System.out.println("goods");
}
}


class Car extends Vehicle
{

VehicleImpl aVehicleImpl=null;
public Car(VehicleImpl vehicleImpl)
{
super(vehicleImpl);
}
public void transport()
{
System.out.print("car transport ");
super.transport();
}
}

class Train extends Vehicle
{
VehicleImpl aVehicleImpl=null;
public Train(VehicleImpl vehicleImpl)
{
super(vehicleImpl);
}
public void transport()
{
System.out.print("Train transport ");
super.transport();
}
}

public class BridgePatternTest
{
public static void main(String[] args)
{
Vehicle aVehicle=new Car(new TransportPeople());
aVehicle.transport();

aVehicle=new Car(new TransportGoods());
aVehicle.transport();

aVehicle=new Train(new TransportPeople());
aVehicle.transport();

aVehicle=new Train(new TransportGoods());
aVehicle.transport();
}
}

//////////////////////////////////////////////////

输出结果:

car transport people
car transport goods
Train transport people
Train transport goods

posted on 2015-04-01 09:23  wudymand  阅读(147)  评论(0编辑  收藏  举报

导航