您的位置:首页 > 其它

适配器模式(Adapter)

2017-06-06 14:11 176 查看

适配器模式(Adapter)

适配模式。是目前支付渠道最常用的一种入参与出参的模式,这种模式常常用于实现不同的 接口,是一种接口转换常用的模式。只要是对接不一样的问题,大多数都是用 适配模式解决。废话不多说。直接代码走起

一.适配模式:简单来说,就是不同接口之间的实现。根据客户另一种说法就是,适配器模式将某个类的接口转换成客户端期望的另一个接口表示,目的是消除由于接口不匹配所造成的类的兼容性问题。

这个适配器模式大致分一下三种模式:

1.类的适配器模式、2.对象的适配器模式、3.接口的适配器模式。

首先看一下:类的适配器模式   比如:目前恒生类hundsun,待适配,目标接口是baofoo(宝付),通过Adapter类,将hundsun的功能扩展到baofoo里

public class hungsun {

public void method() {
System.out.println("this is original method!");
}
}
public interface baofoo{

/* 与原类中的方法相同 */
public void method();

/* 新类的方法 */
public void method1();
}
public class Adapter extends hundsun implements baofoo{

@Override
public void method1() {
System.out.println("this is the baofoo method!");
}
}

Adapter类继承hundsun类,实现baofoo接口,下面是测试类:

public class AdapterTest {

public static void main(String[] args) {
baofoo target = new Adapter();
target.method();
target.method1();
}
}

结果:

this is original method!
this is the baofoo method!

这样baofoo接口的实现类就具有了hundsun类的功能。

 

二.对象适配器模型:

基本思路和类的适配器模式相同,只是将Adapter类作修改,这次不继承hundsun类,而是持有hundsun类的实例,以达到解决兼容性的问题

public class Wrapper implements baofoo{

private hundsun hsun;

public Wrapper(hundsun hsun){
super();
this.hsun= hsun;
}
@Override
public void method2() {
System.out.println("this is the baofoo method!");
}

@Override
public void method1() {
hsun.method1();
}
}
public class AdapterTest {

public static void main(String[] args) {
hundsun hsun= new hundsun();
baofoo target = new Wrapper(hsun);
target.method();
target.method1();
}
}

结果一样:

三.接口适配器模式:接口的适配器是这样的:接口中往往有多个抽象方法,但是我们写该接口的实现类的时候,必须实现所有这些方法,这明显有时比较浪费,因为并不是所有的方法都是我们需要的,有时只需要某一些,此处为了解决这个问题,我们引入了接口的适配器模式,借助于一个抽象类,该抽象类实现了该接口,实现了所有的方法,而我们不和原始的接口打交道,只和该抽象类取得联系,所以我们写一个类,继承该抽象类,重写我们需要的方法就行。

public interface Sourceable {

public void method1();
public void method2();
}

public abstract class Wrapper2 implements Sourceable{

public void method1(){}
public void method2(){}
}
public class SourceSub1 extends Wrapper2 {
public void method1(){
System.out.println("the sourceable interface's first Sub1!");
}
}
public class SourceSub2 extends Wrapper2 {
public void method2(){
System.out.println("the sourceable interface's second Sub2!");
}
}

测试
public class WrapperTest {

public static void main(String[] args) {
Sourceable source1 = new SourceSub1();
Sourceable source2 = new SourceSub2();

source1.method1();
source1.method2();
source2.method1();
source2.method2();
}
}

这例子就把我们接口分离开来了,灵活使用了接口。

总结:

这三个适配器模式的使用。他们的应用场景也不同,

类的适配器模式:当希望将一个类转换成满足另一个新接口的类时,可以使用类的适配器模式,创建一个新类,继承原有的类,实现新的接口即可。

对象的适配器模式:当希望将一个对象转换成满足另一个新接口的对象时,可以创建一个Wrapper类,持有原类的一个实例,在Wrapper类的方法中,调用实例的方法就行。

接口的适配器模式:当不希望实现一个接口中所有的方法时,可以创建一个抽象类Wrapper,实现所有方法,我们写别的类的时候,继承抽象类即可。

适配器模型是我们开发对外企业,互联网开发,app开发。等等最经常用到的一个手段。哈哈哈哈。。

如果设计方面需要咨询的欢迎一起跟我交流。加499749405群。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: