設(shè)計(jì)模式之橋接模式
來源:程序員人生 發(fā)布時(shí)間:2014-12-17 08:13:44 閱讀次數(shù):2681次
橋接模式(bridge),顧名思義,在兩個(gè)有關(guān)系的物體之間搭建1座橋,二者之間可以相互獨(dú)立,下降耦合,解決了繼承之間的強(qiáng)依賴關(guān)系。
舉個(gè)例子:現(xiàn)在有很多的電子產(chǎn)品,比如手機(jī)、平板等,而又有很多的生產(chǎn)廠商,比如蘋果、小米等。如果使用多重繼承的話,類是以乘積增長的,而如果用橋接模式類是以和的方式增加的。明顯可以下降類的個(gè)數(shù)。
橋接模式是將抽象和實(shí)現(xiàn)解耦,使它們可以獨(dú)立地變化。這里有抽象和實(shí)現(xiàn)兩個(gè)概念,其實(shí)不是說實(shí)現(xiàn)這個(gè)抽象。還是以上面的例子來講明,電子產(chǎn)品是抽象的產(chǎn)品,而生產(chǎn)廠商則是對應(yīng)的實(shí)現(xiàn)。
下面直接給出代碼,寫的比較簡單。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();
}
}
運(yùn)行結(jié)果以下:
Apple's phone
xiaomi's pad
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈