惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Recent Announcements
Recent Announcements
人人都是产品经理
人人都是产品经理
月光博客
月光博客
博客园 - 三生石上(FineUI控件)
GbyAI
GbyAI
博客园 - 司徒正美
美团技术团队
Vercel News
Vercel News
IT之家
IT之家
U
Unit 42
Y
Y Combinator Blog
罗磊的独立博客
Microsoft Security Blog
Microsoft Security Blog
MongoDB | Blog
MongoDB | Blog
Jina AI
Jina AI
V
Visual Studio Blog
B
Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
MyScale Blog
MyScale Blog
博客园 - 叶小钗
A
About on SuperTechFans
WordPress大学
WordPress大学
Hugging Face - Blog
Hugging Face - Blog
B
Blog RSS Feed

博客园 - Star.Stroll

【Chrome扩展】Reload image 重载图片 [原创]RegularJS [原创]虚拟化技术真的能让企业降低成本吗? [原创]纯Java获得本地MAC地址 [原创]GCC动态链接库的编译与使用简例 [原创]Cygwin的中文支持(解决乱码) [原创]程序员日志:自制随笔程序 [原创]程序员日志:程序员的快捷方式 [原创]Java Socket(套接字)自学笔记1 [原创]透明的DIV提示框(兼容IE与Firefox) 深入HashCode方法 JavaScript代码实例:拖动对象 Drag Object (兼容:IE、Firefox、Opera ... ) Tomcat中用web.xml控制Web应用详解(2) Tomcat中用web.xml控制Web应用详解(1) java.sql.ResultSet 新增、更新、刪除資料 [原创]Object.clone()的作用与用法 Java 范型编程 Singleton模式(单态模式) Builder模式
[原创]一个简单例子解释 Java 工厂模式
Star.Stroll · 2008-01-31 · via 博客园 - Star.Stroll

    其实工厂模式结构并不复杂,其目的只有一个就是解耦.废话少说看例子吧.这个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接口实例
    }

}

另外这里还有一个更为完整的例子,可用Eclipse打开
https://files.cnblogs.com/starstroll/ModeTrain2.rar