所有的说明和解释都在代码中有注释来标明
package mode.decorator;/*** * 这里定义一个接口,在接口中定义我们要执行的操作。* * 以后所有的装饰器以及我们要装饰的对象都要实现这个接口。有了这样的大前提,我们就可以其用 Sourcable来定义我们的装饰器和要装饰的对象了* * */
public interface Sourcable {public void operation();
}
package mode.decorator;/*** * 所有的装饰器都要实现Sourcable接口,并且要有Sourcable接口的属性以及以Sourcable接口为参数的构造方法* * 在operation中调用传入的Sourcable参数对应的operation方法,当然要加入一些装饰器自己的代码,这些代码就是装饰* * */
public class Decorator1 implements Sourcable {private Sourcable sourcable;public Decorator1(Sourcable sourcable) {super();this.sourcable = sourcable;}@Overridepublic void operation() {System.out.println("第一个装饰器前");this.sourcable.operation();System.out.println("第一个装饰器后");}}
package mode.decorator;/*** * 所有的装饰器都要实现Sourcable接口,并且要有Sourcable接口的属性以及以Sourcable接口为参数的构造方法* * 在operation中调用传入的Sourcable参数对应的operation方法,当然要加入一些装饰器自己的代码,这些代码就是装饰* * */
public class Decorator2 implements Sourcable {private Sourcable sourcable;public Decorator2(Sourcable sourcable) {super();this.sourcable = sourcable;}@Overridepublic void operation() {System.out.println("第二个装饰器前");sourcable.operation();System.out.println("第二个装饰器后");}}
package mode.decorator;/*** * 所有的装饰器都要实现Sourcable接口,并且要有Sourcable接口的属性以及以Sourcable接口为参数的构造方法* * 在operation中调用传入的Sourcable参数对应的operation方法,当然要加入一些装饰器自己的代码,这些代码就是装饰* * */
public class Decorator3 implements Sourcable {private Sourcable sourcable;public Decorator3(Sourcable sourcable) {super();this.sourcable = sourcable;}public void operation() {System.out.println("第三个装饰器前");sourcable.operation();System.out.println("第三个装饰器后");}
}
package mode.decorator;/*** * 最后是要被装饰的对象,直接实现Sourcable接口就行,并且在operation中实现自己的代码* * */
public class Source implements Sourcable {@Overridepublic void operation() {System.out.println("原始类的方法");}}
测试
package mode.decorator;public class Test {public static void main(String[] args) {Sourcable source = new Source();// 装饰类对象Sourcable obj = new Decorator1(new Decorator2(new Decorator3(source)));obj.operation();}
}