seo公司网站,云开发cms内容管理系统,免费源码资源,wordpress默认登录版权声明
本文原创作者#xff1a;谷哥的小弟作者博客地址#xff1a;http://blog.csdn.net/lfdfhl 场景与问题
众所周知#xff0c;我们国家的生活用电的电压是220V而笔记本电脑、手机等电子设备的工作压没有这么高。为了使笔记本、手机等设备可以使用220V的生活用电就需…
版权声明
本文原创作者谷哥的小弟作者博客地址http://blog.csdn.net/lfdfhl 场景与问题
众所周知我们国家的生活用电的电压是220V而笔记本电脑、手机等电子设备的工作压没有这么高。为了使笔记本、手机等设备可以使用220V的生活用电就需要使用电源适配器(AC Adapter)也就是人们常说的充电器或变压器。有了这个电源适配器,原本不能直接工作的生活用电和笔记本电脑就可以兼容了。 另外在生活中我们还经常类似头痛的小问题插座是两脚的但是插板却是三孔的。这个该怎么办呢此时适配器设计模式就能够帮到你
适配器模式概述
在此概述适配器模式。
适配器模式定义
Adapter Pattern: Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
适配器模式将一个类的接口转换成客户希望的另一个接口。适配器模式让那些接口不兼容的类可以一起工作。
适配器的实现就是把客户类的请求转化为对适配者的相应接口的调用。也就是说当客户类调用适配器的方法时在适配器类的内部将调用适配者类的方法而这个过程对客户类是透明的客户类并不直接访问适配者类。因此适配器让那些由于接口不兼容而不能交互的类可以一起工作。
适配器模式可以将一个类的接口和另一个类的接口匹配起来而无须修改原来的适配者接口和抽象目标类接口。
适配器模式角色
在此介绍适配器模式中的主要角色。
目标角色(Target)客户端所期待的接口(可以是具体类或者抽象类)。 源角色(Adaptee)被适配者。已经存在的需要适配的接口或类。 适配器(Adapter)将源接口转换成目标接口。
适配器模式案例
在此以案例形式讲解适配器模式。
案例一
请看适配器模式案例一项目结构如下
Adaptee
/**
* 本文作者谷哥的小弟
* 博客地址http://blog.csdn.net/lfdfhl
* 代码描述被适配的类。例如两脚插头
*/
public class Adaptee {public void adapteeMethod() {System.out.println(两脚插头正常工作);}
}Target
/**
* 本文作者谷哥的小弟
* 博客地址http://blog.csdn.net/lfdfhl
* 代码描述目标接口(客户所期待的接口)。例如三孔插板
*/
public interface Target {void targetMethod();
}Adapter
package com.adapter01;/**
* 本文作者谷哥的小弟
* 博客地址http://blog.csdn.net/lfdfhl
* 代码描述适配类。例如:插头转换器
*/
public class Adapter extends Adaptee implements Target {// 实现Target接口中的方法Overridepublic void targetMethod() {// 调用Adaptee中的方法super.adapteeMethod();}
} Test
package com.adapter01;
/**
* 本文作者谷哥的小弟
* 博客地址http://blog.csdn.net/lfdfhl
* 代码描述测试类
*/
public class Test {public static void main(String[] args) {Adapter adapter new Adapter();adapter.targetMethod();}
} 测试 案例二
请看适配器模式案例二项目结构如下 Adaptee
package com.adapter02;/**
* 本文作者谷哥的小弟
* 博客地址http://blog.csdn.net/lfdfhl
* 代码描述被适配的类。例如两脚插头
*/
public class Adaptee {public void adapteeMethod() {System.out.println(两脚插头正常工作);}
}Target
package com.adapter02;/**
* 本文作者谷哥的小弟
* 博客地址http://blog.csdn.net/lfdfhl
* 代码描述目标类(客户所期待的类)。例如三孔插板
*/
public abstract class Target {abstract void targetMethod();
}Adapter
package com.adapter02;/**
* 本文作者谷哥的小弟
* 博客地址http://blog.csdn.net/lfdfhl
* 代码描述适配类。例如:插头转换器
*/
public class Adapter extends Target {// 持有Adaptee对象private Adaptee adaptee;public Adapter(Adaptee adaptee) {this.adaptee adaptee;}// 重写父类Target中的方法Overridepublic void targetMethod() {// 调用Adaptee中的方法adaptee.adapteeMethod();}
} Test
package com.adapter02;
/**
* 本文作者谷哥的小弟
* 博客地址http://blog.csdn.net/lfdfhl
* 代码描述测试类
*/
public class Test {public static void main(String[] args) {Adaptee adaptee new Adaptee();Adapter adapter new Adapter(adaptee);adapter.targetMethod();}
} 测试