单例设计模式
来源:互联网 发布:sql查询表语句怎么写 编辑:程序博客网 时间:2024/05/14 12:54
//不能保证线程安全的懒汉模式
public class Singleton{
private static Singleton instance;
//构造函数
private Singleton(){
}
public static Singleton getInstance(){
//为空的话 构建一个
if(instance == null ){
instance = new Singleton();
}
return instance;
}
}
//保证了线程安全的懒汉模式
public class Singleton{
//声明一个静态变量
private static Singleton instance;
//构造函数
private Singleton(){
}
//加锁的函数
public static synchronzied Singleton getInstance(){
//为空的话 构建一个
if(instance == null ){
instance = new Singleton();
}
return instance;
}
}
//饿汉模式
public class Singleton{
private static Singleton instance;
static{
instance = new Singleton();
}
private Singleton(){
}
public static Singleton getInstance(){
return instance;
}
}
//双重校验锁 懒汉模式
public class Singleton{
private volatile static Singleton_volatile instance=null;
private Singleton(){
}
public static Singleton getInstance(){
if(instance==null){
synchronzied(Singleton.class){
if(instance==null){
instance = new Singleton();
}
}
}
return instance;
}
}
public class Singleton{
private static Singleton instance;
//构造函数
private Singleton(){
}
public static Singleton getInstance(){
//为空的话 构建一个
if(instance == null ){
instance = new Singleton();
}
return instance;
}
}
//保证了线程安全的懒汉模式
public class Singleton{
//声明一个静态变量
private static Singleton instance;
//构造函数
private Singleton(){
}
//加锁的函数
public static synchronzied Singleton getInstance(){
//为空的话 构建一个
if(instance == null ){
instance = new Singleton();
}
return instance;
}
}
//饿汉模式
public class Singleton{
private static Singleton instance;
static{
instance = new Singleton();
}
private Singleton(){
}
public static Singleton getInstance(){
return instance;
}
}
//双重校验锁 懒汉模式
public class Singleton{
private volatile static Singleton_volatile instance=null;
private Singleton(){
}
public static Singleton getInstance(){
if(instance==null){
synchronzied(Singleton.class){
if(instance==null){
instance = new Singleton();
}
}
}
return instance;
}
}
0 0
- 设计模式--单例
- 单例设计模式
- 设计模式----单例
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 设计模式-单例
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- Hdu 1195 Open the Lock
- 每个android开发者都应该知道的Top 5三方库(2015版)
- java线程学习
- java内部类之方法内部类
- C语言的printf函数的执行顺序
- 单例设计模式
- scanf/fscanf 的%[]和%n使用方法 http://blog.csdn.net/wesweeky/article/details/6439777
- 解一元三次方程
- spi子系统的理解
- 关于GuideActivity制作,sleep 和wait区别
- 用java实现动态分区
- MyBatis配置文件
- 压缩字符串
- Wee5-6Lexicalized parsing