装饰器模式
装饰器模式允许向一个现有的对象添加新的功能,同时又不改变原始结构。装饰类是现有类的一个包装。
基础接口:
1 public interface Component { 2 3 void operation(); 4 }
原始类:
1 public class ConcreComponent implements Component { 2 3 @Override 4 public void operation() { 5 System.out.println("concre component"); 6 } 7 }
抽象装饰器:
1 public abstract class BaseDecorator implements Component { 2 3 public Component component; 4 5 public BaseDecorator(Component component) { 6 this.component = component; 7 } 8 9 @Override 10 public void operation() { 11 this.component.operation(); 12 } 13 }
自定义装饰器:
1 public class ConcreDecorator extends BaseDecorator { 2 3 public ConcreDecorator(Component component) { 4 super(component); 5 } 6 7 @Override 8 public void operation() { 9 this.component.operation(); 10 decorateMethod(); 11 } 12 13 public void decorateMethod() { 14 System.out.println("decorateMethod"); 15 } 16 }
测试方法:
public class Main { public static void main(String[] args) { Component concreComponent = new ConcreComponent(); ConcreDecorator concreDecorator = new ConcreDecorator(concreComponent); concreDecorator.operation(); } }