桥接模式
概述
代码示例
原来的方式
/*
* 汽车
*/
public interface Car {
public void installEngine();
}
public abstract class Bus implements Car {
public abstract void installEngine();
}
public abstract class Jeep implements Car {
public abstract void installEngine();
}
public class Bus2000 extends Bus{
public void installEngine() {
System.out.println("给Bus安装2000cc发动机");
}
}
public class Bus2200 extends Bus {
public void installEngine() {
System.out.println("给Bus安装2200cc发动机");
}
}
public class Jeep2000 extends Jeep{
public void installEngine() {
System.out.println("给Jeep安装2000cc发动机");
}
}
public class Jeep2200 extends Jeep {
public void installEngine() {
System.out.println("给Jeep安装2200cc发动机");
}
}
主函数
public class MainClass {
public static void main(String[] args) {
Car car1 = new Bus2000();
car1.installEngine();
}
}
桥接模式
public abstract class Car {
private Engine engine;
public Car(Engine engine) {
this.engine = engine;
}
public Engine getEngine() {
return engine;
}
public void setEngine(Engine engine) {
this.engine = engine;
}
public abstract void installEngine();
}
public class Bus extends Car{
public Bus(Engine engine) {
super(engine);
}
public void installEngine() {
System.out.print("Bus:");
this.getEngine().installEngine();
}
}
public class Jeep extends Car {
public Jeep(Engine engine) {
super(engine);
}
public void installEngine() {
System.out.print("Jeep:");
this.getEngine().installEngine();
}
}
public interface Engine {
public void installEngine();
}
public class Engine2000 implements Engine {
public void installEngine() {
System.out.println("安装2000cc发动机");
}
}
public class Engine2200 implements Engine{
public void installEngine() {
System.out.println("安装2200cc发动机");
}
}
public class MainClass {
public static void main(String[] args) {
Engine engine2000 = new Engine2000();
Engine engine2200 = new Engine2200();
Car car1 = new Bus(engine2000);
car1.installEngine();
Car car2 = new Bus(engine2200);
car2.installEngine();
Car jeep1 = new Jeep(engine2000);
jeep1.installEngine();
Car jeep2 = new Jeep(engine2200);
jeep2.installEngine();
}
}