首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

利用多例方式编写配置文件读取器

2012-10-27 
利用多例模式编写配置文件读取器??? 多例模式是单例模式的一个变种,可以根据一个特征值购建一个唯一的在JV

利用多例模式编写配置文件读取器

??? 多例模式是单例模式的一个变种,可以根据一个特征值购建一个唯一的在JVM中的实例,有多少个特征值就可以创建多少个实例,如果这个特征值是无限的,就可以创建无限多个实例,但是每个实例一定是和特征值绑定的,每一个特征值的实例在JVM中,有且只有1个。

??? 根据这个特点,想到如下的一个应用:

??? 项目中有多个配置文件,但每一个配置文件应该只有一个实例在内存中,没有必要为每一个文件写一个单例类,每一个配置文件名,就是一个特征值,这个应用刚好符合多例模式的使用。

?

package com.balance.message.common.util;import java.io.InputStream;import java.net.URL;import java.util.HashMap;import java.util.Map;import java.util.Properties;public class MessageProperties {private static Map<String,MessageProperties> map_messageProperties = new HashMap<String,MessageProperties>(19);private Properties ps;private MessageProperties(String propertiesFileName){InputStream in = null;try{ps = new Properties();URL url = this.getClass().getClassLoader().getResource(propertiesFileName);if(url != null){in = this.getClass().getClassLoader().getResource(propertiesFileName).openStream();}else {in = this.getClass().getResourceAsStream(propertiesFileName);}ps.load(in);}catch(Exception e){e.printStackTrace();}finally{if(in != null){try{in.close();in = null;}catch(Exception e){e.printStackTrace();}}}}public static MessageProperties getInstance(String propertiesFileName){if(!map_messageProperties.containsKey(propertiesFileName)){MessageProperties messageProperties  = new MessageProperties(propertiesFileName);map_messageProperties.put(propertiesFileName, messageProperties);}return map_messageProperties.get(propertiesFileName);}public String getValue(String key){return ps.getProperty(key);}}

?

我们在classpath下放上下面2个配置文件

??? msg.head.properties

tds.intra.day.header.cut.as = 160tds.intra.day.header.cut.atd = 160tds.intra.day.header.cut.fd = 160tds.intra.day.header.cut.sq = 160

??? msg.tailer.properties

tds.intra.day.trailer.cut.as = 8000tds.intra.day.trailer.cut.atd = 7900tds.intra.day.trailer.cut.fd = 6800tds.intra.day.trailer.cut.sq = 7300

?

下面使用这个MessageProperties去读取属性,

public static void main(String[] args){System.out.println(MessageProperties.getInstance("msg.head.properties").getValue("tds.intra.day.header.cut.fd"));System.out.println(MessageProperties.getInstance("msg.tailer.properties").getValue("tds.intra.day.trailer.cut.as"));}
?

?

执行结果:

160
8000

?

热点排行