Skip to content

Commit a0f8104

Browse files
committed
Added enum based singleton
1 parent 0c7c2bd commit a0f8104

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

enum-singleton.ser

126 Bytes
Binary file not shown.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.javamultiplex.pattern.creational.singleton;
2+
3+
/**
4+
* @author Rohit Agarwal on 29/08/20 11:19 pm
5+
* @copyright www.javamultiplex.com
6+
*/
7+
8+
//enum is by default serializable
9+
public enum EnumBasedSingleton {
10+
INSTANCE;
11+
12+
private int value;
13+
14+
EnumBasedSingleton() {
15+
value = 42;
16+
}
17+
18+
public int getValue() {
19+
return value;
20+
}
21+
22+
public void setValue(int value) {
23+
this.value = value;
24+
}
25+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.javamultiplex.pattern.creational.singleton;
2+
3+
import com.javamultiplex.util.SerializationUtil;
4+
import org.junit.jupiter.api.Test;
5+
6+
import java.io.IOException;
7+
8+
/**
9+
* @author Rohit Agarwal on 29/08/20 11:21 pm
10+
* @copyright www.javamultiplex.com
11+
*/
12+
public class EnumBasedSingletonClient {
13+
14+
@Test
15+
public void shouldNotCreateTwoInstances() throws IOException, ClassNotFoundException {
16+
EnumBasedSingleton enumBasedSingleton = EnumBasedSingleton.INSTANCE;
17+
enumBasedSingleton.setValue(13);
18+
System.out.println(enumBasedSingleton.name());
19+
SerializationUtil.serialize(enumBasedSingleton,"enum-singleton.ser");
20+
EnumBasedSingleton another = (EnumBasedSingleton)SerializationUtil.deserialize("enum-singleton.ser");
21+
System.out.println(another.getValue());
22+
}
23+
}

0 commit comments

Comments
 (0)