`
edwin492
  • 浏览: 112629 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

设计模式之适配器(adapter)

阅读更多

将一个类的接口转换为客户希望的另外一个接口。包括类适配器和对象适配器。

 

//类适配器
public class ClassAdapter {
	interface Target{
		public abstract void targetMethod();
	}
	
	class Adaptee{
		public void adapteeMethod(){
			System.out.println("adapteeMethod...");
		}
	}
	
	class Adapter extends Adaptee implements Target{
		public void targetMethod() {
			  super.adapteeMethod();
		}
	}
	public static void main(String[] args){
		ClassAdapter ca = new ClassAdapter();
		Target t = ca.new Adapter();
		t.targetMethod();
	}
}
   

 //对象适配器

public class ObjectAdapter {
	interface Target{
		public abstract void targetMethod();
	}
	
	class Adaptee{
		public void adapteeMethod(){
			System.out.println("adapteeMethod...");
		}
	}
	
	class Adapter implements Target{
		private Adaptee adaptee;
		
		public Adapter(Adaptee adaptee){
			this.adaptee = adaptee;
		}
		public void targetMethod() {
			adaptee.adapteeMethod();
		}
	}
	public static void main(String[] args){
		ObjectAdapter ca = new ObjectAdapter();
		Adaptee adptee = ca.new Adaptee();
		Target t = ca.new Adapter(adptee);
		t.targetMethod();
	}
}
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics