欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-03-09 20:29:38
...


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

实现灵活一点的工厂模式


一:产品接口,和工厂类

interface Fruit
{
	public void eat();
}
class Apple implements Fruit
{
	@Override
	public 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 block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.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();
		
	}

}