装饰器模式
文章目录
- 装饰器模式
- 定义
- 优缺点
- 优点
- 缺点
- 示例代码
- 示例代码地址
定义
装饰模式(Decorator Pattern)是一种比较常见的模式,其定义如下:
Attach additional responsibilities to an object dynamically keeping the same interface.Decorators provide a flexible alternative to subclassing for extending functionality.(动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活。)
优缺点
优点
- 装饰类和被装饰类可以独立发展,而不会相互耦合
- 装饰模式是继承关系的一个替代方案
- 装饰模式可以动态地扩展一个实现类的功能,这不需要多说,装饰模式的定义就是如此
缺点
- 需要扩展一个类的功能,或给一个类增加附加功能
- 需要动态地给一个对象增加功能,这些功能可以再动态地撤销
- 需要为一批的兄弟类进行改装或加装功能,当然是首选装饰模式
示例代码
-
定义接口或者抽象类
public interface Component {void operate(); }
-
抽象类实现上述接口
public abstract class Decorator implements Component {private Component component;// 通过构造函数传递被修饰者public Decorator(Component component) {this.component = component;}@Overridepublic void operate() {this.component.operate();} }
-
实现类
public class ConcreteComponent implements Component {@Overridepublic void operate() {System.out.println("do something");} }
-
具体实现类
public class ConcreteDecorator1 extends Decorator {public ConcreteDecorator1(Component component) {super(component);}public void method1() {System.out.println("method1修饰");}// 重写父类operate方法@Overridepublic void operate() {this.method1();super.operate();} }
public class ConcreteDecorator2 extends Decorator {public ConcreteDecorator2(Component component) {super(component);}private void method2() {System.out.println("method2修饰");}@Overridepublic void operate() {this.method2();super.operate();} }
-
测试方法
@Test public void test() {Component component = new ConcreteComponent();// 第一次修饰component = new ConcreteDecorator1(component);// 第二次修饰component = new ConcreteDecorator2(component);// 修饰后运行component.operate(); }
运行结果如下:
method2修饰 method1修饰 do something
示例代码地址
https://gitee.com/youxiaxiaomage/java-practices/tree/master/yxxmg-gof-sample/src/main/java/com/yxxmg/gof/structure/decorator