public interface Car{
void produce(){
}
}
public class Truck extends Car {
public void produce() {
}
}
public class Bus extends Car {
public void produce() {
}
}
public class FawTruck extends Truck{
public void produce() {
}
}
public class FawBus extends Truck{
public void produce() {
}
}
public class DfmcTruck extends Truck{
public void produce() {
}
}
public class DfmcBus extends Truck{
public void produce() {
}
}
这样问题出现了,假设我们有15中车型,6家汽车制造商,那么我们不得不实现15×6 = 90 种子类车型,这样设计势必造成类的数量翻倍的上升,工作量巨大。Car.java
public abstract class Car {
public Car(Manufacturer lnkManufacturer) {
this.lnkManufacturer = lnkManufacturer;
}
public abstract class Car {
public Car(Manufacturer lnkManufacturer) {
this.lnkManufacturer = lnkManufacturer;
}
public void produce() {
lnkManufacturer.produce();
}
/**
* @directed
*/
Manufacturer lnkManufacturer;
}
public interface Manufacturer {
void produce();
}
public class Truck extends Car {
public Truck(Manufacturer lnkManufacturer) {
super(lnkManufacturer);
}
public void produce() {
lnkManufacturer.produce();
System.out.println("的货车");
}
}
public class Bus extends Car {
public Bus(Manufacturer lnkManufacturer) {
super(lnkManufacturer);
}
public void produce() {
lnkManufacturer.produce();
System.out.println("的公共汽车");
}
}
public class Faw implements Manufacturer {
public void produce() {
System.out.println("一汽制造");
}
}
public class Dfmc implements Manufacturer {
public void produce() {
System.out.println("二汽制造");
}
}
public class Client {
public static void main(String[] argv) {
Car car = new Truck(new Faw());
car.produce();
}
}
桥梁模式由4部分组成:抽象类、抽象类的继承类、实现类、实现类的继承类。桥梁模式的原理图如下:
代码如下:
抽象化角色类,它声明了一个方法operation(),并给出了它的实现。这个实现是通过向实现化对象的委派(调用operationImpl()方法)实现的。
public abstract class Abstraction {
protected Implementor impl;
public Abstraction(Implementor impl){
this.impl = impl;
}
//示例方法
public void operation(){
impl.operationImpl();
}
}
public class RefinedAbstraction extends Abstraction {
public RefinedAbstraction(Implementor impl) {
super(impl);
}
//其他的操作方法
public void otherOperation(){
}
}
实现类:
public abstract class Implementor {
/**
* 示例方法,实现抽象部分需要的某些具体功能
*/
public abstract void operationImpl();
}
实现类的继承类:
public class ConcreteImplementorA extends Implementor {
@Override
public void operationImpl() {
//具体操作
}
}
public class ConcreteImplementorB extends Implementor {
@Override
public void operationImpl() {
//具体操作
}
}