适配器模式

    xiaoxiao2021-04-03  28

    适配器模式

    组合方式实现

    /** * 三相插座接口 */ public interface IThreePlug { //使用三相电流供电 void powerWithThree(); } public class GBTwoPlug { //使用二相电流供电 public void powerWithTwo(){ System.out.println("使用二相电流供电"); } } public class TwoPlugAdapter implements IThreePlug { private GBTwoPlug plug; public TwoPlugAdapter(GBTwoPlug plug) { super(); this.plug = plug; } @Override public void powerWithThree() { System.out.println("通过组合方式转化"); plug.powerWithTwo(); } } public class NoteBook { private IThreePlug plug; public NoteBook(IThreePlug plug){ this.plug=plug; } /** * 使用插座充电 */ public void charge(){ plug.powerWithThree(); } } public static void main(String[] args) { GBTwoPlug two = new GBTwoPlug(); IThreePlug plug = new TwoPlugAdapter(two); NoteBook noteBook = new NoteBook(plug); noteBook.charge(); }

    继承方式实现

    /** * 采用继承方式的插座适配器 */ public class TwoPlugClassAdapter extends GBTwoPlug implements IThreePlug{ @Override public void powerWithThree() { System.out.println("借助继承方式转化"); this.powerWithTwo(); } } public static void main(String[] args) { TwoPlugClassAdapter adapter = new TwoPlugClassAdapter(); NoteBook nb = new NoteBook(adapter); nb.charge(); }

    转载请注明原文地址: https://ju.6miu.com/read-665909.html

    最新回复(0)