java反射机制学习(五):工厂模式
程序员文章站
2022-07-14 08:55:33
...
1、普通的工厂模式:
//定义接口 interface Fruit { public void eat(); } //苹果类 class Apple implements Fruit{ public void eat(){ System.out.println("*****吃苹果"); } } //橘子类 class Orange implements Fruit{ public void eat(){ System.out.println("******吃橘子"); } } //梨子类 class Pear implements Fruit{ public void eat(){ System.out.println("******吃梨"); } } //普通工厂类 class Factory{ public static Fruit getInstance(String className){ Fruit fruit = null; if("apple".equals(className.toLowerCase())){ fruit = new Apple(); } if("orange".equals(className.toLowerCase())){ fruit = new Orange(); } return fruit; } } //main方法测试 public class FactoryDemo { public static void main(String[] args) throws Exception { //实例化 Fruit f = Factory.getInstance("orange"); f.eat(); } }
普通工厂类存在一个问题:当添加新的fruit子类时需要修改Factory类。因此使用反射来解决这个问题。
2、使用反射的工厂类:
//使用反射的工厂类 class FactoryByReflect{ public static Fruit getInstance(String className){ Fruit f = null; try{ f = (Fruit)Class.forName(className).newInstance(); }catch(Exception e){ e.printStackTrace(); } return f; } } //main方法测试 public class FactoryDemo { public static void main(String[] args) throws Exception { //使用反射进行改进 Fruit f2 = FactoryByReflect.getInstance("com.wjl.reflect.Pear"); f2.eat(); } }
使用反射机制进行改进后依然存在一个问题:className配置时需要添加过长的包名且不能灵活配置 ,因此考虑使用配置文件的方式进一步改进。
3、使用配置文件的工厂类:
先在src下新建一个fruit.properties内容如下:
apple=com.wjl.reflect.Apple orange=com.wjl.reflect.Orange pear=com.wjl.reflect.Pear
编写InitProperties类进行读取和测试:
class InitProperties{ public static Properties getPro(){ Properties pro = new Properties(); try{ //获取src下的properties配置文件 String filePath = InitProperties.class.getResource("/fruit.properties").getPath(); // System.out.println("配置文件路径:"+filePath); filePath = URLDecoder.decode(filePath,"utf-8");//将路径中的空格(%20)替换成空格 File file = new File(filePath); if(file.exists()){ pro.load(new FileInputStream(file)); /* //或者使用一下方法直接加载数据 InputStream in = InitProperties.class.getClassLoader().getResourceAsStream("fruit.properties"); pro.load(in); */ }else{ pro.setProperty("apple", "com.wjl.reflect.Apple"); pro.setProperty("orange", "com.wjl.reflect.Orange"); pro.setProperty("pear", "com.wjl.reflect.Pear"); pro.store(new FileOutputStream(file),"Fruit class"); } }catch(Exception e){ e.printStackTrace(); } return pro; } } //main方法测试 public class FactoryDemo { public static void main(String[] args) throws Exception { //使用配置文件 Properties pro = InitProperties.getPro(); Fruit f3 = (Fruit) Class.forName(pro.getProperty("apple")).newInstance(); f3.eat(); } }
上一篇: 什么是copy and swap