码迷,mamicode.com
首页 > 其他好文 > 详细

装饰器模式 decorator

时间:2015-01-30 23:00:26      阅读:345      评论:0      收藏:0      [点我收藏+]

标签:装饰器模式

所有的说明和解释都在代码中有注释来标明


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;
	}

	@Override
	public 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;
	}

	@Override
	public 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 {

	@Override
	public 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();
	}
}


装饰器模式 decorator

标签:装饰器模式

原文地址:http://blog.csdn.net/u012613903/article/details/43306755

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!