定义:把一个类的接口变换为客户端所期待的另一种接口,使原本因接口不兼容而无法在一起工作的两个类能够在一起工作。

       分类:

    类适配器模式:把适配的类的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

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐