裝飾器模式 decorator

全部的說明和解釋都在代碼中有註釋來標明java


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("原始類的方法");
	}

}



測試ide

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();
	}
}
相關文章
相關標籤/搜索