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

设计模式之适配器模式

时间:2015-12-03 02:23:02      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:适配器模式   设计模式   

以下情况使用适配器模式
你想使用一个已经存在的类,而它的接口不符合你的需求。
你想创建一个可以复用的类,该类可以与其他不相关的类或不可预见的类(即那些接口可能不一定兼容的类)协同工作。
(仅适用于对象Adapter)你想使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配它们的接口。对象适配器可以适配它的父类接口。

技术分享


其中目标接口target:

// 目标接口,或称为标准接口
package com.nudt.design.adapter;

/**
 * Created by jeffrey on 15-12-2.
 */
public interface Target {
    public void request();
}

被适配类Adaptee

// 已存在的、具有特殊功能、但不符合我们既有的标准接口的被适配类
package com.nudt.design.adapter;

/**
 * Created by jeffrey on 15-12-2.
 */
public class Adaptee {
    public void commonRequest(){
        System.out.println("common function!");
    };
}

第一种:适配器Adapter(继承模式):

// 适配器类,继承了被适配类,同时实现标准的目标接口
package com.nudt.design.adapter;

/**
 * Created by jeffrey on 15-12-2.
 */
public class AdapterExtends extends Adaptee implements Target {
    @Override
    public void request() {
        System.out.println("after extends");
        this.commonRequest();
    }
}

第二种:适配器Adapter(组合模式):

//通过继承目标标准接口,然后讲通用的被适配类作为成员变量组合进去
package com.nudt.design.adapter;

/**
 * Created by jeffrey on 15-12-2.
 */
public class AdapterZuhe implements Target {

    private Adaptee special;
    public AdapterZuhe(Adaptee special){
        this.special = special;
    }
    @Override
    public void request() {
        System.out.println("after zuhe!");
        special.commonRequest();
    }
}

测试类:

package com.nudt.design.adapter;

/**
 * Created by jeffrey on 15-12-2.
 */
public class NoteBook {
    //private Target concreteTarget;
    private Target target;
    //private Adaptee adaptee;
    public NoteBook(Target target){
        this.target = target;
    }
    public void request(){
        target.request();
    }

    public static void main(String[] args) {
        //只有一个普通的工具
        Adaptee adaptee = new Adaptee();
        //要实现特殊功能
        //方式一:采用组合的方式
        Target target = new AdapterZuhe(adaptee);
        NoteBook nb1 = new NoteBook(target);
        nb1.request();
        //方式二:采用继承的方式
        Target target2 = new AdapterExtends();
        NoteBook nb2 = new NoteBook(target2);
        nb2.request();
    }
}

最关键的一句话:继承被适配类,同时实现目标接口


设计模式之适配器模式

标签:适配器模式   设计模式   

原文地址:http://muyunzhe.blog.51cto.com/9164050/1719043

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