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("哈哈,没关系张,只是个测试而已!");
}
}
执行结果:测试