Java设计模式--------适配器模式(AdapterPattern)

适配器模式:
百度百科解释如下:适配器模式(有时候也称包装样式或者包装)将一个类的接口适配成用户所期待的。一个适配允许通常因为接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。
适配器使用情形如下: 一个程序想要使用已存在的类但是该类实现的接口和当前程序使用的接口不一致导致无法使用,在这种情形下可以使用适配器模式进行转换使得原本无法使用的接口可以使用。
适配器代码演示:

 /**
 * 需求:客户购买了新的苹果手机
 * 但是由于新苹果手机听歌接口是新接口导致顾客无法使用原来3.5接口的耳机
 * 顾客现在有一个3.5接口的耳机想要在新苹果手机上可以使用 请解决这个问题
 * 分析:可以使用适配器模式 创建一个转换器 将3.5接口和新接口联系在一起 进行转换
 * 从而让顾客可以使用3.5接口的耳机在新苹果手机上听音乐
 *
 */
public class NewIphone {

//新手机测试在新接口下3.5耳机的接口是否可以使用
    public void NewIpone_test(NewInterface a){
       a.PlayNMusic();
    }
    public static void main(String[] args) {
    /*  测试对象适配器接口下
        NewIphone iphone = new NewIphone();
        OldInterface oldInterface = new OldInterface();
        NewInterface a = new AdapterInterface2(oldInterface);//将3.5接口耳机传入适配器进行转换
        iphone.NewIpone_test(a);
        */
     /*  测试类适配器接口下
        NewIphone iphone = new NewIphone();
        OldInterface oldInterface = new OldInterface();
        NewInterface a = new AdapterInterface();
        iphone.NewIpone_test(a);
        */

    }
}
/*
老手机3.5接口的耳机
 */
public class OldInterface {
    public void PlayMusic(){
        System.out.println("插入3.5接口数据线的耳机进行播放音乐");
    }
}

/*
新手机接口的耳机线接口
*/
public interface NewInterface {
    void PlayNMusic();
}



/*
 转换器接口利用类适配器处理
 */
public class AdapterInterface extends OldInterface implements NewInterface {

    /**
     * 利用继承实现适配的方式成为类适配器
     */
    @Override
    public void PlayNMusic() {
       super.PlayMusic();
    }
}


/*
 转换器接口利用对象适配器处理
 */
public class AdapterInterface2 implements NewInterface {

    private OldInterface o;//创建旧接口的对象

    //将旧的接口传入适配器中
    public AdapterInterface2(OldInterface o) {
        this.o = o;
    }

    /**
     * 不利用继承实现适配的方式成为对象适配器
     */
    @Override
    public void PlayNMusic() {
       o.PlayMusic();
    }
}

结果:
在这里插入图片描述

在Java中使用到适配器的情形:
java-io.InputStreamReader(InputStream in) 字节流转为字符流
java-io.OutputStreamWriter(OutputStream out) 字符流转为字节流
这个方式就是使用适配器进行转换的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值