Java教程

软件设计-桥接模式

本文主要是介绍软件设计-桥接模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

两个维度的桥接模式
用桥接模式实现在路上开车这个问题,其中,车可以是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();
}

 

运行截图

 

这篇关于软件设计-桥接模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!