定義介面
package com.ttjslbz.factory;public interface Api {void functionA();}
定義實現A
public class ImplA implements Api {@Overridepublic void functionA() {// TODO Auto-generated method stubSystem.out.print("This is implement A for Api");}}
定義實現B
public class ImplB implements Api {@Overridepublic void functionA() {// TODO Auto-generated method stubSystem.out.print("This is implement B for Api");}}
工廠
public class Factory {// 預先載入需要讀取的設定檔private static Properties p;static {InputStream in = Factory.class.getResourceAsStream("Factory.properties");;p = new Properties();try {p.load(in);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {try {in.close();} catch (IOException e) {e.printStackTrace();}}}public static Api creatApi(String propertie) {Apiapi = null;try { api = (Api)Class.forName(p.getProperty(propertie)).newInstance();}catch(InstantiationException e){e.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}return api;}}
用戶端
public class Client {public static void main(String[] args) {Api apiA = Factory.creatApi("IMPLEMENTA");apiA.functionA();Api apiB= Factory.creatApi("IMPLEMENTB");apiB.functionA();Api apiC = Factory.creatApi("IMPLEMENTC");apiC.functionA();}}