1.定义:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
2.UML类图
3.简单介绍:Component是定义一个对象接口,可以给这些对象动态地添加职责。ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的。至于ConcreteDecorator就是具体的装饰者,起到给Component添加职责的功能。
4.简单代码实现
//装饰者模式抽象类
package com.guo.decoratorPattern;
public abstract class Component {
public abstract void operation();
}
//具体操作的被装饰的类
package com.guo.decoratorPattern;
public class ConcreteComponent extends Component {
@Override
public void operation() {
System.out.println("具体对象的操作。。。");
}
}
//装饰者抽象类
package com.guo.decoratorPattern;
public abstract class Decorator extends Component {
private Component component;
public Decorator(Component component) {
super();
this.component = component;
}
@Override
public void operation() {
if (component != null) {
System.out.println("实际执行的是传入的Component,被装饰的是 :" + component.getClass().getName());
component.operation();
}
}
}
//装饰者实现类
package com.guo.decoratorPattern;
public class DecoratorComponent extends Decorator {
public DecoratorComponent(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
System.out.println("此处可以添加一些装饰类自己的行为。。。");
}
}
//客户端调用示例
package com.guo.decoratorPattern;
public class DecoratorClient {
public static void main(String[] args) {
//实例化一个被装饰者
Component concreteComponent = new ConcreteComponent();
//实例化一个装饰者
Component decoratorComponent = new DecoratorComponent(concreteComponent);
decoratorComponent.operation();
}
}
5.总结