淺談JAVA設計模式之——裝飾模式(Decorator)

來源:互聯網
上載者:User

標籤:java設計模式   decorator   

轉載請註明出處:http://blog.csdn.net/l1028386804/article/details/45464445
一、概述

動態地給一個對象添加一些額外的職責。就增加功能來說,Decorator模式相比產生子類更為靈活。

二、適用性

1.在不影響其他對象的情況下,以動態、透明的方式給單個對象添加職責。

2.處理那些可以撤消的職責。

3.當不能採用產生子類的方法進行擴充時。

三、參與者

1.Component 定義一個對象介面,可以給這些對象動態地添加職責。

2.ConcreteComponent 定義一個對象,可以給這個對象添加一些職責。

3.Decorator 維持一個指向Component對象的指標,並定義一個與Component介面一致的介面。

4.ConcreteDecorator 向組件添加職責。

四、類圖

五、樣本

Component

package com.lyz.design.decorator;/** * 定義Component介面Person * @author liuyazhuang * */public interface Person {    void eat();}

ConcreteComponent

package com.lyz.design.decorator;/** * Person介面的實作類別Man * @author liuyazhuang * */public class Man implements Person {public void eat() {System.out.println("男人在吃");}}

Decorator

package com.lyz.design.decorator;/** * Decorator抽象類別實現Person介面 * @author liuyazhuang * */public abstract class Decorator implements Person {    protected Person person;        public void setPerson(Person person) {        this.person = person;    }        public void eat() {        person.eat();    }}

ConcreteDecorator

package com.lyz.design.decorator;/** * Decorator的子類 * @author liuyazhuang * */public class ManDecoratorA extends Decorator {    public void eat() {        super.eat();        reEat();        System.out.println("ManDecoratorA類");    }    public void reEat() {        System.out.println("再吃一頓飯");    }}

package com.lyz.design.decorator;/** * Decorator的子類 * @author liuyazhuang * */public class ManDecoratorB extends Decorator {        public void eat() {        super.eat();        System.out.println("===============");        System.out.println("ManDecoratorB類");    }}

Test

package com.lyz.design.decorator;/** * 測試類別 * @author liuyazhuang * */public class Test {    public static void main(String[] args) {        Man man = new Man();        ManDecoratorA md1 = new ManDecoratorA();        ManDecoratorB md2 = new ManDecoratorB();                md1.setPerson(man);        md2.setPerson(md1);        md2.eat();    }}

result
男人在吃再吃一頓飯ManDecoratorA類===============ManDecoratorB類


淺談JAVA設計模式之——裝飾模式(Decorator)

聯繫我們

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