Design Pattern——Adapter

来源:互联网 发布:2014 电影 知乎 编辑:程序博客网 时间:2024/05/22 04:37

Adapter的目的是复用代码,解决接口不兼容的问题。

一种是类适配器,一种是对象适配器。

类适配器举例:

package com.zxy.designpattern;public class Client{<span style="white-space:pre"></span>public static void main(String[] args) {<span style="white-space:pre"></span>// TODO Auto-generated method stub<span style="white-space:pre"></span>Clientt clientt = new Clientt();<span style="white-space:pre"></span>clientt.funA();<span style="white-space:pre"></span>}}interface function{<span style="white-space:pre"></span>public void funA();}class Clientt implements function{<span style="white-space:pre"></span>public void funA(){<span style="white-space:pre"></span>Adapter adapter = new Adapter();<span style="white-space:pre"></span>adapter.funA();<span style="white-space:pre"></span>}}class Serve{<span style="white-space:pre"></span>protected void funB(){<span style="white-space:pre"></span>System.out.println("funB");<span style="white-space:pre"></span>}}class Adapter extends Serve implements function{<span style="white-space:pre"></span>public void funA(){<span style="white-space:pre"></span>funB();<span style="white-space:pre"></span>}}


对象适配器举例:

package com.zxy.designpattern;public class Client {public static void main(String[] args) {// TODO Auto-generated method stubFunA funA = new Adapter();funA.funA();}}class FunA{public void funA(){}}class Serve{public void funB(){System.out.println("funB");}}class Adapter extends FunA{private Serve serve = new Serve();public void funA(){serve.funB();}}

不同点:

类适配器在客户端指定的是接口,对象适配器在客户端没有指定接口。

对象适配器安全性没有类适配器高,因为它依赖于现有类的实例,而适配器无法保证客户端调用的方法不改变。


0 0