一、項目截圖java
二、黑白打印機類ide
package com.example.demo.printer; public class GrayPrinter implements Printer{ @Override public void init() { System.out.println("啓動打印機"); } @Override public void print(String txt) { System.out.println("打印黑白文字:".concat(txt)); } }
三、彩色打印機類測試
package com.example.demo.printer; public class ColorPrinter implements Printer { @Override public void init() { System.out.println("啓動彩色打印機!"); } @Override public void print(String txt) { System.out.println("打印彩色文字:".concat(txt)); } }
四、電腦this
package com.example.demo.printer; /** * Created by Admin on 2018/5/8. */ public class Computer { Printer p; public void printTxt(String txt){ p.init(); p.print(txt); } public Printer getP() { return p; } public void setP(Printer p) { this.p = p; } }
五、配置文件spa
printer = com.example.demo.printer.ColorPrinter
配置文件的建立: code
六、讀取bean配置並建立實例類對象
package com.example.demo.printer; import java.io.IOException; import java.util.Properties; public class GetBeans { private static Properties p = new Properties(); static{ try{ //讀取bean配置文件 p.load(TestComputer.class.getResourceAsStream("/bean.properties")); }catch(IOException e){ System.out.println("沒法找到配置文件!"); } } public static Object getBean(String keyName){ Object o = null; try{ //根據屬性文件中定義的關鍵字建立實例 o = Class.forName(p.get(keyName).toString()).newInstance(); }catch (Exception e){ System.out.println("沒法實例化對象!"); } return o; } }
七、打印機接口blog
package com.example.demo.printer; public interface Printer { void init(); void print(String txt); }
八、測試類接口
package com.example.demo.printer; public class TestComputer { public static void main(String[] args) { Computer pcl = new Computer(); //實現不用new關鍵字 Printer p = (Printer) GetBeans.getBean("printer"); pcl.setP(p); pcl.getP().print("打印測試頁..."); } }
九、效果get
當電腦要安裝黑白打印機的時候只須要將配置文件中的printer變量的值設置爲
printer = com.example.demo.printer.GrayPrinter
這樣作的好處就是實現,既不須要改變Computer類也不須要改變測試類中的代碼,經過配置的方式就能夠選擇不一樣的打印機進行安裝