软件设计-桥接模式

两个维度的桥接模式
用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。

 

类图

软件设计-桥接模式

 

 

java

package rjsj.no9;

public class Car implements Vehicle{
    @Override
    public void drive() {
        System.out.println("小轿车行驶在");
    }
}
package rjsj.no9;

public class CementRoad extends Road{

    public CementRoad(Vehicle vehicle) {
        super(vehicle);
    }

    @Override
    public void driveOnRoad() {
        super.vehicle.drive();
        System.out.println("水泥路");
    }
}
package rjsj.no9;

public class Client {
    public static void main(String[] args) {
        Road road = new AsphaltRoad(new Car());
        road.driveOnRoad();
        System.out.println("**************************************************");
        Road road1 = new CementRoad(new Bus());
        road1.driveOnRoad();
    }
}
package rjsj.no9;

public abstract class Road {
    protected Vehicle vehicle;
    public Road(Vehicle vehicle){
        this.vehicle = vehicle;
    }
    public abstract void driveOnRoad();
}
package rjsj.no9;

public interface Vehicle {
    public void drive();
}
package rjsj.no9;

public class AsphaltRoad extends Road{
    public AsphaltRoad(Vehicle vehicle) {
        super(vehicle);
    }

    @Override
    public void driveOnRoad() {
        super.vehicle.drive();
        System.out.println("沥青路");
    }
}
package rjsj.no9;

public class Bus implements Vehicle{

    @Override
    public void drive() {
        System.out.println("公交车行驶在");
    }
}

 

C++

#include <iostream>

using namespace std;

class Vehicle{
public:
    virtual void drive(){}
};

class Car:public Vehicle{
public:
    void drive(){
        cout<<"汽车行驶"<<endl;
    }
};

class Bus:public Vehicle{
public:
    void drive(){
        cout<<"公交车行驶"<<endl;
    }
};

class Road{
public:
    Vehicle* vehicle;

    Road(Vehicle* vehicle){
        this->vehicle=vehicle;
    }
    virtual void driveOnRoad(){}
};

class CementRoad:public Road{
public:
    CementRoad(Vehicle* vehicle):Road(vehicle){}

    void driveOnRoad(){
        cout<<"水泥路";
        vehicle->drive();
    }
};

class BituminousRoad:public Road{
    public:
    BituminousRoad(Vehicle* vehicle):Road(vehicle){}
    void driveOnRoad(){
        cout<<"沥青路";
        vehicle->drive();
    }
};


int main(){
    Vehicle* vehicle;
    Car car=Car();
    vehicle=&car;
    CementRoad(vehicle).driveOnRoad();

    Bus bus=Bus();
    vehicle=&bus;
    BituminousRoad(vehicle).driveOnRoad();
}

 

运行截图

软件设计-桥接模式

 

上一篇:The constructor Vehicle(String) is undefined


下一篇:设计模式-七大设计原则