package cn.telling.factory; /** * 工廠類,用來建立API對象 * @ClassName: Api * TODO * @author xingle * @date 2015-10-28 下午4:27:45 */ public interface Api { public void opration(String s); }
package cn.telling.factory; /** * 接口具體實現對象A * @ClassName: ImplA * TODO * @author xingle * @date 2015-10-28 下午4:30:23 */ public class ImplA implements Api{ /** * * @Description: TODO * @param s * @author xingle * @data 2015-10-28 下午4:30:32 */ @Override public void opration(String s) { System.out.println("ImplA s=="+s); } }
package cn.telling.factory; /** * 接口具體實現對象B * @ClassName: ImplB * TODO * @author xingle * @date 2015-10-28 下午4:40:15 */ public class ImplB implements Api{ /** * * @Description: TODO * @param s * @author xingle * @data 2015-10-28 下午4:40:25 */ @Override public void opration(String s) { System.out.println("ImplB s=="+s); } }
配置文件用最簡單的properties文件,實際開發中可能是xml配置。定義一個名稱爲「FactoryTest.properties」的配置文件,放置到factory同一個包下面,內容以下:java
ImplAClass=cn.telling.factory.ImplA
ImplBClass=cn.telling.factory.ImplB
工廠類實現以下:api
package cn.telling.factory; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * 工廠類 * @ClassName: Factory TODO * @author xingle * @date 2015-10-28 下午4:31:52 */ public class Factory { /** * 具體的創造Api的方法,根據配置文件的參數來建立接口 * * @return 創造好的Api對象 */ public static Api createApi(String type) { // 直接讀取配置文件來獲取須要建立實例的類 // 至於如何讀取Properties,還有如何反射這裏就不解釋了 Properties p = new Properties(); InputStream in = null; try { in = Factory.class.getResourceAsStream("FactoryTest.properties"); p.load(in); } catch (IOException e) { System.out.println("裝載工廠配置文件出錯了,具體的堆棧信息以下:"); e.printStackTrace(); } finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } // 用反射去建立,那些例外處理等完善的工做這裏就不作了 Api api = null; try { if("A".equals(type)){ api = (Api) Class.forName(p.getProperty("ImplAClass")).newInstance(); }else if("B".equals(type)){ api = (Api) Class.forName(p.getProperty("ImplBClass")).newInstance(); } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return api; } }
客戶端程序:ide
package cn.telling;
import cn.telling.factory.Api;
import cn.telling.factory.Factory;
/**
*
* @ClassName: Client
* TODO
* @author xingle
* @date 2015-10-28 下午4:36:58
*/
public class Client {
public static void main(String[] args) {
Api api = Factory.createApi("B");
api.opration("哈哈,沒關係張,只是個測試而已!");
}
}
執行結果:測試