现在的位置: 首页 > 综合 > 正文

适配器模式-adapter

2017年12月03日 ⁄ 综合 ⁄ 共 1439字 ⁄ 字号 评论关闭

米店只卖米。

肉店只卖肉。

顾客到米店只能买到米,到肉店只能买到肉。

顾客想到一个店中既买到米,又买到肉,于是就产生了适配器模式来满足顾客的需求。

---------------------------------------------------------------------------------------

定义一个接口MiInterface,定义一个卖米的
方法sellMi()。

/**
* 定义一个接口MiInterface,定义一个卖米的方法。
* @author hsy
*  
*/
public interface MiInterface {
public void sellMi();

}

---------------------------------------------------------------------------------------

定义一个类Mi实现了MiInterface接口,并且实现了卖米
方法sellMi()。

即米店只卖米。

/**
*
* @author hsy
*  
*/
public class Mi implements MiInterface {

public void sellMi() {
   System.out.println(" sell mi");
}

}

---------------------------------------------------------------------------------------

定义一个接口RouInterface,定义一个卖米的方法sellRou()。

/**
*
* @author hsy
*  

*/
public interface RouInterface {
public void sellRou();
}

---------------------------------------------------------------------------------------

定义一个类Rou实现了RouInterface接口,并且实现了卖米
方法sellRou()。

即米店只卖肉。

/**
*
* @author hsy
*  
*/
public class Rou implements RouInterface{

public void sellRou() {
   System.out.println(" sell rou");
  
}

}

---------------------------------------------------------------------------------------

定义一个类MAdapter实现了MiInterface和RouInterface接口,

就可以同时实现卖米sellRou()
和卖肉sellMi()
两个方法。

/**
*
* @author tarena
* 适配器(双向)模式
*/
public class MAdapter
implements MiInterface,RouInterface{
private Mi mi;
private Rou r;
public MAdapter(Mi mi){
   this.mi = mi;
}
public MAdapter(Rou r){
   this.r = r;
}


public void sellMi(){ //米店可以卖肉
   r.sellRou();
}
public void sellRou(){ //肉店可以卖米
   mi.sellMi();
}
public static void main(String[] args) {

}

}


抱歉!评论已关闭.