装饰模式:给一个类添加一些额外的职责,并且在添加这些额外的职责时不会控制该类的执行逻辑。
UML类图:
组成部分:
抽象构件:原始的功能接口
具体构件:具体的原始功能类
装饰角色:持有具体构件类的对象,以便执行原有功能
具体装饰:具体扩展的功能在这里
下面看一个人物功能拓展的实例(姓名+爱好):
package com.dashu.decorator; /** * 抽象接口类 * */ public interface Component { public void operation(); }
package com.dashu.decorator; /** * 具体构建 * */ public class ConcreteComponent implements Component { public ConcreteComponent() { } @Override public void operation() { // TODO Auto-generated method stub System.out.println("我的名字叫大树!"); } }
package com.dashu.decorator; /** * 装饰角色,持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口 * */ public class Decorator implements Component { private Component component; public Decorator(Component component) { this.component = component; } @Override public void operation() { // TODO Auto-generated method stub component.operation(); } }
package com.dashu.decorator; public class ConcreteDecorator extends Decorator { public ConcreteDecorator(Component component) { super(component); } @Override public void operation() { // TODO Auto-generated method stub super.operation(); this.addedOperation(); } public void addedOperation() { System.out.println("我爱好是编程!"); } }
package com.dashu.client; import com.dashu.decorator.Component; import com.dashu.decorator.ConcreteComponent; import com.dashu.decorator.ConcreteDecorator; import com.dashu.decorator.Decorator; public class Client { public static void main(String[] args) { Component component=new ConcreteComponent(); Decorator decorator =new ConcreteDecorator(component); //客户端不变,但是已经添加了职责 decorator.operation(); } }