适配器模式属于结构型模式java
定义:将一个类的接口转换成客户但愿的另一个接口。适配器模式使得本来因为接口不兼容而不能一块儿工做的那些类能够一块儿工做ide
使用场景:测试
你想使用一个已经存在的类,而他的接口不符合你的要求。this
你想建立一个能够复用的类,该类能够与其余不相关或不可预见的类(即那些接口可能不兼容的类)协同工做spa
你想使用一些已经存在的子类,可是不可能对每个都进行子类话以匹配他们的接口。对象适配器能够适配它的父类接口设计
结构:代理
target:定义client使用的与特定领域相关的接口code
client:与符合target接口的对象协同对象
Adaptee:定义一个已经存在的接口,这个接口须要适配。继承
Adapter:对Adaptee的接口与target接口进行适配。
适配器模式是一种补偿机制,虽然他有不少优势,但这是在后期发现原有类不知足扩展需求所作的一种妥协,因此不推荐设计初期使用。
下面的方法经过在类adapter中声明一个adaptee来实现,被称为对象适配器;也能够经过继承adaptee类实现,被称为类适配器,不过java只支持单继承,因此不推荐类适配器。
public static void main(String[] args) { Target target=new Adapter(new Adaptee()); target.adapteeMethod(); target.adapterMethod(); } } interface Target{ void adapteeMethod(); void adapterMethod(); } class Adaptee{ public void adapteeMethod(){ System.out.println("adaptee method"); } } class Adapter implements Target{ private Adaptee adaptee; public Adapter(Adaptee adaptee){ this.adaptee=adaptee; } @Override public void adapteeMethod() { adaptee.adapteeMethod(); } @Override public void adapterMethod() { adaptee.adapteeMethod(); } }
下面这段测试代码模拟的是不一样人不一样的起名习惯,在不违背开放封闭原则的基础上统一为同一习惯,适配为一种接口的适配器模式,是否是感受很像代理模式?
下节将讲代理模式,包括静态代理、动态代理、以及代理模式和适配器模式的区别。内容应该比较多因此须要两天才能更新吧,敬请期待。
public class ShipeiqiTest { public static void main(String[] args) { BaseService service=new VisitorImpl(new VisitorServiceImpl()); service.update(); } } //习惯1 target interface BaseService { void insert(); void update(); } class AdminServiceImp implements BaseService { @Override public void insert() { } @Override public void update() { } } //习惯二 被适配者 adaptee interface DaoService { void insert(); } class VisitorServiceImpl implements DaoService { @Override public void insert() { } } //适配器 adapter class VisitorImpl implements BaseService { DaoService service; public VisitorImpl(DaoService service) { this.service = service; } @Override public void insert() { service.insert(); } @Override public void update() { } }