# 單例設計模式
### 一個類只能創建唯一的一個對象
### 想要完成單例模式,必須私有化構造器
>惡漢式
```
在類里創建對象
創建方法獲得對象(static)
不存在線程問題;
```
```
public class Singleton1 {
static private Singleton1 instance = new Singleton1();
public static Singleton1 getInstance() {
return instance;
}
}
```
>懶漢式
```
在類里聲明對象,不賦值(static)
創建方法為對象賦值(static)
存在線程問題;
解決方案:用對象鎖synchronized修飾對象賦值方法
//鎖對象為字節碼文件;
```
```
public class Singleton2 {
static private Singleton2 instance = null;
public static synchronized Singleton2 getInstance() {
if(instance == null) {
instance = new Singleton2();
}
return instance;
}
}
```