Head First 设计模式学习笔记(四)工厂模式

工厂模式

例子1、

/**
 * IOC模式简单实例
 */

/**
 * 运行类
 */
public class MainClass {
    /**
     * 主函数
     */
    public static void main(String[] args) {
        try {
            PrinterFactory.createPrinter().printByString("Hello World~!");
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }
}

/**
 * Printer接口
 */
interface IF_Printer {
    /**
     * 接口printByString方法声明
     */
    public void printByString(String str);
}

/**
 * MyPrinter实现Printer接口
 */
class MyPrinter implements IF_Printer {
    public void printByString(String str) {
        System.out.println(str);
    }
}

/**
 * IF_Printer对象工厂,用于创建实现接口的类对象
 */
class PrinterFactory {
    /**
     * 工厂方法,返回IF_Printer接口实例
     */
    public static IF_Printer createPrinter() throws InstantiationException,
            ClassNotFoundException, IllegalAccessException {
        String str = "MyPrinter";//通过字符串寻找实现接口的类,字符串可从文件中读取获得,从而实现IOC模式
        return (IF_Printer) Class.forName(str).newInstance();//返回IF_Printer接口实例
    }
}

例子2、

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");//创建文件流对象stream
			myProperties.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类库URL
			URLClassLoader 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);
		}
	}
}

猜你喜欢

转载自chxiaowu.iteye.com/blog/1235829