適配器模式(Adapter):將一個類的接口轉換成客戶但願的另一個接口。適配器模式使得本來因爲接口不兼容而不能一塊兒工做的那些類能夠一塊兒工做。java
package com.main; //適配器模式 public class AdapterDesignPattern { public static void main(String[] args) { PowerA powerA = new PowerAImpl(); input(powerA); System.out.println("---------------"); PowerB powerB = new PowerBImpl(); // input(powerB);//不能用,由於input()方法只能接受PowerA接口 PowerAdapter powerAdapter = new PowerAdapter(powerB); input(powerAdapter); } public static void input(PowerA powerA) { powerA.connect(); } } // 適配器,能夠適配電源A的適配器 class PowerAdapter implements PowerA { private PowerB powerB; public PowerAdapter(PowerB powerB) { this.powerB = powerB; } @Override public void connect() { powerB.insert(); } } interface PowerB { public void insert(); } class PowerBImpl implements PowerB { @Override public void insert() { System.out.println("電源B接口開始工做"); } } interface PowerA { public void connect(); } class PowerAImpl implements PowerA { @Override public void connect() { System.out.println("電源A接口開始工做"); } }