反射机制对设计模式的影响和改进
反射机制是一种强大的应用功能,特别是对工厂设计模式的改进:
1.不用修改工厂类,
2.Properties配置文件与代码分离!
——实例:
package com.mldn;
import java.io.*;
import java.util.*;
/*
反射机制对程序开发的支持,对工厂设计模式的改进!
*/
public class FactoryDemo
{
public static void main(String[] args)
{
Fruit f = Factory.getInstance(new Init().getPro().getProperty(“apple”));
if (f != null)
{
f.eat(); // 执行解耦合
}
}
}
class Factory
{
public static Fruit getInstance(String className) // 获取接口的子类实例,解耦合
{
Fruit fruit = null; // 声明使用的类
Class> classT = null; // 声明Class对象
try
{
classT = Class.forName(className); // 反射机制的支持,获取运行时类
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
try
{
fruit = (Fruit)classT.newInstance(); // 反射机制的支持,有运行时类获取一个默认实例
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
return fruit;
}
}
class Init
{
public Properties getPro()
{
File file = new File(“fruit.properties”); // 打开配置文件:”./fruit.Properties”
Properties pro = new Properties(); // 实例化一个空的属性对象
OutputStream out = null; // 声明字节输出流,用于存储
InputStream in = null; // 声明字节输入流,用于读取
try
{
if (!file.exists())
{
file.createNewFile();
}
else if (new FileInputStream(file).read() != -1) // 配置信息不为空
{
pro.load(in); // 载入配置信息
}
else
{
pro.setProperty(“apple”, “com.mldn.Apple”); // 设置配置信息
pro.setProperty(“orange”, “com.mldn.Orange”);
out = new FileOutputStream(file); // 实例化输出流
pro.store(out, “Fruit class”); // 存储
out.close();
}
}
catch (FileNotFoundException e)
{
System.out.println(“配置文件不存在!”);
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return pro; // 返回载入配置信息的属性对象
}
}
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(“~·~吃橘子!”);
}
}
声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 嗅谱网
转载请注明:转自《反射机制对设计模式的影响和改进》
本文地址:http://www.xiupu.net/archives-146.html
关注公众号:
微信赞赏
支付宝赞赏