---
title: "利用多例模式编写配置文件读取器"
author: "squll369"
date: "2011-07-13T23:26:51Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-03-06T14:55:28Z"
id: 1123884
url: "https://squll369.iteye.com/blog/1123884"
---

多例模式是单例模式的一个变种，可以根据一个特征值购建一个唯一的在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

```
header.cut.as = 160
header.cut.atd = 160
header.cut.fd = 160
header.cut.sq = 160
```

    msg.tailer.properties

```
trailer.cut.as = 8000
trailer.cut.atd = 7900
trailer.cut.fd = 6800
trailer.cut.sq = 7300
```

 

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

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

 

 

执行结果：

160  
8000