Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
装饰模式可以,可以动态地为一个对象(注意是对象,不是类)添加功能,而不是通过继承来扩展整个类。
LCD- 最低共同点
/**
* Lowest Common Denominator
*/
public interface LCD {
void doIt();
}
核心被包装类
/**
* 被包装的核心类实现LCD
*/
public class Core implements LCD {
@Override
public void doIt() {
System.out.println("Core - I am closed for modification.");
}
}
装饰器基类
/**
* 抽象装饰器也实现LCD("is a LCD"),并且"has a LCD"
*/
public abstract class AbstractDecorator implements LCD {
// has a LCD
private LCD core;
public AbstractDecorator(LCD inner) {
core = inner;
}
public void doIt() {
if (core != null) {
core.doIt();
}
}
}
注意装饰器基类不仅是一个LCD,同时拥有一个LCD。
具体装饰器类
public class DecoratorA extends AbstractDecorator {
public DecoratorA(LCD inner) {
super(inner);
}
public void doIt() {
super.doIt();
doA();
}
private void doA() {
System.out.println("A");
}
}
public class DecoratorB extends AbstractDecorator {
public DecoratorB(LCD inner) {
super(inner);
}
public void doIt() {
super.doIt();
doB();
}
private void doB() {
System.out.println("B");
}
}
public class DecoratorC extends AbstractDecorator {
public DecoratorC(LCD inner) {
super(inner);
}
public void doIt() {
super.doIt();
doC();
}
private void doC() {
System.out.println("C");
}
}
执行
public class Test {
public static void main(String[] args) {
DecoratorA a = new DecoratorA(new Core());
a.doIt();
System.out.println("-----------------------------------");
DecoratorB b = new DecoratorB(a);
b.doIt();
System.out.println("-----------------------------------");
// 一层一层的包装
// 不需要去继承Core类,就可以为其添加额外的功能
DecoratorC c = new DecoratorC(new DecoratorB(new DecoratorA(new Core())));
c.doIt();
}
}
类图
decorator.png参考:
网友评论