1.单例设计模式
解决的问题:就是可以保证一个类在内存中的对象唯一性。比如对于多个程序使用同一个配置信息对象时,就需要保证该对象的唯一性。
如何保证对象的唯一性呢?
1.不允许其他程序用new来创建该类对象。
2.在该类中创建一个本类实例。
3.对外提供一个方法让其他程序可以获取该对象。
步骤:
1.私有化该类的构造函数
2.通过new在本类中创建的一个本类对象
3.定义一个公有的静态方法,将创建的对象返回
单例模式之饿汉式
代码:
package day08;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
public class ConfigureFile {
private static final ConfigureFile configureFile=new ConfigureFile();
private ConfigureFile()
{}
public static ConfigureFile getInstance()
{
return configureFile;
}
public HashMap<String,String> getInfo() throws IOException
{
HashMap<String,String> map=new HashMap<String, String>();
Properties p=new Properties();
FileReader fr=new FileReader("D:\\1.properties");
p.load(fr);
// Enumeration<?> en=p.propertyNames();
// ArrayList<?> list=Collections.list(en);
// for(ListIterator<?> it=list.listIterator();it.hasNext();)
// {
// String key=(String)it.next();
// map.put(key, p.getProperty(key));
// }
Set<String> set=p.stringPropertyNames();
for(Iterator<String> it=set.iterator();it.hasNext();)
{
String key=it.next();
map.put(key, p.getProperty(key));
}
return map;
}
}
package day08;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
public class SingleEntityMode {
public static void main(String[] args) throws IOException
{
ConfigureFile configure=ConfigureFile.getInstance();
HashMap<String, String> map=configure.getInfo();
//keySet(),entrySet(),values等方法遍历地图
Set<Entry<String, String>> set=map.entrySet();
for(Iterator<Entry<String, String>> it=set.iterator();it.hasNext();)
{
Entry<String, String> e=it.next();
String key=e.getKey();
String value=e.getValue();
System.out.println(key+" : "+value);
}
}
}
单例模式之懒汉式
代码如下:
package day08;
public class LazyMenMode {
private static LazyMenMode lazy;
private LazyMenMode()
{}
public static LazyMenMode getInstance()
{
if(null==lazy)
{
lazy = new LazyMenMode();
}
return lazy;
}
}
不过这种在多线程中,存在线程安全问题。以下来分析一下,比如线程1和线程2在获取该类实例,线程1进来判断null==lazy成立后,没有执行下去,就被中断了,这时线程2进来就会产生两个不同的实例,就不能保证该类在内存中的实例唯一。改进如下:
package day08;
public class LazyMenMode {
private static LazyMenMode lazy;
private LazyMenMode()
{}
public static LazyMenMode getInstance()
{
if(null==lazy)
{
synchronized(LazyMenMode.class)
{
if(null==lazy)
{
lazy = new LazyMenMode();
}
}
}
return lazy;
}
}