Java23种设计模式--Adapter模式(二)

Adapter模式——–适配器

  这个设计模式相对来说还是比较容易理解的.
  本文以电源适配器为例子,其中Banner类就相当于是240V的实际输入电压,Print接口,则代表着适配器的输出,就当他是12V24V,而PrintBanner类就相当于是适配器,他拥有着转换功能.
目录:

Banner类
public class Banner {
    private int input;

    public Banner(int input) {
        this.input = input;
    }
    public void showLowOutput(){
        System.out.println("output1:"+input/20+"V");
    }
    public void showHighOutput(){
        System.out.println("output2:"+input/10+"V");
    }
}

  该类主要是提供showLowOutput方法和showHighOutput方法.

Print接口
public interface Print {
    public void printWeak();//输出低电压--12V
    public void printStrong();//输出高电压--24V
}

  两种输出方式

PrintBanner类
public class PrintBanner extends Banner implements Print {

    public PrintBanner(int input) {
        super(input);
    }

    //在printWeak中调用showLowOutput方法
    @Override
    public void printWeak() {
        showLowOutput();
    }
    //在pritStrong方法中调用showHighOutput方法
    @Override
    public void printStrong() {
        showHighOutput();
    }
}

  PrintBanner继承Banner类,继承了showLowOutput方法showHighOutput方法,同时又实现了Print接口,实现了printWeak方法和printStrong方法.

测试
public class Main {
    public static void main(String[] args) {
        Print p = new PrintBanner(240);//输入240
        p.printWeak();//输出12V
        p.printStrong();//输出24V
    }
}
结果

结果

总结

  编程中,很多时候都不是从零开始,而是有现成的类.而Adapter模式,主要就是将那些现有的类作为组件重复利用.
  就像本文中的例子一样,如果适配器功能参数都没变,只是需求变了,它不叫printWeakprintStrong了而改叫showWeakshowStrong了,那么当用了Adapter模式后,我们只需要换一个接口,然后去实现它和它内部的方法就可以,不会在原有的类上进行修改,确保了代码的正确性.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值