Java 23中设计模式之适配器模式
一:介绍
适配器模式(Adapter)把一个类的接口变换成客户端所期待的另一种接口,从而使原来因接口不匹配而无奈在一起工作的两个类可能放在一起工作。
用电器来打个比喻:有一个电器的插头是三脚的,而现有的插座是两孔的,要使插头插上插座,咱们须要一个插头转换器,这个转换器即是适配器。
二:模式角色
适配器模式有以下角色:
1.Target(指标):这就是所期待失去的接口 2.Adaptee(源):现有须要适配的接口 3.Adapter(适配器):适配器类是本模式的外围,适配器把Adaptee转换成Target.
三:模式结构图
1.类的适配器模式结构图
2.对象的适配器模式结构图
四:模式实现
1.类的适配器模式
/**用户期待的指标接口*/public interface Target { void doSomething1(); //Adaptee中没有的办法,用户期待的指标接口doSomething2() void doSomething2();}//源业务做得事件public class Adaptee { public void doSomething1() { // 业务逻辑,源业务做的事件 }}/**类适配器模式*/public class Adapter extends Adaptee implements Target { // Adaptee中没有办法doSomething2,因而适配器类补充此办法 @Override public void doSomething2() { //业务逻辑,适配的接口须要做的事件 }}//应用 Adapter adapter=new Adapter(); adapter.doSomething2();//通过适配减少的接口 adapter.doSomething1();
2.对象适配器模式
/**用户期待的指标接口*/public interface Target { void doSomething1(); //Adaptee中没有的办法,用户期待的指标接口doSomething2() void doSomething2();}//源业务做得事件public class Adaptee { public void doSomething1() { // 业务逻辑,源业务做的事件 }}/**对象适配器模式*/public class Adapter implements Target { private Adaptee adaptee; public Adapter(Adaptee adaptee){ this.adaptee=adaptee; } @Override public void doSomething1() { adaptee.doSomething1(); } // Adaptee中没有办法doSomething2,因而适配器类补充此办法 @Override public void doSomething2() { //业务逻辑,适配的接口须要做的事件 }}//应用,通过构造方法传入对象 Adapter adapter=new Adapter(new Adaptee()); adapter.doSomething2(); adapter.doSomething1();
3.接口适配器模式:也叫缺省适配器模式
次要解决接口的复用问题:有时候可能咱们的业务仅仅须要应用接口中的某一个办法而不是所有办法。可是因为接口的语言个性而 不得不实现所有的形象办法。这样就会使得接口的应用过程十分麻烦,特地是接口中存在十分多形象办法的时候。面对接口的这类问题。咱们可能採用一个抽象类(也可 以不是抽象类)去实现接口
//对象适配器模式public abstract class BaseAdapter implements ListAdapter, SpinnerAdapter {//源数据public void notifyDataSetChanged() { mDataSetObservable.notifyChanged(); } public int getViewTypeCount() { return 1; } //指标接口public boolean isEnabled(int position) { return true; }}//指标数据public interface ListAdapter extends Adapter{boolean isEnabled(int position);}
小“姿态”
VGA:VGA接口与连贯的电缆,但通常指VGA接口,也叫D-Sub接口
HDMI :高清晰度多媒体接口
结尾:活学活用