11、代码与配置分离

1、  基于反射的工厂设计模式

在前面的设计模式中,我们展示了简单的工厂模式,但是它有个弊端,就是如果我们要增加一个子类的话,我们必须修改我们的对象工厂(增加新类的判断)

而通过反射模式,我们可以解决这个问题,代码如下

interface Fruit{

    publicvoid eat();

}

class Apple implements Fruit{

    publicvoid eat(){ System.out.println("we eat apple");}

}

class Orange implements Fruit{

    publicvoid eat(){ System.out.println("we eat Orange");}

}

class Factory{

    publicstatic Fruit getInstance(String className){

        Fruit f =null;

        //此处使用了反射方法生成类的实例对象

        //所以不管真假多少个Fruit的实现类,都不需要修改Factory

        try{

            Class c = Class.forName(className);

            f =(Fruit)c.newInstance();

        }

        catch(Exception ex){

            ex.printStackTrace();

        }

        return f;

    }

}

 

publicclass hello{

    publicstaticvoid main(String args[])throws Exception{

       

        Fruit f1 = Factory.getInstance("Apple");

        f1.eat();

        Fruit f2 = Factory.getInstance("Orange");

        f2.eat();

    }

}

 

 

2、  结合属性文件的工厂模式

以上工厂使用反射获取接口的实例对象,但在操作时需要传入完整的包类名称,而且用户无法知道工厂有多少个类可以使用

这时我们可以结合属性配置文件来配置需要使用的类信息,程序与配置的分离是java开发中一个非常重要的模式,如下

import java.util.Properties;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

 

interface Fruit{

    publicvoid eat();

}

class Apple implements Fruit{

    publicvoid eat(){ System.out.println("we eat apple");}

}

class Orange implements Fruit{

    publicvoid eat(){ System.out.println("we eat Orange");}

}

class Factory{

    publicstatic Fruit getInstance(String className){

        Fruit f =null;

        try{

            Class c = Class.forName(className);

            f =(Fruit)c.newInstance();

        }

        catch(Exception ex){

            ex.printStackTrace();

        }

        return f;

    }

}

//从文件获取属性配置信息

class Init{

    publicstatic Properties getProperties(){

        Properties ps =new Properties();

        //配置文件

        File f =new File("C:"+ File.separator +"AAA\\Fruit.properties");

       

        try{

            if(f.exists()){

                //加载配置文件内容到属性对象

                ps.load(new FileInputStream(f));

            }else{

                ps.setProperty("App","Apple");

                ps.setProperty("Org","Orange");

                //将属性对象写入到配置文件中

                ps.store(new FileOutputStream(f),"Fruit Config");

            }

        }catch(Exception e){

            e.printStackTrace();

        }

       

        return ps;

    }

}

 

publicclass hello{

    publicstaticvoid main(String args[])throws Exception{

        //获取属性配置

        Properties classConf = Init.getProperties();

        //根据key读取配置的value的值

        //可以看到我们简化了包类名,相当于包类名的简写

        Fruit f1 = Factory.getInstance(classConf.getProperty("App"));

        f1.eat();

        Fruit f2 = Factory.getInstance(classConf.getProperty("Org"));

        f2.eat();

    }

}

 

 

3、  Annotation,注解,用于标识程序的一些额外信息

 

 

4、  JDBC,java database connector(java数据库连接器)

 

你可能感兴趣的:(java基础)