您的位置:首页 > 大数据 > 物联网

物联网数据中心项目第五天修改

2020-07-12 17:21 281 查看

模块化接口

1.定义模块化接口,定义init方法

模块化接口WossModuleInit,用来对每个模块进行配置初始化。

在其中定义所有模块都需要的方法,常用于初始化。将所需要的配置文件信息传递给该类,得到之后进行初始化操作,在执行真正的子类功能方法之前执行该方法。

public class ConfigurationImpl implements Configuration{
//存储解析以及反射的实例化对象
private Map<String, WossModuleInit> map=new HashMap<String, WossModuleInit>();
private Properties properties=new Properties();//存储三级标签及文本内容
public ConfigurationImpl() {
this("src/main/java/config.xml");
}
public ConfigurationImpl(String path) {
try {
//1.获取解析对象,解析配置文件
SAXReader reader=new SAXReader();
//2.解析xml文件,将XML文件以document文档树形式加载到内存中
Document document = reader.read(path);
//3.获取根节点
Element root = document.getRootElement();
//4.获取所有的二级标签
List<Element> elements= root.elements();
//5.遍历集合获取属性值
for (Element e : elements) {
//获取属性节点的属性值
String value = e.attributeValue("class");
//6.获取镜像所对应的实例对象
Object newInstance = Class.forName(value).newInstance();
//7.map中存放对象
if(newInstance instanceof WossModuleInit) {
map.put(e.getName(),(WossModuleInit)newInstance);
}
//8.读取三级标签,获取文本内容
List<Element> elements2=e.elements();
for (Element e2 : elements2) {
properties.setProperty(e2.getName(), e2.getTextTrim());
}
((WossModuleInit)newInstance).init(properties);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
public Log getLogger() throws Exception {
return (Log) map.get("Log");
}

public Server getServer() throws Exception {
return (Server) map.get("Server");
}

public Client getClient() throws Exception {
return (Client) map.get("Client");
}

public DBStore getDbStore() throws Exception {
return (DBStore) map.get("DBStore");
}

public Gather getGather() throws Exception {
return (Gather) map.get("Gather");
}

}

该版本先将实例对象以对象名和对象的键值对存入HashMap集合中。
后遍历次一级标签,以标签名和标签值为一对,存入properties对象中,由于所有模块都间接继承了模块化接口,都有init方法,所以利用多态性,直接将实例强转为WossModuleInit类型,直接调用init()方法初始化,在各个模块中,执行类似的赋值代码。

public void init(Properties properties) throws Exception {
ip=properties.getProperty("ip");
port=Integer.parseInt(properties.getProperty("port"));

}

配置初始化完成后,返回HashMap集合。
因为以上步骤全部发生在有参构造器中,并且在无参构造器中调用有参构造器方法。所以,可以定义一系列类的实例的获取方法,从map集合中通过接口名,取得对应实现类的实例,强转后返回出去。所以一旦这个类被实例化,就可以调用getXXX的方法,获取强转后的实例对象,以便于直接调用所需要的方法。

与前一版相比新增了模块化思想,非常重要!

至此,项目完结。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: