适配器模式
2018-02-04 17:09
190 查看
适配器模式将某个类的接口转换成客户端期望的另一个接口表示。核心是有一个Source类,拥有一个方法待适配,目标接口是 Targetable ,通过 Adapter 类,将Source 的功能扩展到 Targetable 里。主要包括三类:类适配器,对象适配器,接口适配器。常见的应用场景:java.io.InputstreamReader(InputStream)
类适配器
对象适配器
结果输出如下:
this is the original method
this is the targetble method
this is the original method
this is the targetable method
上面只有类的适配器和对象适配器的例子,接口适配器也比较简单,就是一个接口可能有多个抽象方法,我们实现接口的时候,有些并不需要,但是仍要实现,就会造成浪费,现在引入一个抽象类,实现该接口,我们的类继承这个抽象类,只需要重写我们需要的方法就可以了。
public class Source { public void method1(){ System.out.println("this is the original method"); } }
public interface Targetable { //与原类中的方法相同 void method1(); //新类的方法 void method2(); }
类适配器
//继承Source,实现Targetable public class Adapter extends Source implements Targetable { @Override public void method2() { System.out.println("this is the targetble method"); } }
对象适配器
public class Wrapper implements Targetable{ //持有Source对象 private Source source; public Wrapper(Source source) { this.source = source; } @Override public void method1() { source.method1(); } @Override public void method2() { System.out.println("this is the targetable method"); } }
public cla 4000 ss Test { public static void main(String[] args) { //调用类适配器 classAdapter(); //调用对象适配器 objectAdapter(); } public static void classAdapter(){ Targetable target = new Adapter(); target.method1(); target.method2(); } public static void objectAdapter(){ Wrapper wrapper = new Wrapper(new Source()); wrapper.method1(); wrapper.method2(); } }
结果输出如下:
this is the original method
this is the targetble method
this is the original method
this is the targetable method
上面只有类的适配器和对象适配器的例子,接口适配器也比较简单,就是一个接口可能有多个抽象方法,我们实现接口的时候,有些并不需要,但是仍要实现,就会造成浪费,现在引入一个抽象类,实现该接口,我们的类继承这个抽象类,只需要重写我们需要的方法就可以了。
相关文章推荐
- PHP设计模式--适配器模式
- 一个简单的适配器模式例子
- java设计模式之适配器模式
- 设计模式学习系列五:适配器模式(Adapter)
- c++设计模式:适配器模式(Adapter Pattern)
- 【大话设计模式】——适配器模式
- 设计模式之结构类模式——适配器模式
- 设计模式笔记之六 (适配器模式)
- Java开发模式(适配器模式)
- 适配器模式实例(C#)
- 适配器模式及C++实现
- 《设计模式》-适配器模式
- Java适配器模式
- 适配器模式入门
- C#设计模式-1、适配器模式(Adapter Pattern)(转载)
- 设计模式--学习笔记--适配器模式Adapter--基础篇
- Adapter 适配器模式
- 适配器模式(Adapter Pattern)
- 【原】从头学习设计模式(七)——适配器模式
- 适配器模式(Adapter)