設計模式理解(八)結構型——裝飾者模式(記得加上UML圖 --- 未完)

一段時間沒寫,又忘了,暈。。。設計模式這種東西必定要常常用。設計模式

裝飾者模式(Decorator)用於動態地給一個對象增長一些額外的職責,就增長功能來講,他比生成子類更爲靈活。this

裝飾者模式的原則是:spa

  1. 能用組合就用組合,而不用繼承設計

  2. 在運行時才肯定添加的方法code

UML類圖:component

 

/* -------------------------對象

 * ------- 分割線 ----------blog

 * ------------------------- */繼承

代碼:接口

///Component:
///定義一個對象接口,能夠給這些對象動態地添加職責。
public interface Component{
    void operation();
}
///Concrete Component:
///定義一個對象,能夠給這個對象添加一些職責。
public class ConcreteComponent implements Component
{
    public void operation()
    {
        // Write your code here
    }
}
///  裝飾者父類, 默認直接調用component的方法
public class Decorator implements Component{
    public Decorator(Component component){
        this.component = component;
    }
    public void operation(){
        component.operation();
    }
    private Component component;
}
/// 之後的裝飾者子類,重寫父類的operator()方法,在裏面加入本身的東西便可。

 

 

/*  --- 完 --- */

相關文章
相關標籤/搜索