Java设计模式之适配器模式

简而言之所谓适配器模式就是将一个东西转换为在此基础上改善的一个东西,就是适配器模式的用武之地。

1  原有类具有的功能

package com.javapatterns.adapter.classAdapter;

public class Adaptee {
    /*
     * 原有类具有的功能
     */
    public void sampleOperation1()
    {
        System.out.println("this is 220v");
    }
}

2 现在需要新的功能,通过接口创建。

package com.javapatterns.adapter.classAdapter;

public interface Target {
    /**
     * Class Adaptee contains operation sampleOperation1. 
     */
    void sampleOperation1();

    /**
     * Class Adaptee doesn't contain operation sampleOperation2. 
     */
    void sampleOperation2();
}

3 在新类中添加实现具体的新功能

package com.javapatterns.adapter.classAdapter;

public class Adapter extends Adaptee implements Target {
    /**
     * Class Adaptee doesn't contain operation sampleOperation2. 
     */
    public void sampleOperation2(){
        System.out.println("This is 5v");
    }
}

4 测试

package com.javapatterns.adapter.classAdapter;

public class test {
    
    /** Creates a new instance of test */
    public test() {
    }
    
    
    public static void main(String[] args)
    {
        Adapter a  = new Adapter();
        a.sampleOperation2();
        a.sampleOperation1();
    }
}

运行结果:
This is 5v
this is 220v
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值