---
title: "单例模式"
author: "darezhong"
date: "2011-10-18T00:16:04Z"
tags: ["单例模式"]
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2011-10-20T00:24:23Z"
id: 1198857
url: "https://darezhong.iteye.com/blog/1198857"
---

单例模式：保证一个类仅有一个实例，并提供一个访问她的全局访问点。

有懒汉式与饿汉式之分：
1.懒汉式：
public class Singleton {
	
	private static Singleton instance = null;
	
	private Singleton() {
		
	}
	
	public static synchronized Singleton getInstance() {
		if(instance == null) {
                           synchronized(synchronized.class) {
                                if(instance == null) {
                                    instance = new Singleton();
                                }
                           }
		}
		return instance;
	}
}


2.饿汉式：
public class Singleton {
	
	private static Singleton instance = new Singleton();
	
	private Singleton() {
		
	}
	
	public static Singleton getInstance() {
		return instance;
	}
	
}