public class CEOextends Staff {
// 1、饿汉单例模式
private static final CEOceo =new CEO();
//构造函数私有
private void CEO() {
}
//公有的静态函数,对外暴露获取单例对象的接口
public static CEO getCeo() {
return ceo;
}
}
****************************************************************************************
public class CEOextends Staff {
private static CEOinstance =null;
private CEO() {
}
// 2、懒汉模式
public static synchronized CEO getInstance() {
if (null ==instance) {
instance =new CEO();
}
return instance;
}
}
***********************************************************************
public class CEOextends Staff {
private static CEOinstance =null;
private CEO() {
}
// 3、Double Check Lock
public static CEO getInstance(){
if (null ==instance){
synchronized (CEO.class){
if (null ==instance){}
instance =new CEO();
}
}
return instance;
}
}
*********************************************************************
public class CEOextends Staff {
private CEO() {
}
public static CEO getInstance() {
return SingletonHolder.ceo;
}
/*4、静态内部类 推荐使用的单例模式*/
private static class SingletonHolder {
private static final CEOceo =new CEO();
}
}
------------------------------------------------------------------------------------------------------------------
// 要杜绝单例对象在反序列化是重新生成对象 需加入该方法
private Object readResolve()throws ObjectStreamException{
return instance;
}
***********************************************************************************************
/*5、枚举单例*/
public enum CeoEnumSingleimplements InterStaff{
INSTANCE;
@Override
public void work() {
}
}
*******************************************************************************************
/*使用容器实现单例模式*/
public class SingletonManager {
private static MapobjectMap =new HashMap();
private SingletonManager() {
}
public static void registerService(String key, Object instance) {
if (!objectMap.containsKey(key)) {
objectMap.put(key,instance);
}
}
public static Object getService(String key){
return objectMap.get(key);
}
}
网友评论