`
xieyaxiong
  • 浏览: 39238 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

design pattern——适配器模式

 
阅读更多

 

针对问题:将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。——Gang of Four

 

 

 

 

 

适配器模式结构图:

 



 适配器模式实现代码:

 

/**
 * 现实存在的接口
 * @author bruce
 *
 */
public interface Adaptee {
	
	public void specificRequest();
}




/**
 * 客户期望的接口
 * @author bruce
 *
 */
public interface Target {
	
	public void request();

}





/**
 * 适配器
 * @author bruce
 *
 */
public class Adapter implements Target{
	
	private Adaptee adaptee;//组合现实存在的接口
	
	public Adapter(Adaptee adaptee){
		this.adaptee=adaptee;
	}

	public void request() {
		// TODO Auto-generated method stub
		adaptee.specificRequest();
	}

}






/**
 * 现实存在的类
 * @author bruce
 *
 */
public class ConcreteAdaptee implements Adaptee{

	public void specificRequest() {
		// TODO Auto-generated method stub
	}

}





/**
 * 将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。——Gang of Four
 */

/**
 * 测试
 * @author bruce
 *
 */
public class Client {
	
	public static void main(String[] args) {
		
		Adaptee adaptee=new ConcreteAdaptee(); //根据已存在的类创建对象
		
		Adapter adapter=new Adapter(adaptee);  //继承目标接口并组合已存在的对象来生成适配器
		
		adapter.request(); //可以调用该接口了
	}

}

 

 

 

  • 大小: 7 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics