---
title: "为什么需要Singleton"
author: "步行者"
date: "2009-06-07T11:23:08Z"
tags: []
categories: ["企业架构"]
slug: "singleton"
draft: false
lastmod: "2009-06-09T00:06:38Z"
id: 403489
url: "https://yangjunfeng.iteye.com/blog/403489"
---

为什么需要 单例设计模式(Singleton)？

像下面的一个单例

 

```
public class Singleton {
	private static Singleton instance = null;
	private Singleton(){};
	public static synchronized Singleton getInstance(){
		if(instance == null)
			instance = new Singleton();
		return instance;
	}
	public void doSomething(){
		//do something
	}
}
```

它要实现的主要目标，就是在一个应用中只维护一个Singleton实例

但一个类在一个应用中也是唯一的，为什么不能直接以类作为单例呢？

 

```
public final class AnotherSingleton{
	private AnotherSingleton(){}
	public static synchronized void doSomething(){
		//do something
	}
}
```

 

把类的所有方法都改为静态方法，

所有属性都改为静态属性（我们可以把

静态属性看成类的内部状态），

但是不允许实例化，

对类的操作相当于对单例的操作

而且类也可以维护内部状态（通过静态私有属性）

这完全满足了单例的要求。

不知道为什么需要单例模式。。。

因为我想不出来在什么情况下 单例可以满足需求

而 类 不能。