橋接模式-Bridge(Java實現)

來源:互聯網
上載者:User

標籤:time   open   分享圖片   abstract   action   static   bridge   分享   功能實現   

橋接模式-Bridge

橋樑模式的用意是"將抽象化(Abstraction)與實現化(Implementation)脫耦, 將"類的功能階層" 與 "類的實現階層"分離為兩個獨立的類階層.

類的實現層次介面DisplayImpl介面
public interface DisplayImpl {    void rawOpen();    void rawPrint();    void rawClose();}
StringDisplayImpl類
public class StringDisplayImpl implements DisplayImpl {    private String string;    private int width;    public StringDisplayImpl(String string) {        this.string = string;        this.width = string.getBytes().length;    }    public void rawOpen() {        printLine();    }    public void rawPrint() {        System.out.println("|" + string + "|");    }    public void rawClose() {        printLine();    }    private void printLine() {        System.out.print("+");        for (int i = 0; i < width; i++) {            System.out.print("-");        }        System.out.println("+");    }}
類的功能階層Display類

在功能實現的最高層上關聯了DisplayImpl介面, 在此處進行了橋接.

public class Display {    private DisplayImpl impl;    public Display(DisplayImpl impl) {        this.impl = impl;    }    public void open() {        impl.rawOpen();    }    public void print() {        impl.rawPrint();    }    public void close() {        impl.rawClose();    }    public final void display() {        open();        print();        close();    }}
CountDisplay類

在Display類的基礎上, 進行功能上的擴充. 擴充一個multiDisplay()功能.

public class CountDisplay extends Display {    public CountDisplay(DisplayImpl impl) {        super(impl);    }    public void multiDisplay(int times) {        open();        for (int i = 0; i < times; i++) {            print();        }        close();    }}
Main

用於測試回合

public class Main {    public static void main(String[] args) {        Display d1 = new Display(new StringDisplayImpl("Hello, China."));        Display d2 = new CountDisplay(new StringDisplayImpl("Hello, World."));        CountDisplay d3 = new CountDisplay(new StringDisplayImpl("Hello, Universe."));        d1.display();        d2.display();        d3.display();        d3.multiDisplay(5);    }}

 

橋接模式-Bridge(Java實現)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.