设计模式之单例模式三种实现
来源:互联网 发布:手机短信恢复 软件 编辑:程序博客网 时间:2024/05/22 15:01
/**
* 懒汉式
* @author niwei
* 懒汉式单例类.在第一次调用的时候实例化
*/
public class Sinleton {
//私有的默认构造子
private Sinleton(){};
//注意,这里没有final
private static Sinleton instance = null;
//静态工厂方法
public synchronized static Sinleton getSinleton(){
if(instance == null){
instance = new Sinleton();
}
return instance;
}
}
package com.mw.mbox.boss.demo;
/**
* 饿汉式
* @author niwei
* //饿汉式单例类.在类初始化时,已经自行实例化
*/
public class Sinleton2 {
//私有的默认构造方法
private Sinleton2(){}
//已经自行实例化
private static Sinleton2 sinleton = new Sinleton2();
//静态工厂方法
public static Sinleton2 getSinleton(){
return sinleton;
}
}
package com.mw.mbox.boss.demo;
import java.util.HashMap;
import java.util.Map;
//登记式单例类.
//类似Spring里面的方法,将类名注册,下次从里面直接获取。
public class Singleton3 {
private static Map<String,Singleton3> map = new HashMap<String,Singleton3>();
static{
Singleton3 single = new Singleton3();
map.put(single.getClass().getName(), single);
}
//保护的默认构造子
protected Singleton3(){}
//静态工厂方法,返还此类惟一的实例
public static Singleton3 getInstance(String name) {
if(name == null) {
name = Singleton3.class.getName();
System.out.println("name == null"+"--->name="+name);
}
if(map.get(name) == null) {
try {
map.put(name, (Singleton3) Class.forName(name).newInstance());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return map.get(name);
}
//一个示意性的商业方法
public String about() {
return "Hello, I am RegSingleton.";
}
public static void main(String[] args) {
Singleton3 single3 = Singleton3.getInstance(null);
System.out.println(single3.about());
}
}
- 设计模式之单例模式三种实现
- 设计模式之单例模式(三种实现方式)
- 设计模式之单例模式的三种c++的优化实现
- 设计模式之----创建型模式(三)-----单例模式
- 23种设计模式之python实现--单例模式
- [设计模式](三):单例模式(含kotlin实现)
- 设计模式三(单例设计模式)
- 设计模式C++之三(Singleton单例模式)
- C++设计模式之三 单例模式
- C++设计模式之三--Singleton单例模式
- 设计模式之(三)——单例模式
- 创建型:设计模式之单例模式(三)
- 设计模式初探之三------单例模式与多线程
- 设计模式之三--单例模式《转载》
- 设计模式学习(三)之单例模式
- scala实现设计模式之单例设计模式
- java设计模式之五 —— 单例模式的三种模式优缺点整理
- 设计模式之-单例实现
- 实现用鼠标拖动没有标题栏的窗口(窗体的任何部分都可实现拖动效果)
- 如何在AMDP中使用SELECT-OPTION
- Git 分支管理和冲突解决
- Java基础的一些小问题
- JavaWeb中Model1简介
- 设计模式之单例模式三种实现
- Art Gallery POJ
- 1.绪论
- UE4--Log写入到单独文件中
- 分类器性能评价总结
- cogs505. 城市
- 移动端常见bug(3)
- 每日一道算法题(1)
- GROMACS运行参数之em.mdp文件详解