装饰模式:动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
UML图:
模型类:
Component类:
package com.cnblog.clarck;
/**
* 接口对象,可以动态的给对象添加职责
*
* @author clarck
*
*/
public abstract class Component {
public abstract void Operation();
}
ConcreateComponent类:
package com.cnblog.clarck;
/**
* 具体的装饰对象,起到给Component添加职责
*
* @author clarck
*
*/
public class ConcreateComponent extends Component {
@Override
public void Operation() {
System.out.println("具体对象的操作");
}
}
Decorator类:
package com.cnblog.clarck; /** * 装饰抽象类,继承了Component,从外来类来扩展Component类的功能, * 但对于Component来说是不需要知道Decorator的存在的。 * * @author clarck * */ public abstract class Decorator extends Component { protected Component mComponent; public void setComponent(Component component) { mComponent = component; } @Override public void Operation() { if (mComponent != null) { mComponent.Operation(); } } }
ConcreateDecoratorA类:
package com.cnblog.clarck; /** * 具体的的装饰对象,起到给Component添加职责的作用 * * @author clarck * */ public class ConcreateDecoratorA extends Decorator { private String addedState; @Override public void Operation() { super.Operation(); addedState = "New State"; System.out.println("具体装饰对象A的操作" + addedState); } }
ConcreateDecoratorB类:
package com.cnblog.clarck; /** * 具体的装饰类B * * @author clarck * */ public class ConcreateDecoratorB extends Decorator { @Override public void Operation() { super.Operation(); addedBehaivor(); System.out.println("具体装饰对象B"); } private void addedBehaivor() { //用来区别ConcreateDecoratorA } }
测试类:
package com.cnblog.clarck; /** * 测试类 * * @author clarck * */ public class Test { public static void main(String[] args) { ConcreateComponent component = new ConcreateComponent(); ConcreateDecoratorA decoratorA = new ConcreateDecoratorA(); ConcreateDecoratorB decoratorB = new ConcreateDecoratorB(); decoratorA.setComponent(component); decoratorB.setComponent(decoratorA); decoratorB.Operation(); } }