- 15.7类的生命周期
- 15.8工厂设计模式
- 15.8.1将反射应用在工厂模式上
- 15.8.2结合属性文件的工厂模式
- 【例15.29]属性操作类
- 【例15.30】测试程序
package file;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface Fruit
{
public void eat();
}
class Apple implements Fruit
{
public void eat()
{
System.out.println("吃苹果");
}
}
class Orange implements Fruit
{
public void eat()
{
System.out.println("吃橘子");
}
}
class Factory
{
public static Fruit getinstance(String path)
{
Fruit f = null;
try
{
f = (Fruit) Class.forName(path).newInstance();
}
catch (Exception e)
{
e.printStackTrace();
}
return f;
}
}
public class demo
{
public static void main(String[] args) throws Exception
{
Fruit f =Factory.getinstance("file.Apple");
if(f!=null)
{
f.eat();
}
}
}
15.8.2结合属性文件的工厂模式
【例15.29]属性操作类
【例15.30】测试程序
class Init
{
public static Properties getProperties()
{
Properties pro = new Properties();
File f = new File("d:"+File.separator+"fruit.properties");
try
{
if(f.exists())
{
pro.load(new FileInputStream(f));
}
else
{
pro.setProperty("apple", "file.Apple");
pro.setProperty("orange", "file.Orange");
pro.store(new FileOutputStream(f), "不存在文件,store的");
}
}
catch (Exception e)
{
e.printStackTrace();
}
return pro;
}
}
public class demo
{
public static void main(String[] args) throws Exception
{
Properties pro = Init.getProperties();
Fruit f =Factory.getinstance(pro.getProperty("orange"));
if(f!=null)
{
f.eat();
}
}
}



