码迷,mamicode.com
首页 > 其他好文 > 详细

八、适配器模式

时间:2017-09-22 14:08:59      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:div   main   static   间接   int   over   bsp   child   inter   

适配器模式,用一个类作为中间桥梁把无法被直接使用的功能类通过适配,最终能够被间接使用。

如图:

技术分享

优点:适配器模式能够提高代码的复用性,使得原本无法被使用的类能够被使用。

缺点:但是适配器模式会提高代码的复杂性,让原本简单的逻辑结构变得有些绕,如果使用了大量的适配器,那整个程序结构就会变得混乱不堪,所以如果能够通过重构完成的,还是不要使用适配器比较好。

下面是代码:

/**
 * 适配器模式
 * @author lay
 */
public class AdapterDemo {
    
    public static void main(String[] args) {
        Adapter adapter = new Adapter();
        adapter.sayAdapter();
    }
}

// 将无法使用的接口进行适配,客户端通过适配器调用接口
class Adapter{
    
    private Parent parent;
    
    public Adapter(){
        this.parent = new Child();
    }
    
    public void sayAdapter(){
        System.out.println("调用适配器方法");
        parent.say();
    }
}

// 无法被客户端使用的接口
interface Parent{
    public void say();
}

class Child implements Parent{

    @Override
    public void say() {
        System.out.println("i‘m a child");
    }
    
}

 

八、适配器模式

标签:div   main   static   间接   int   over   bsp   child   inter   

原文地址:http://www.cnblogs.com/lay2017/p/7574341.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!