Java-裝飾模式簡單學習__Java

來源:互聯網
上載者:User

根據網易雲課堂Java開發課程學習
- 裝飾模式介紹
裝飾模式以對客戶透明的方式動態給一個對象附加上更多的責任。換言之,客戶並不會感到對象在裝飾前後有什麼不同。裝飾模式可以在不使用創造更多子類的情況下,將對象的功能進行擴充(Java中的IO流就是用的這種模式)。
- 裝飾模式中的角色:
1. 抽象組件(Componet)角色:給出一個抽象介面,以規範準備接收附加責任的對象。
說白了 定義一個介面
2. 具體組件(ConcreteComponent)角色:定義一個將要接收附加責任的類
執行個體化這個介面
3. 裝飾(Decorator)角色:持有一個(Component)對象的執行個體,並定義一個與抽象組件一致的介面。
調用介面,執行個體化一個對象
4. 具體裝飾(ConcreteDecorator)角色:負責給組件對象添加附加的功能。
繼承Decorator,給對象添加功能。 下面是簡單的代碼示範
定義一個介面,介面裡面有一個方法。

package com.test.decorate;public interface Component {    public void doThingA();}

2.執行個體化這個介面

package com.test.decorate;public class ConCreateComponent implements Component {    @Override    public void doThingA() {        System.out.println("do A Thing !");    }}

3.建立一個裝飾類:

package com.test.decorate;public class Decorator implements Component {    private Component component = null;    public Decorator(Component component) {        this.component = component;    }    @Override    public void doThingA() {        component.doThingA();    }}
添加附加功能
package com.test.decorate;public class ConCreateDecorator extends Decorator {    public ConCreateDecorator(Component component) {        super(component);        // TODO Auto-generated constructor stub    }    @Override    public void doThingA() {        super.doThingA();        doThingB();    }    private void doThingB() {        System.out.println("do B thing");    }}

再加一個功能:

package com.test.decorate;public class ConCreateDecorator1 extends Decorator {    public ConCreateDecorator1(Component component) {        super(component);        // TODO Auto-generated constructor stub    }    @Override    public void doThingA() {        super.doThingA();        doThingC();    }    private void doThingC() {        System.out.println("do C thing");    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.