适配器模式(Adapter)

        前言:适配器就是一种适配中间件,它存在于不匹配的二者之间,用于连接二者,将不匹配变得匹配,简单点理解就是平常所见的转接头,转换器之类的存在。

        概念:适配器模式的种类:1.类适配器(通过继承来实现适配器功能)、2.对象适配器(通过组合来实现适配器功能)、3.接口适配器(通过抽象类来实现适配)。

一:类适配器    

          通过继承来实现适配器功能

          生活场景:美国的插头是三角,中国的插头是两角,如果让二角变三角或者三角变两角呢?数据转换线就是适配器

          代码实现:AmericaPower.java(美国插头接口),APower.java(实现类),ChinaPower.java(中国插头接口),CPower.java(中国插头实现类)

public interface AmericaPower {
    public void threeStep();
}

public class APower implements AmericaPower {

    @Override
    public void threeStep() {
        System.out.println("我是三角的电源");
    }
}

public interface ChinaPower {
    
    public void twoStep();
}

public class CPower extends APower implements ChinaPower {

    @Override
    public void twoStep() {
        this.threeStep();
    }
}

//测试
 public static void main(String[] args) {
        ChinaPower chinaPower = new CPower();
        //两脚适配三角
        chinaPower.twoStep();
        
    }

二:对象适配器

          通过组合来实现适配器功能

          生活场景:美国的插头是三角,中国的插头是两角,如果让二角变三角或者三角变两角呢?数据转换线就是适配器

          代码实现:AmericaPower.java(美国插头接口),APower.java(实现类),ChinaPower.java(中国插头接口),CPower.java(中国插头实现类)

public interface AmericaPower {
    public void threeStep();
}


public class APower implements AmericaPower {

    @Override
    public void threeStep() {
        System.out.println("我是三角的电源");
    }
}

public interface ChinaPower {
    
    public void twoStep();
}

public class CPower implements ChinaPower {
    
//*** 可以通过构造传入
private AmericaPower ap = new APower(); @Override public void twoStep() { ap.threeStep(); } }
//测试
publicstaticvoid main(String[] args) {
ChinaPower chinaPower
= new CPower();
//两角适配三角
chinaPower.twoStep();
}

三:接口适配器

          当存在这样一个接口,其中定义了N多的方法,而我们现在却只想使用其中的一个到几个方法,如果我们直接实现接口,那么我们要对所有的方法进行实现,哪怕我们仅仅是对不需要的方法进行置空(只写一对大括号,不做具体方法实现)也会导致这个类变得臃肿,调用也不方便,这时我们可以使用一个抽象类作为中间件,即适配器,用这个抽象类实现接口,而在抽象类中所有的方法都进行置空,那么我们在创建抽象类的继承类,而且重写我们需要使用的那几个方法即可。注意模板模式也可以用抽象类来实现。

          生活场景:现代化酒店都有很多服务,但是我不需要这么多服务,作为一个穷人,我只有经济能力吃饭和住房

          代码实现:HotelInterface.java(酒店服务接口),HotelAdapter(酒店服务抽象类),Traveler(旅客) 

public interface HotelInterface {
    void eat();//吃饭
    void live();//居住
    void washFoot();//洗脚
    void chess();//棋牌
}

public class HotelAdapter implements HotelInterface {
    @Override
    public void eat() {
        System.out.println("吃饭");
    }

    @Override
    public void live() {
        System.out.println("留宿");
    }

    @Override public void washFoot() { }

    @Override public void chess() { }
}

//旅客
public class Traveler extends HotelAdapter {
    @Override
    public void eat() {
        super.eat();
    }
    @Override
    public void live() {
        super.live();
    }
}

四:总结

         优点:转换匹配,复用功能,自然地扩展系统的功能。

         缺点:过多的适配,会让系统非常的凌乱,不容易整理进行把握。因此如果不是很有必要,可以不使用适配器,而似乎直接对系统进行重构。

原文地址:https://www.cnblogs.com/dyg0826/p/11326715.html