---
title: "单例模式"
author: "return_space"
date: "2012-03-25T14:05:57Z"
tags: []
categories: ["企业架构"]
slug: "untitled"
draft: false
lastmod: "2012-03-25T14:05:57Z"
id: 1463379
url: "https://return-space.iteye.com/blog/1463379"
---

单例模式：即在全局范围内，某个类只允许存在一个实例。

 

具体代码如下：

考虑了多线程、克隆情况

 

代码增加多线程，主要是为了测试，把多线程去掉就是一个单例。

 

```
package com.mkf.pattern;

public class Singleton implements Runnable {
	private static Singleton _instance = null;
	static int i = 0;
	static int j = 0;
	private Singleton(){
		i++;
	}
	
	synchronized public static Singleton getInstance(){
		if(null == _instance){
			_instance = new Singleton();
		}
		return _instance;
	}
	
	@Override
	public Singleton clone(){
		return getInstance();
	}
	
	@Override
	public void run() {
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(i + "\t" + j);
		j++;
		getInstance();
	}
}
```

 

测试：

 

```
package com.mkf.pattern;

public class TestMain {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int i = 0;
		while(i<5){
			Thread t = new Thread(Singleton.getInstance());
			t.start();
			System.out.println("i  " + i + "\t" + t.getName());
			i++;
		}
		
	}

}
```