天天看點

單例模式

主要介紹單例模式的一種寫法、注意事項、作用、測試,以java語言為例,下面代碼是目前見過最好的寫法:

java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

public class singleton {

private static volatile singleton instance = null;

// private constructor suppresses

private singleton(){

}

public static singleton getinstance() {

// if already inited, no need to get lock everytime

if (instance == null) {

synchronized (singleton.class) {

instance = new singleton();

return instance;

1、需要注意的點

其中需要注意的點主要有三點

(1) 私有化構造函數

(2) 定義靜态的singleton instance對象和getinstance()方法

(3) getinstance()方法中需要使用同步鎖synchronized (singleton.class)防止多線程同時進入造成instance被多次執行個體化

可以看到上面在synchronized (singleton.class)外又添加了一層if,這是為了在instance已經執行個體化後下次進入不必執行synchronized (singleton.class)擷取對象鎖,進而提高性能。

2、單例的作用

單例主要有兩個作用

(1) 保持程式運作過程中該類始終隻存在一個示例

(2) 對于new性能消耗較大的類,隻執行個體化一次可以提高性能

3、單例模式測試

單例模式可以使用多線程并發進行測試,代碼如下:

22

23

24

25

public static void main(string[] args) {

final countdownlatch latch = new countdownlatch(1);

int threadcount = 1000;

for (int i = 0; i < threadcount; i++) {

new thread() {

@override

public void run() {

try {

// all thread to wait

latch.await();

} catch (interruptedexception e) {

e.printstacktrace();

// test get instance

system.out.println(singleton.getinstance().hashcode());

}.start();

// release lock, let all thread excute singleton.getinstance() at the same time

latch.countdown();

其中countdownlatch latch為閉鎖,所有線程中都用latch.await();等待鎖釋放,待所有線程初始化完成使用latch.countdown();釋放鎖,進而達到線程并發執行singleton.getinstance()的效果。