桥模式按类型不同实现

时间:2017-05-23 08:36:40

标签: design-patterns bridge

我搜索了桥梁模式的示例,以下示例很好地解释了设计模式,但我对此示例有一个问题。例如,如果手动齿轮handleGear方法与Car and Truck或auto gear handle不同,我应该做什么?汽车还是卡车?你能否提供这种情况的示例代码?

/* Implementor interface*/
interface Gear{
    void handleGear();
}

/* Concrete Implementor - 1 */
class ManualGear implements Gear{
    public void handleGear(){
        System.out.println("Manual gear");
    }
}
/* Concrete Implementor - 2 */
class AutoGear implements Gear{
    public void handleGear(){
        System.out.println("Auto gear");
    }
}
/* Abstraction (abstract class) */
abstract class Vehicle {
    Gear gear;
    public Vehicle(Gear gear){
        this.gear = gear;
    }
    abstract void addGear();
}
/* RefinedAbstraction - 1*/
class Car extends Vehicle{
    public Car(Gear gear){
        super(gear);
        // initialize various other Car components to make the car
    }
    public void addGear(){
        System.out.print("Car handles ");
        gear.handleGear();
    }
}
/* RefinedAbstraction - 2 */
class Truck extends Vehicle{
    public Truck(Gear gear){
        super(gear);
        // initialize various other Truck components to make the car
    }
    public void addGear(){
        System.out.print("Truck handles " );
        gear.handleGear();
    }
}
/* Client program */
public class BridgeDemo {    
    public static void main(String args[]){
        Gear gear = new ManualGear();
        Vehicle vehicle = new Car(gear);
        vehicle.addGear();

        gear = new AutoGear();
        vehicle = new Car(gear);
        vehicle.addGear();

        gear = new ManualGear();
        vehicle = new Truck(gear);
        vehicle.addGear();

        gear = new AutoGear();
        vehicle = new Truck(gear);
        vehicle.addGear();
    }
}

1 个答案:

答案 0 :(得分:0)

在一个好的设计中,Gear不应该关心外部环境。因此,它应该采取行动,无论它安装在哪个Vehicle

你可以写点像

class SportCar extens Car {
  public SportCar (Gear gear){
    if (gear instanceof SportCarGear) {
      super(gear);
    } else {
      super(new SportCarGear());
      // throwing an exception is even worse
    }
}

完全错误并且违反了太多内容:

  • 来自用户的期望:Car bolid = new SportCar(new TruckGear());将无法按预期行事。可以说这违反了Liskov原则,但我不确定它是否适用
  • 更高的耦合:现在SportCar'知道'Gear
  • 的特定实现
  • 如果您有CarGearTruckGear等,则设计与 Bridge 提供的设计不同

您使用Bridge来实现VehicleGear的实现。在这种情况下,Gear对于Vehicle的不同实现应该有不同的期望是......非常奇怪。