Head First設計モード学習ノート(四)工場モード

2727 ワード

工場モード
 
 
例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);
		}
	}
}