设计模式——适配器模式
场景
美国交流电插头(2头)无法插到欧洲壁式插座(3孔)
解决方法是在中间环节用适配器转化下搞定。
意图
将一个借口转化成另一个接口
举例
代码
#
package designpattern.adapter; public interface AmericanPlug { public void desc(); public void func(); }
#
package designpattern.adapter; public interface EuropePlug { public void desc(); public void func(); }
##
package designpattern.adapter; public class AmericanPlugImpl implements AmericanPlug{ public void desc() { System.out.println("American"); } public void func() { System.out.println("American two plug"); } }
##
package designpattern.adapter; public class EuropePlugImpl implements EuropePlug{ public void desc() { System.out.println("EuropePlug"); } public void func() { System.out.println("EuropePlug three plug"); } }
###
package designpattern.adapter; public class AmericanAdapter implements EuropePlug{ AmericanPlug americanPlug; public AmericanAdapter(AmericanPlug americanPlug) { this.americanPlug = americanPlug; } public void desc() { americanPlug.desc(); } public void func() { System.out.println("Before adapter"); americanPlug.func(); System.out.println("After adapter"); } }
测试
package designpattern.adapter; public class Test { public static void main(String[] args) { System.out.println("AmericanPlug---------"); AmericanPlug americanPlug = new AmericanPlugImpl(); americanPlug.desc(); americanPlug.func(); System.out.println("\nEuropePlug---------"); EuropePlug europePlug = new EuropePlugImpl(); europePlug.desc(); europePlug.func(); System.out.println("\nAmericanAdapter---------"); AmericanAdapter americanAdapter = new AmericanAdapter(americanPlug); americanAdapter.desc(); americanAdapter.func(); } }
输出
AmericanPlug--------- American American two plug EuropePlug--------- EuropePlug EuropePlug three plug AmericanAdapter--------- American Before adapter American two plug After adapter Process finished with exit code 0