Skip to content

Commit fd34d7b

Browse files
committed
Add Singleton example to Design Patterns
1 parent 045ed17 commit fd34d7b

File tree

113 files changed

+35
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

113 files changed

+35
-0
lines changed
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package singleton;
2+
3+
// final is to avoid having non-static nested classes subclassing Captain
4+
final class Captain {
5+
6+
private static Captain captain;
7+
8+
private Captain() {}
9+
10+
// synchronized is for multithreaded purpose
11+
public static synchronized Captain getInstance() {
12+
if (captain == null) { // lazy initialization
13+
captain = new Captain();
14+
System.out.println("A new captain is created :)");
15+
return captain;
16+
} else {
17+
System.out.println("You already have a captain!");
18+
}
19+
return captain;
20+
}
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package singleton;
2+
3+
public class SingletonExample {
4+
public static void main(String[] args) {
5+
Captain captain1 = Captain.getInstance();
6+
Captain captain2 = Captain.getInstance();
7+
8+
if (captain1 == captain2) {
9+
System.out.println("Captain 1 and 2 are same instances");
10+
}
11+
12+
}
13+
}

interview-preparation.iml

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
<exclude-output />
55
<content url="file://$MODULE_DIR$">
66
<sourceFolder url="file://$MODULE_DIR$/problems" isTestSource="false" />
7+
<sourceFolder url="file://$MODULE_DIR$/Design-patterns/src" isTestSource="false" />
78
</content>
89
<orderEntry type="inheritedJdk" />
910
<orderEntry type="sourceFolder" forTests="false" />

0 commit comments

Comments
 (0)