Skip to content

Commit

Permalink
Add Singleton example to Design Patterns
Browse files Browse the repository at this point in the history
  • Loading branch information
dawand committed Jan 2, 2021
1 parent 045ed17 commit fd34d7b
Show file tree
Hide file tree
Showing 113 changed files with 35 additions and 0 deletions.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
21 changes: 21 additions & 0 deletions Design-patterns/src/singleton/Captain.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package singleton;

// final is to avoid having non-static nested classes subclassing Captain
final class Captain {

private static Captain captain;

private Captain() {}

// synchronized is for multithreaded purpose
public static synchronized Captain getInstance() {
if (captain == null) { // lazy initialization
captain = new Captain();
System.out.println("A new captain is created :)");
return captain;
} else {
System.out.println("You already have a captain!");
}
return captain;
}
}
13 changes: 13 additions & 0 deletions Design-patterns/src/singleton/SingletonExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package singleton;

public class SingletonExample {
public static void main(String[] args) {
Captain captain1 = Captain.getInstance();
Captain captain2 = Captain.getInstance();

if (captain1 == captain2) {
System.out.println("Captain 1 and 2 are same instances");
}

}
}
1 change: 1 addition & 0 deletions interview-preparation.iml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/problems" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/Design-patterns/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
Expand Down

0 comments on commit fd34d7b

Please sign in to comment.