设计模式-桥接模式
题目:
用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。
Java代码
package t9; public class Bus implements Vehicle { @Override public void drive() { System.out.print("bus"); } } package t9; public class Car implements Vehicle { @Override public void drive() { System.out.print("car"); } } package t9; public class CementRoad extends Road { public CementRoad(Vehicle vehicle) { super(vehicle); } @Override public void driveOnRoad() { super.vehicle.drive(); System.out.println("行驶在水泥路"); } } package t9; public class main { public static void main(String[] args) { Road road = new CementRoad(new Car()); road.driveOnRoad(); } } package t9; public abstract class Road { protected Vehicle vehicle; public Road(Vehicle vehicle) { this.vehicle = vehicle; } public abstract void driveOnRoad(); } package t9; public class UnpavedRoad extends Road { public UnpavedRoad(Vehicle vehicle) { super(vehicle); } @Override public void driveOnRoad() { super.vehicle.drive(); System.out.println("行驶在沥青路"); } } package t9; public interface Vehicle { public void drive(); }
c++代码
#include <iostream> using namespace std; class AbstractCar { public: virtual void run () = 0; }; class Car:public AbstractCar { public: void run () { cout<<"Car行驶在"; } }; class Bus:public AbstractCar { public: void run () { cout<<"Bus行驶在"; } }; class AbstractRoad { public: AbstractRoad(AbstractCar *car):car(car){} virtual void run() = 0; protected: AbstractCar *car; }; class SpeedWay: public AbstractRoad { public: SpeedWay(AbstractCar *car):AbstractRoad(car){} void run() { car->run(); cout<<" 水泥路"<<endl; } }; class Street: public AbstractRoad { public: Street(AbstractCar *car):AbstractRoad(car){} void run() { car->run(); cout<<" 沥青路"<<endl; } }; main() { AbstractRoad *carOnSpeedway = new SpeedWay(new Car); AbstractRoad *busOnSpeedway = new SpeedWay(new Bus); AbstractRoad *carOnStreet = new Street(new Car); AbstractRoad *busOnStreet = new Street(new Bus); carOnSpeedway ->run(); busOnSpeedway ->run(); carOnStreet ->run(); busOnStreet ->run(); }