单例设计模式
饿汉式懒汉式的调用方法,给个加注释的例子,写了亲
[解决办法]
http://www.iteye.com/topic/1121918
[解决办法]
public class Singleton{
private static Singleton{};
private static Singleton st=new Singleton();
public static Singleton get(){
return st;
}
[解决办法]
懒汉式
public class LazySingleton {
private static LazySingleton instance = null;
private LazySingleton(){};
public static synchronized LazySingleton getInstance(){
if(instance==null){
instance = new LazySingleton();
}
return instance;
}
} public class EagerSingleton {
private static EagerSingleton instance = new EagerSingleton();
private EagerSingleton(){};
public static EagerSingleton getInstance(){
return instance;
}
}
package com.javapatterns.singleton;
/**
* 饿汉式单例类
*
*/
public class EagerSingleton {
private static final EagerSingleton m_instance = new EagerSingleton();
/**
* 私有的构造方法
*/
private EagerSingleton(){
}
/**
* 功能:静态工厂方法
* @return EagerSingleton
* @param @return
* @date 2013-4-4
* @author arch_mage
*/
public static EagerSingleton getInstance() {
return m_instance;
}
}
package com.javapatterns.singleton;
/**
* 懒汉式单例类
*
*/
public class LazySingleton {
private static LazySingleton m_instance = null;
/**
* 私有构造方法
*/
private LazySingleton() {
}
synchronized public static LazySingleton getInstance() {
if(m_instance == null) {
m_instance = new LazySingleton();
}
return m_instance;
}
}