adapter - 类对象结构型模式

1.意图
               将一个类的接口转换成客户希望的接口,adapter模式使得原来由于接口不兼容的
        而不能一起工作的那些类可以一起工作。
     2.参与者
      Target,Client,Adaptee,Adapter
     3.相关模式
      Bridge与对象适配器类似,但是出发点不同:Bridge目的是将接口部分和实现
            部分分离,从而对它们可以较容易相对对立的加以改变。而adapter意味着改变
            一个已有的接口
      Decorator增强了其它对象的功能而同时不改变它的接口。因此decorator对应用
           程序的透明性比adapter好,结果是decorator支持递归组合而纯粹使用适配器
           是不可能实现这一点的。
           代理模式proxy在不改变接口的条件下为另一个对象定义一个代理。

4.类适配器结构

5.类适配器代码

public interface Target {
  void playA();
}

public class ConcreteTarget implements Target {

	@Override
	public void playA() {
		System.out.println("playA");
	}

}


public class Adaptee {
 void playB(){
	 System.out.println("playB");
 }
}

public class Adapter extends Adaptee implements Target {

	@Override
	public void playA() {
		super.playB();
	}

}

public class Client {
	public static void main(String[] args) {
       Target t = new Adapter();
       t.playA();
	}
}

6.对象适配器结构

7.对象适配器代码

public interface Adaptee {
 void playA();
}

public class Adaptee1 implements Adaptee {

	@Override
	public void playA() {
		System.out.println("Adaptee1");
	}

}

public class Adaptee2 implements Adaptee {

	@Override
	public void playA() {
       System.out.println("Adaptee2");
	}

}

public interface Target {
  void playB();
}

public class Adapter implements Target {
	private Adaptee adaptee;
	Adapter(Adaptee adaptee){
		this.adaptee = adaptee;
	}
	@Override
	public void playB() {
		adaptee.playA();
	}

}

public class Client {
	public static void main(String[] args) {
		Adaptee a = new  Adaptee1();
       Target t = new Adapter(a);
       t.playB();
       Adaptee b = new  Adaptee2();
       Target t2 = new Adapter(b);
       t2.playB();
       
	}
}

   

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章