java语言factory_一个简单例子解释 Java factory
其實工廠模式結構并不復雜,其目的只有一個就是解耦.廢話少說看例子吧.這個HelloWorld就足夠說明工廠模式在Java語言里的實現方法.
/** *//**
* 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接口實例
}
}
總結
以上是生活随笔為你收集整理的java语言factory_一个简单例子解释 Java factory的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 天平应什么放置_电子天平讲义全解(使用/
- 下一篇: java美元兑换,(Java实现) 美元