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

图解设计模式之Adapter模式

时间:2018-07-14 21:34:29      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:使用   with   区别   类适配器   其他   super   date   ace   电源   

什么是Adapter模式

 Adapter模式即适配器模式,对于适配器的理解参考现实生活中把交流电转换成直流电的电源适配器,用于填补现有的程序所需的程序之间差异的设计模式就是Adapter模式,有以下两种实现方式:
 1. 类适配器模式(使用继承的适配器)
 2. 对象适配器模式(使用委托的适配器)
所谓继承和委托的区别在哪呢?委托是指将某个方法中的实际处理交给其他实例的方法,继承则是自己进行处理,下面分别看下两种实现方式:

代码清单

这里有一个需要被适配的Banner类

/**
 * 被适配角色:交流100福特电源
 * @author guozhenZhao
 * @date 2018年6月21日
 */
public class Banner {
    private String string;

    public Banner(String string) {
        super();
        this.string = string;
    }

    public void showWithParen() {
        System.out.println("("+ string +")");
    }

    public void showWithAster() {
        System.out.println("*"+ string +"*");
    }
}

还有一个接口和一个抽象类

public interface Print {
    public abstract void printWeak();
    public abstract void printStrong();
}
public abstract class PrintTwo {
    public abstract void printWeak();
    public abstract void printStrong();
}

下面看一下两种方式的区别:
1. 使用继承的适配器

/**
 * 使用继承的适配器
 * @author guozhenZhao
 * @date 2018年6月20日
 */
public class PrintBanner extends Banner implements Print {

    public PrintBanner(String string) {
        super(string);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void printWeak() {
        // TODO Auto-generated method stub
        showWithParen();
    }

    @Override
    public void printStrong() {
        // TODO Auto-generated method stub
        showWithAster();
    }

}

2.使用委托的适配器

/**
 * 使用委托的适配器
 * @author guozhenZhao
 * @date 2018年6月21日
 */
public class PrintBannerTwo extends PrintTwo {
    private Banner banner;

    public PrintBannerTwo(String string) {
        super();
        this.banner = new Banner(string);
    }

    @Override
    public void printWeak() {
        // TODO Auto-generated method stub
        banner.showWithParen();
    }

    @Override
    public void printStrong() {
        // TODO Auto-generated method stub
        banner.showWithAster();
    }

}

当PrintBanner类的printWeak方法被调用时,并不是PrintBanner类自己进行处理,而是交给了其他类的实例的某些方法

什么时候使用适配器模式呢

有一些现有的类可以被我们重复使用时,我们可以使用适配器将这些类作为组件重复利用,另外适配器模式用于连接接口(API)不同的类

图解设计模式之Adapter模式

标签:使用   with   区别   类适配器   其他   super   date   ace   电源   

原文地址:http://blog.51cto.com/13416247/2142592

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