用Properties和反射实现简单的 工厂模式

来源:互联网 发布:华为手机淘宝无法登陆 编辑:程序博客网 时间:2024/05/17 04:18


用Properties在本地生成一个配置文件,在工厂模式中使用反射调用此配置

实现灵活一点的工厂模式


一:产品接口,和工厂类

interface Fruit{public void eat();}class Apple implements Fruit{@Overridepublic void eat() {System.out.println("eat apple");}}class Bennana implements Fruit{public void eat(){System.out.println("eat bennana");}}class Factory{public static Fruit getInstance(String n){/*  没用到反射的工厂模式,不易于延展Fruit f = null;if(n.endsWith("apple")){f = new Apple();}if(n.endsWith("Bennana")){f = new Bennana();}*/Fruit f = null;try {Class<?> c = null;f = (Fruit) (c.forName(n)).newInstance();} catch (InstantiationException | IllegalAccessException| ClassNotFoundException e) {e.printStackTrace();}return f; }}



二:属性类和属性操作

class PropertiesOperate{private Properties pro  = null;private File file = new File("d:"+File.separator+"fruit.properties");//在D盘存储配置文件public PropertiesOperate(){this.pro = new Properties();if(file.exists()){try {pro.loadFromXML(new FileInputStream(file));//如果存在就加载此属性} catch (Exception e) {e.printStackTrace();}}else{this.save();//不存在的情况:调用save方法}}private void save(){this.pro.setProperty("apple","com.rt.factoryDemo.Apple");this.pro.setProperty("bennana","com.rt.factoryDemo.Bennana");//以上是添加仅有的两个键-值对try {this.pro.storeToXML(new FileOutputStream(this.file), "fruit");//写入文件} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public Properties getProperties(){return this.pro;//返回实例}}



三:测试Demo

public class FactoryDemo {public static void main(String[] args) {Properties pro = new PropertiesOperate().getProperties();//实例化属性Fruit f = Factory.getInstance(pro.getProperty("apple"));//反射得到“属性键值对匹配出来的”的实例。好处是输入简单些,配置文件也更易于维护f.eat();}}













原创粉丝点击