单例模式:保证运行内存中只有一个实体的实现模式就是单例模式,最常见的有饿汉模式、懒汉模式两种。
饿汉模式:
package com.madg.design.singleton;
public class Hungry
{
private static Hungry instance=new Hungry();
private Hungry() {};
public Hungry getInstance()
{
return instance;
}
}
懒汉模式:
package com.madg.design.singleton;
public class Lazy
{
private static Lazy instance;
private Lazy() {
}
public Lazy getInstance()
{
if(instance==null)
{
instance =new Lazy();
}
return instance;
}
}
线程安全:待续。。。