package org.lxh.demo15.factorydemo01 ; interface Fruit{ public void eat() ; // 吃水果 } class Apple implements Fruit{ public void eat(){ // 覆写eat()方法 System.out.println("** 吃苹果"); } }; class Orange implements Fruit{ public void eat(){ System.out.println("** 吃橘子") ; } }; class Factory{ public static Fruit getInstance(String className){ Fruit fruit = null ; try{ fruit = (Fruit)Class.forName(className).newInstance() ; }catch(Exception e){ e.printStackTrace() ; } return fruit ; } }; public class FactoryDemo01{ public static void main(String args[]){ Fruit f = Factory.getInstance("org.lxh.demo15.factorydemo01.Apple") ; if(f!=null){ f.eat() ; } } };
package org.lxh.demo15.factorydemo02 ; import java.util.Properties ; import java.io.File ; import java.io.FileOutputStream ; import java.io.FileInputStream ; interface Fruit{ public void eat() ; // 吃水果 } class Apple implements Fruit{ public void eat(){ // 覆写eat()方法 System.out.println("** 吃苹果"); } }; class Orange implements Fruit{ public void eat(){ System.out.println("** 吃橘子") ; } }; class Init{ public static Properties getPro(){ Properties pro = new Properties() ; File f = new File("d:\\fruit.properties") ; // 找到属性文件 try{ if(f.exists()){ // 文件存在 pro.load(new FileInputStream(f)) ; // 读取属性 }else{ pro.setProperty("apple","org.lxh.demo15.factorydemo02.Apple") ; pro.setProperty("orange","org.lxh.demo15.factorydemo02.Orange") ; pro.store(new FileOutputStream(f),"FRUIT CLASS") ; } }catch(Exception e){} return pro ; } }; class Factory{ public static Fruit getInstance(String className){ Fruit fruit = null ; try{ fruit = (Fruit)Class.forName(className).newInstance() ; }catch(Exception e){ e.printStackTrace() ; } return fruit ; } }; public class FactoryDemo02{ public static void main(String args[]){ Properties pro = Init.getPro() ; Fruit f = Factory.getInstance(pro.getProperty("apple")) ; if(f!=null){ f.eat() ; } } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理