Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitea6c4e5

Browse files
committed
Added Singleton Design pattern implementation in Java and its test
1 parent09c4cd7 commitea6c4e5

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
packagesrc.main.java.com.designpatterns.singletonpattern;
2+
3+
/**
4+
* The singleton pattern is a design pattern that restricts the instantiation of a class to one "single" instance.
5+
* This is useful when exactly one object is needed to coordinate actions across the system. The term comes from the
6+
* mathematical concept of a singleton.
7+
* <p>
8+
* The key idea in this pattern is to make the class itself responsible for controlling its instantiation (only once).
9+
* The hidden constructor (declared private) ensures that the class can never be instantiated from outside the class.
10+
* The public static operation can be accessed easily by using the class name and function name(Singleton.getInstance())
11+
*
12+
* @see <a href="https://en.wikipedia.org/wiki/Singleton_pattern">Singleton Pattern</a>
13+
*/
14+
publicclassSingleton {
15+
privatevolatilestaticSingletoninstance =null;
16+
17+
privateSingleton() {
18+
}
19+
20+
/**
21+
* A singleton implementation may use lazy initialization, where the instance is created when the static method
22+
* is first invoked.
23+
* <p>
24+
* If the static method might be called from multiple threads simultaneously, measures may need
25+
* to be taken to prevent race conditions that could result in the creation of multiple instances of the class.
26+
* <p>
27+
* The following implementation is a thread-safe sample implementation, using lazy initialization with
28+
* double-checked locking.
29+
*
30+
* @return the single instance of the Singleton class
31+
*/
32+
publicstaticSingletongetInstance() {
33+
if (instance ==null) {
34+
// First attempt to make thread safe
35+
synchronized (Singleton.class) {
36+
// Double Checked locking as multiple threads can reach the above step
37+
if (instance ==null) {
38+
instance =newSingleton();
39+
}
40+
}
41+
}
42+
returninstance;
43+
}
44+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
packagesrc.test.java.com.designpatterns.singletonpattern;
2+
3+
importorg.junit.Assert;
4+
importorg.junit.Test;
5+
importsrc.main.java.com.designpatterns.singletonpattern.Singleton;
6+
7+
importjava.util.ArrayList;
8+
importjava.util.concurrent.ExecutorService;
9+
importjava.util.concurrent.Executors;
10+
importjava.util.concurrent.TimeUnit;
11+
12+
publicclassSingletonTest {
13+
privatestaticvolatileArrayList<Integer>hashCodeList =newArrayList<>();
14+
15+
@Test
16+
publicvoidtestSingleton()throwsInterruptedException {
17+
booleantestFailed =false;
18+
ExecutorServicees =Executors.newCachedThreadPool();
19+
// Creates 15 threads and makes all of them access the Singleton class
20+
// Saves the hash code of the object in a static list
21+
for (inti =0;i <15;i++)
22+
es.execute(() -> {
23+
try {
24+
SingletonsingletonInstance =Singleton.getInstance();
25+
intsingletonInsCode =singletonInstance.hashCode();
26+
System.out.println(singletonInsCode);
27+
hashCodeList.add(singletonInsCode);
28+
}catch (Exceptione) {
29+
System.out.println("Exception is caught");
30+
}
31+
});
32+
es.shutdown();
33+
booleanfinished =es.awaitTermination(1,TimeUnit.MINUTES);
34+
// wait for all threads to finish
35+
if (finished) {
36+
IntegerfirstCode =hashCodeList.get(0);
37+
for (Integercode :hashCodeList) {
38+
if (!firstCode.equals(code)) {
39+
testFailed =true;
40+
}
41+
}
42+
Assert.assertFalse(testFailed);
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp