顧名思義,裝飾模式就是給一個(gè)對(duì)象增加一些新的功能,而且是動(dòng)態(tài)的,要求裝飾對(duì)象和被裝飾對(duì)象實(shí)現(xiàn)同一個(gè)接口,裝飾對(duì)象持有被裝飾對(duì)象的實(shí)例。
Source類是被裝飾類,Decorator類是一個(gè)裝飾類,可以為Source類動(dòng)態(tài)的添加一些功能,代碼如下:
public interface Sourceable {
public void method();
}
public class Source implements Sourceable {
@Override
public void method() {
System.out.println("the original method!");
}
}
public class Decorator implements Sourceable {
private Sourceable source;
public Decorator(Sourceable source){
super();
this.source = source;
}
@Override
public void method() {
System.out.println("before decorator!");
source.method();
System.out.println("after decorator!");
}
}
測(cè)試類:
public class DecoratorTest {
public static void main(String[] args) {
Sourceable source = new Source();
Sourceable obj = new Decorator(source);
obj.method();
}
}
輸出:
before decorator!
the original method!
after decorator!
裝飾器模式的應(yīng)用場(chǎng)景:
- 需要擴(kuò)展一個(gè)類的功能。
- 動(dòng)態(tài)的為一個(gè)對(duì)象增加功能,而且還能動(dòng)態(tài)撤銷。(繼承不能做到這一點(diǎn),繼承的功能是靜態(tài)的,不能動(dòng)態(tài)增刪)
缺點(diǎn):
產(chǎn)生過(guò)多相似的對(duì)象,不易排錯(cuò)!