設計模式(五)適配器模式(結構型)

       定義:把一個類的接口變換爲客戶端所期待的另一種接口,使原本因接口不兼容而無法在一起工作的兩個類能夠在一起工作。

       分類:

    類適配器模式:把適配的類的API轉換成目標類的API。(繼承需要適配的類)

    對象適配器模式:把適配的類的API轉換成目標類的API。(委派需要適配的類)

       組成:

    目標(Target)角色:所期待得到的結果,目標接口

    客戶(Client)角色:調用目標接口

    被適配(Adapee)角色:需要適配的接口

    適配器(Adaper)角色:適配器把源接口轉換成目標接口。


     類適配器模式

     目標角色類     

/**
 * 目標角色類
 * @author Jeff
 */
public interface Target {
	
	void hello();
	
	void world();

}

     源角色類 

/**
 * 源角色類
 * @author Jeff
 *
 */
public class Adapee {
	
	public void hi(){
		System.out.println("hi!");
	}
	
	public void world(){
		System.out.println("world!");
	}

}
    適配器類 
/**
 * 適配器類
 * @author Jeff
 *
 */
public class Adaper extends Adapee implements Target{
	
	public void hello(){
		System.out.println("hello!");
	}

}
    客戶端類 
/**
 * 客戶端類
 * @author Jeff
 *
 */
public class Client {
	
	public static void main(String[] args){
		Target target = new Adaper();
		target.hello();
		target.world();
	}
}

     對象適配器模式

     目標角色類  

/**
 * 目標角色類
 * @author Jeff
 */
public interface Target {
	
	void hello();
	
	void world();

}

     源角色類 

/**
 * 源角色類
 * @author Jeff
 *
 */
public class Adapee {
	
	public void hi(){
		System.out.println("hi!");
	}
	
	public void world(){
		System.out.println("world!");
	}

}

       適配器類 

/**
 * 適配器類
 * @author Jeff
 *
 */
public class Adaper implements Target{
	
	private Adapee adapee;
	
	public Adapee getAdapee() {
		return adapee;
	}

	public void setAdapee(Adapee adapee) {
		this.adapee = adapee;
	}

	public void hello(){
		System.out.println("hello!");
	}
	
	public void world(){
		this.getAdapee().world();
	}

}
    客戶端類
/**
 * 客戶端類
 * @author Jeff
 *
 */
public class Client {
	
	public static void main(String[] args){
		Adapee adapee = new Adapee();
		Adaper adaper = new Adaper();
		adaper.setAdapee(adapee);
		Target target = adaper;
		target.hello();
		target.world();
	}
}

       參考文章:http://blog.csdn.net/hguisu/article/details/7527842

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章