`
hanlingbo2008
  • 浏览: 79974 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

适配器模式(Adapter)

阅读更多

6.  适配器模式(Adapter)

 

     模式所设计的角色有:

  • 目标角色(Target): 这里是所期待得到的接口。此目标不可以是类。
  • 源角色(Adaptee): 现有需要适配的具体类,要包装类中的方法。
  • 适配器(Adapter): 把源接口转换成目标接口。适配器必须是具类。                                                          

      例子: 请做一个Kittie的具体类,并实现miao(), catchRat(), run() , sleep()方法,在做一个接口Puppie,要求有   wao(), fetchBall(),  run() , sleep()等方法。

      假设现在John有个朋友想要一只Puppie,可是只找到一只Kittie, John需要使用适配器模式把Kittie适配成Puppie,让他朋友满意。请问John该怎么做。

 

      代码:

     

    

/** 
* 源角色(Adaptee)-------具体类 
* 
*/ 
public class Kittie { 

public void miao(){} 
public void catchRat(){} 
public void run(){} 
public void sleep(){} 

}

 

/**
 * 目标角色(Target)
 *
 */

public interface Puppie {
	void wao();
	void fetchBall();
	void run();
	void sleep();
}

    

/**
 * 适配器Adapter 
 *
 */
public class John extends Kittie implements Puppie {

	public void fetchBall() {
		this.catchRat();
	}

	public void wao() {
		this.miao();
	}
	
	public void run(){
		super.run();
	}
	
	public void sleep(){
		super.sleep();
	}


}

          

分享到:
评论
2 楼 hanlingbo2008 2008-11-14  
从Enueration到Iterator的适配


public interface Enumeration<E> {
        boolean hasMoreElements();
        E nextElement();
}


public interface Iterator<E> {
    boolean hasNext();
     E next();
    void remove();
}


public class Itermeration implements Enumeration {
   private Enumeration em;
   public Itermeration(Enumeration em){
      this.em = em;
   }
   //是否存在下个元素
   public boolean hasNext(){
       return em.hasMoreElements();
   }
   //返回下一个元素
   public Object next()throws NoSuchElementException{
      return en.nextElement()
   }
}
1 楼 hanlingbo2008 2008-11-14  
从Iterator到Enueration的适配

public interface Enumeration<E> {
        boolean hasMoreElements();
        E nextElement();
}

public interface Iterator<E> {
    boolean hasNext();
     E next();
    void remove();
}

public class Itermeration implements Enumeration {
   private Iterator it;
   public Itermeration(Iterator it){
      this.it = it;
   }
   //是否存在下个元素
   public boolean hasMoreElements(){
       return it.hasNext();
   }
   //返回下一个元素
   public Object nextElement()throws NoSuchElementException{
      return it.next();
   } 
}

相关推荐

Global site tag (gtag.js) - Google Analytics