设计模式(五)适配器模式(结构型)

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

       分类:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值