Skip to content

Commit 52a824d

Browse files
committed
add single enum
1 parent f3e9c49 commit 52a824d

3 files changed

Lines changed: 68 additions & 3 deletions

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.yiyun;
2+
3+
public enum SingleEnumTest {
4+
SingleFactory;
5+
private MySingleton instance;
6+
7+
SingleEnumTest() {//枚举类的构造方法在类加载是被实例化
8+
instance = new MySingleton();
9+
}
10+
11+
public MySingleton getInstance() {
12+
return instance;
13+
}
14+
15+
}
16+
17+
class MySingleton {
18+
public MySingleton() {
19+
}
20+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package com.yiyun;
2+
3+
public class TestEnum {
4+
public static void main(String[] args) {
5+
for (int i = 0; i < 10; i++) {
6+
new Thread(()->{
7+
System.out.println(SingleEnumTest.SingleFactory.getInstance().hashCode());
8+
}).start();
9+
}
10+
}
11+
}

myoffer/src/main/java/book/offer/_2_Single.java

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -145,22 +145,26 @@ public static void main(String[] args) {
145145

146146
}
147147

148-
class SingleResolve implements Serializable{
148+
class SingleResolve implements Serializable {
149149

150150
private static final long serialVersionUID = 8396313380667197389L;
151-
private static class MySingletonHandler{
151+
152+
private static class MySingletonHandler {
152153
private static SingleResolve instance = new SingleResolve();
153154
}
154155

155-
private SingleResolve(){}
156+
private SingleResolve() {
157+
}
156158

157159
public static SingleResolve getInstance() {
158160
return MySingletonHandler.instance;
159161
}
162+
160163
protected Object readResolve() throws ObjectStreamException {
161164
System.out.println("调用了readResolve方法!");
162165
return MySingletonHandler.instance;
163166
}
167+
164168
public static void main(String[] args) {
165169
SingleResolve singleton = SingleResolve.getInstance();
166170

@@ -195,6 +199,36 @@ public static void main(String[] args) {
195199
}
196200

197201
}
202+
203+
}
204+
class SingleStatic{
205+
private static SingleStatic instance=null;
206+
static {
207+
instance=new SingleStatic();
208+
}
209+
private SingleStatic(){
210+
System.out.println("eager");
211+
}
212+
public static SingleStatic getInstance(){
213+
return instance;
214+
}
198215

216+
public static void main(String[] args) {
217+
218+
}
219+
}
220+
221+
enum EnumFactory{
222+
singletonFactory;
223+
private SingleEnum instance;
224+
private EnumFactory(){
225+
instance=new SingleEnum();
226+
}
227+
public SingleEnum getInstance(){
228+
return instance;
229+
}
199230

231+
}
232+
class SingleEnum{
233+
public SingleEnum(){}
200234
}

0 commit comments

Comments
 (0)