通过配置文件,反射,工厂模式实现IOC控制反转

package designMode;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

interface Fruit{
  public abstract void eat();
}
class Apple implements Fruit{
  public void eat(){
    System.out.println("Apple");
  }  
}
class Orange implements Fruit{
  public void eat(){
    System.out.println("Orange");
  }  
}
class Factory{
  public static Fruit getInstance(String className){
    Fruit f=null;
    try{
      f=(Fruit)Class.forName(className).newInstance();
    }catch (Exception e) {
      e.printStackTrace();
    }
    return f;
   }
}
/*
* *方法2 通过配置文件
*/
class init{
  public static Properties getPro() throws FileNotFoundException, IOException{
    Properties pro=new Properties();
    File f=new File("resources/fruit.properties");
    if(f.exists()){
      pro.load(new FileInputStream(f));
    }

    else{
      pro.setProperty("apple", "designMode.Apple");
      pro.setProperty("orange", "designMode.Orange");
      pro.store(new FileOutputStream(f), "FRUIT CLASS");
    }
    return pro;
  }
}
public class ReflectFactoryIOC {
  public static void main(String[] a) throws FileNotFoundException, IOException{
/*
* *方法1
*/
/*   Fruit f=Factory.getInstance("designMode.Apple"); 

    if(f!=null){
      f.eat();
    }
*/
/*
* *方法2
*/
    Properties pro=init.getPro();
    Fruit ff=Factory.getInstance(pro.getProperty("orange"));
    System.out.println(pro.toString());
    if(ff!=null){
      ff.eat();
    }  
  }
}

/*fruit.properties*/

apple=designMode.Apple

orange=designMode.Orange

猜你喜欢

转载自www.cnblogs.com/Jmublog/p/12207307.html
今日推荐