单例模式

单例模式(Singleton Pattern)属于创建型模式,此模式涉及单一的类与对象,类负责创建自己的对象,同时保证只有一个对象被使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141

/*
* Copyright,ShanNong Inc,2018 and onwards
*
* Author:fanghua fan
*/

package com.fanghua.designpattrn.singleton;

/**
* 单例模式, 线程不安全模式
*/
public class SingletonPattern {
private static SingletonPattern object;

private SingletonPattern() {
}

/**
* 获取单利对象
*
* @return
*/
private static SingletonPattern getInstance() {
if (object == null) {
object = new SingletonPattern();
}
return object;
}

private void showInstance() {
System.out.println("show instance:" + getClass().hashCode());
}

public static void main(String[] args) {
for (int i = 0; i < 100; i++)
SingletonPattern.getInstance().showInstance();
}
}

/**
* 线程安全式
*/
class SingletonPatternSafe {
private static SingletonPatternSafe object;

private SingletonPatternSafe() {
}

/**
* 获取单利对象
*
* @return
*/
private static synchronized SingletonPatternSafe getInstance() {
if (object == null) {
object = new SingletonPatternSafe();
}
return object;
}

private void showInstance() {
System.out.println("show instance:" + getClass().hashCode());
}

public static void main(String[] args) {
for (int i = 0; i < 100; i++)
SingletonPatternSafe.getInstance().showInstance();
}
}

/**
* 线程安全,但是浪费内存
*/
class Singleton {
private static Singleton instance = new Singleton();

private Singleton() {
}

public static Singleton getInstance() {
return instance;
}
}

/**
* 基于双重校验锁的线程安全式
*/
class SingletonDoubleLock {
private volatile static SingletonDoubleLock singleton;

private SingletonDoubleLock() {
}

public static SingletonDoubleLock getSingleton() {
if (singleton == null) {
synchronized (SingletonDoubleLock.class) {
if (singleton == null) {
singleton = new SingletonDoubleLock();
}
}
}
return singleton;
}
}

/**
* 基于内部类的线程安全式单例模式
*/
class SingletonInnerStatic {
private static class SingletonHolder {
private static final SingletonInnerStatic INSTANCE = new SingletonInnerStatic();
}

private SingletonInnerStatic() {
}

public static final SingletonInnerStatic getInstance() {
return SingletonHolder.INSTANCE;
}
}


/**
* 单元素的枚举类型是singleton实现的最佳方法,同时也是线程安全的
*/
class ObjectResource {
}

enum SomeThing {
INSTANCE;
private ObjectResource instance;

SomeThing() {
instance = new ObjectResource();
}

public ObjectResource getInstance() {
return instance;
}
}

(全文完)3/31/2018 10:05:32 PM