Head First 设计模式学习笔记(四)工厂模式
工厂模式
?
?
例子1、
?
?
package mainpackage;import projectinterface.IF_Printer;import java.util.Properties;import java.io.*;import java.net.URL;import java.net.URLClassLoader;import javax.swing.JOptionPane;public class MainClass {public static void main(String[] args) {try {/** * myProperties读取配置文件config.properties获取运行信息 */Properties myProperties = new Properties();//myProperties属性实例FileInputStream stream = new FileInputStream("config.properties");//创建文件流对象streammyProperties.load(stream);//读取属性配置文件String className = myProperties.getProperty("printerClass");//获得IF_Printer实现类String printString = myProperties.getProperty("printString");//获取要打印的字符串String libName = myProperties.getProperty("libName");//获取jar类库文件名/** * 根据libName动态加载jar类库 */URL url = new File(libName).toURI().toURL();//得到jar类库URLURLClassLoader loader = new URLClassLoader(new URL[] { url });//实例化类加载器IF_Printer printer = (IF_Printer) loader.loadClass(className).newInstance();//动态实例化对象printer.printString(printString);//执行接口方法printString} catch (Exception e) {JOptionPane.showMessageDialog(null, e.toString());} finally {System.exit(0);}}}