标签:ati cli pac int code new 对象 end http
从用户的角度看:需要知道基本类和装饰类之间的嵌套关系(大致能添加什么装饰功能) 并且这些装饰规则可以互相嵌套 来实现特定顺序的功能。
从实现者的角度看:让这些类真的可以嵌套
package com.dp.decorator1; /** * 定义了一个对象接口 可以给这些对象动态的添加职责 * @author 黄二狗 * */ public interface Component { void operation(); }
package com.dp.decorator1; /** * 被装饰的基础对象 * @author 黄二狗 * */ public class ConcreteComponent implements Component{ @Override public void operation() { System.out.println("基础操作"); } }
package com.dp.decorator1; /** * 实现了Component 从外类来扩展Component类的功能 但对于Component来说,不需要知道Decorator的存在 * @author 黄二狗 * */ public abstract class Decorator implements Component{ private Component component; public void setComponent(Component component) { this.component=component; } @Override public void operation() { if(component!=null) { component.operation(); } } }
package com.dp.decorator1; /** * 具体的装饰对象,起到给Component添加职责的功能 * 装饰类A可以有自己的一些操作 * @author 黄二狗 * */ public class ConcreteDecoratorA extends Decorator{ //装饰类A的一个状态 private String state="concreteDecorator__A"; @Override public void operation() { super.operation(); System.out.println(state); } }
package com.dp.decorator1; public class ConcreteDecoratorB extends Decorator{ @Override public void operation() { super.operation(); addedBehavior(); } //装饰类B public void addedBehavior() { System.out.println("添加一些额外的行为"); } }
package com.dp.decorator1; /** * 用户需要知道基本类和装饰类之间的嵌套关系 * @author 黄二狗 * */ public class Client { public static void main(String[] args) { //基础类 ConcreteComponent concreteComponent=new ConcreteComponent(); //装饰类A ConcreteDecoratorA decoratorA=new ConcreteDecoratorA(); decoratorA.setComponent(concreteComponent); //装饰类B ConcreteDecoratorB decoratorB=new ConcreteDecoratorB(); decoratorB.setComponent(decoratorA); //装饰链的调用 decoratorB.operation(); } }
标签:ati cli pac int code new 对象 end http
原文地址:http://www.cnblogs.com/HJL085/p/6607547.html