不用反射机制的工厂模式
/** 2 * 工厂模式 3 */ 4 interface fruit{ 5 public abstract void eat(); 6 } 7 8 class Apple implements fruit{ 9 public void eat(){ 10 System.out.println("Apple"); 11 } 12 } 13 14 class Orange implements fruit{ 15 public void eat(){ 16 System.out.println("Orange"); 17 } 18 } 19 // 构造工厂类 20 // 也就是说以后如果我们在添加其他的实例的时候只需要修改工厂类就行了 21 class Factory{ 22 public static fruit getInstance(String fruitName){ 23 fruit f=null; 24 if("Apple".equals(fruitName)){ 25 f=new Apple(); 26 } 27 if("Orange".equals(fruitName)){ 28 f=new Orange(); 29 } 30 return f; 31 } 32 } 33 34 class hello{ 35 public static void main(String[] a){ 36 fruit f=Factory.getInstance("Orange"); 37 f.eat(); 38 } 39 }
这种当我们添加一个子类的时候就要去修改工厂类了。
package Reflect; 2 3 interface fruit{ 4 public abstract void eat(); 5 } 6 7 class Apple implements fruit{ 8 public void eat(){ 9 System.out.println("Apple"); 10 } 11 } 12 13 class Orange implements fruit{ 14 public void eat(){ 15 System.out.println("Orange"); 16 } 17 } 18 19 class Factory{ 20 public static fruit getInstance(String ClassName){ 21 fruit f=null; 22 try{ 23 f=(fruit)Class.forName(ClassName).newInstance(); 24 }catch (Exception e) { 25 e.printStackTrace(); 26 } 27 return f; 28 } 29 } 30 31 class hello{ 32 public static void main(String[] a){ 33 fruit f=Factory.getInstance("Reflect.Apple"); 34 if(f!=null){ 35 f.eat(); 36 } 37 } 38 }
使用反射机制的工厂模式可以通过反射取得接口的实例,但是需要传入完整的包和类名。而且用户也无法知道一个接口有多少个可以使用的子类,所以我们通过属性文件的形式配置所需要的子类。
3.使用反射机制并结合属性文件的工厂模式(即IoC)
首先创建一个fruit.properties的资源文件:
1 apple=Reflect.Apple 2 orange=Reflect.Orange
然后编写主类代码:
1 package Reflect; 2 3 import java.io.*; 4 import java.util.*; 5 6 interface fruit{ 7 public abstract void eat(); 8 } 9 10 class Apple implements fruit{ 11 public void eat(){ 12 System.out.println("Apple"); 13 } 14 } 15 16 class Orange implements fruit{ 17 public void eat(){ 18 System.out.println("Orange"); 19 } 20 } 21 //操作属性文件类 22 class init{ 23 public static Properties getPro() throws FileNotFoundException, IOException{ 24 Properties pro=new Properties(); 25 File f=new File("fruit.properties"); 26 if(f.exists()){ 27 pro.load(new FileInputStream(f)); 28 }else{ 29 pro.setProperty("apple", "Reflect.Apple"); 30 pro.setProperty("orange", "Reflect.Orange"); 31 pro.store(new FileOutputStream(f), "FRUIT CLASS"); 32 } 33 return pro; 34 } 35 } 36 37 class Factory{ 38 public static fruit getInstance(String ClassName){ 39 fruit f=null; 40 try{ 41 f=(fruit)Class.forName(ClassName).newInstance(); 42 }catch (Exception e) { 43 e.printStackTrace(); 44 } 45 return f; 46 } 47 } 48 49 class hello{ 50 public static void main(String[] a) throws FileNotFoundException, IOException{ 51 Properties pro=init.getPro(); 52 fruit f=Factory.getInstance(pro.getProperty("apple")); 53 if(f!=null){ 54 f.eat(); 55 } 56 } 57 } 58 //【运行结果】:Apple