桥接模式(bridge),顾名思义,在两个有关系的物体之间搭建1座桥,二者之间可以相互独立,下降耦合,解决了继承之间的强依赖关系。
举个例子:现在有很多的电子产品,比如手机、平板等,而又有很多的生产厂商,比如苹果、小米等。如果使用多重继承的话,类是以乘积增长的,而如果用桥接模式类是以和的方式增加的。明显可以下降类的个数。
桥接模式是将抽象和实现解耦,使它们可以独立地变化。这里有抽象和实现两个概念,其实不是说实现这个抽象。还是以上面的例子来讲明,电子产品是抽象的产品,而生产厂商则是对应的实现。
下面直接给出代码,写的比较简单。UML图自己画吧:
-----------------------------------------------------------
//ElectronicProduct.java
package org.uestc.bridge;
public abstract class ElectronicProduct {
Manufacturer manufacturer;
public ElectronicProduct(Manufacturer manufacturer) {
this.manufacturer = manufacturer;
}
public void GetBrand() {
this.manufacturer.GetBrand();
//System.out.println(")
}
}
class Phone extends ElectronicProduct {
public Phone(Manufacturer manufacturer) {
super(manufacturer);
}
public void GetBrand() {
manufacturer.GetBrand();
System.out.println("phone");
}
}
class Pad extends ElectronicProduct {
public Pad(Manufacturer manufacturer) {
super(manufacturer);
}
public void GetBrand() {
manufacturer.GetBrand();
System.out.println("pad");
}
}
//Manufacture.java
package org.uestc.bridge;
public interface Manufacturer {
void GetBrand();
}
class Apple implements Manufacturer {
@Override
public void GetBrand() {
System.out.print("Apple's ");
}
}
class XiaoMi implements Manufacturer {
@Override
public void GetBrand() {
// TODO Auto-generated method stub
System.out.print("xiaomi's ");
}
}
//client.java
package org.uestc.bridge;
public class Client {
public static void main(String[] args) {
ElectronicProduct iphone = new Phone(new Apple());
iphone.GetBrand();
ElectronicProduct xiaoMiPad = new Pad(new XiaoMi());
xiaoMiPad.GetBrand();
}
}
运行结果以下:
Apple's phone
xiaomi's pad