1、裝飾者模式優缺點
優點
相對於繼承,靈活性更強。通過把複雜功能切分爲一個個獨立的裝飾器,再動態組合這些裝飾器,創建不同的功能組件,滿足現實多種不同需求。
符合開閉原則:但有新功能添加時,只需要添加新的裝飾器實現類,再通過組合的方式添加這個新裝飾器。
缺點
隨着需求增加,可能不斷增加組合,多層嵌套,增加複雜度,理解、定位難度
2.涉及角色:
2.1 組件接口:定義了全部組件實現類以及所有裝飾者實現的行爲。Component.java
package com.example.testspringboot.test.designmode;
/**組件接口:定義了全部組件實現類以及所有裝飾者實現的行爲
* @author tlj
* @date 2020/1/22
*/
public interface Component {
void operation();
}
2.2具體組件實現類:實現了Component接口 ConcreteComponent.java
package com.example.testspringboot.test.designmode;
/**具體組件實現類:實現了Component接口
* @author tlj
* @date 2020/1/22
*/
public class ConcreteComponent implements Component{
@Override
public void operation() {
System.out.println("一般組件,提供基本功能(待被裝飾)");
}
}
2.3裝飾器:所有裝飾器的父類,它是一個實現了Component接口的抽象類(也可以是一般類).同時持有一個Component對象(組合):Decorator.java
/**裝飾器:所有裝飾器的父類,它是一個實現了Component接口的抽象類(也可以是一般類).同時持有一個Component對象(組合)
* @author tlj
* @date 2020/1/22
*/
public abstract class Decorator implements Component{
private Component component;
public Decorator(Component component){
this.component= component;
}
@Override
public void operation() {
this.component.operation();
}
}
2.4具體的裝飾者實現類,該實現類要向被裝飾者對象添加某些功能 ConcreteDecoratorA.java ConcreteDecoratorB.java
/**具體的裝飾者實現類,該實現類要向被裝飾者對象添加某些功能
* @author tlj
* @date 2020/1/22
*/
public class ConcreteDecoratorA extends Decorator{
public ConcreteDecoratorA(Component component){
super(component);
}
public void operationA(){
System.out.println("裝飾器A擴展的功能");
}
@Override
public void operation() {
System.out.println("裝飾器A 添加新的裝飾");
super.operation();
System.out.println("裝飾器A 添加新的裝飾結束");
}
}
package com.example.testspringboot.test.designmode;
/**具體的裝飾者實現類,該實現類要向被裝飾者對象添加某些功能
* @author tlj
* @date 2020/1/22
*/
public class ConcreteDecoratorB extends Decorator{
public ConcreteDecoratorB(Component component){
super(component);
}
public void operationB(){
System.out.println("裝飾器B擴展的功能");
}
@Override
public void operation() {
System.out.println("裝飾器B 添加新的裝飾");
super.operation();
System.out.println("裝飾器B 添加新的裝飾結束");
}
}
3.測試類
/**
* @author tlj
* @date 2020/1/22
*/
public class MainTest {
public static void main(String[] args) {
ConcreteComponent concreteComponent =new ConcreteComponent();
System.out.println("-----------未裝飾-------------------\n");
concreteComponent.operation();//原來的方法
System.out.println("------------------------------------\n");
test2(concreteComponent) ;
}
private static void test2(ConcreteComponent apple){
ConcreteDecoratorB decoratorB = new ConcreteDecoratorB(apple);
System.out.println("\n-----------裝飾後-------------------\n");
decoratorB.operation();
System.out.println("------------------------------");
}
}
4.UML圖