适配器模式

来源:互联网 发布:社会网络的同义词 编辑:程序博客网 时间:2024/06/05 14:12

定义:

适配器模式将一个类的接口转换成客户期望的另一个接口。使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作


适配器分类


1.组合


对象适配器


特点:把“被适配者”作为一个对象组合到适配器类中,以修改目标接口包装被适配者


/** *  * 三相插座接口 *  * @author Administrator * */public interface ThreePlugInterface {//使用三相电流供电public void powerWithThree();}

public class GBTwoPlug {//使用二相电流供电public void powerWithTwo() {System.out.println("使用二相电流供电");}}


/** *  * 二相转三相的插座适配器 *  * @author Administrator * */public class TwoPlugAdapter implements ThreePlugInterface {private GBTwoPlug plug;public TwoPlugAdapter(GBTwoPlug plug) {this.plug = plug;}@Overridepublic void powerWithThree() {System.out.println("通过转化");plug.powerWithTwo();}}


2.继承


类适配器


特点:通过多重继承不兼容接口,实现对目标接口的匹配,单一的为某个类而实现适配


/** *  * 采用继承方式的插座适配器 *  * @author Administrator * */public class TwoPlugAdapterExtends extends GBTwoPlug implementsThreePlugInterface {@Overridepublic void powerWithThree() {System.out.println("借助继承适配器");this.powerWithTwo();}}


public class NoteBook {private ThreePlugInterface plug;public NoteBook(ThreePlugInterface plug) {this.plug = plug;}//使用插座充电public void charge() {plug.powerWithThree();}public static void main(String[] args) {GBTwoPlug twoPlug = new GBTwoPlug();ThreePlugInterface threePlug = new TwoPlugAdapter(twoPlug);NoteBook noteBook = new NoteBook(threePlug);noteBook.charge();threePlug = new TwoPlugAdapterExtends();noteBook = new NoteBook(threePlug);noteBook.charge();}}






https://github.com/LiuchangDuan/designpatterndemo/tree/master/src/com/example/pattern/adapter



0 0