一、模式介绍
装饰器模式,能够为已有功能增加一些新功能,进行增强
装饰器将被装饰对象封装为自己的成员,然后实现被装饰对象的接口方法,
相当于,装饰器代替被装饰对象完成相应的功能,从而达到代码增强的目的
代理模式跟装饰器很像,但目的不是功能增强,而是控制对被代理对象的访问
比如,代理模式可以应用于远程代理,虚拟代理(模拟被代理对象的行为),安全代理(访问权限控制)等
二、基于装饰器模式增强计算器功能
我们继续之前的加法器(大话设计模式 —— 策略模式),编写一个加法装饰器
public class AddDecorator implements Operation{
private AddOperation opt;
public AddDecorator(AddOperation opt) {
this.opt = opt;
}@Override
public int compute(int num1, int num2) {
System.out.println("do something");
return opt.compute(num1, num2);
}}
测试类
public class Main {
public static void main(String[] args) {
Operation opt = new AddDecorator(new AddOperation());
System.out.println(opt.compute(1, 2));
}}