面试:你懂什么是分布式系统吗?Redis分布式锁都不会?>>>
建立配置文件,fruit.properties,内容如下:
apple=com.gavin.reflect.Apple2
orange=com.gavin.reflect.Orange2
并将该配置文件放在res文件夹下
package com.gavin.reflect;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
/**
*
* 而且用户也无法知道一个接口有多少个可以使用的子类,所以我们通过属性文件的形式配置所需要的子类。
* @author gavin
* 使用配置文件,实现工厂方法
*
* 2013-5-5
*/
class FactoryPatttern
{
public static void main(String[] a) throws FileNotFoundException, IOException
{
Properties pro = getPro();
String property=pro.getProperty("apple");
fruit2 f = Factory2.getInstance(property);
if (f != null)
{
f.eat();
}
}
// 操作属性文件类
public static Properties getPro() throws FileNotFoundException, IOException
{
Properties pro = new Properties();
File f = new File("res/fruit.properties");
if (f.exists())
{
pro.load(new FileInputStream(f));
} else
{
System.out.println("文件不存在");
}
return pro;
}
}
interface fruit2
{
public abstract void eat();
}
class Apple2 implements fruit2
{
public void eat()
{
System.out.println("Apple");
}
}
class Orange2 implements fruit2
{
public void eat()
{
System.out.println("Orange");
}
}
class Factory2
{
public static fruit2 getInstance(String ClassName)
{
fruit2 f = null;
try
{
f = (fruit2) Class.forName(ClassName).newInstance();
} catch (Exception e)
{
e.printStackTrace();
}
return f;
}
}