|
|
@@ -0,0 +1,33 @@
|
|
|
+package cn.qinys.learn.creational.singleton;
|
|
|
+
|
|
|
+/**
|
|
|
+ * Singleton Design Pattern Example
|
|
|
+ * Ensures only one instance of the class exists throughout the application.
|
|
|
+ */
|
|
|
+public class Singleton {
|
|
|
+
|
|
|
+ // Private static instance variable
|
|
|
+ private static volatile Singleton instance;
|
|
|
+
|
|
|
+ // Private constructor to prevent instantiation
|
|
|
+ private Singleton() {
|
|
|
+ // Initialization code if needed
|
|
|
+ }
|
|
|
+
|
|
|
+ // Public static method to get the instance
|
|
|
+ public static Singleton getInstance() {
|
|
|
+ if (instance == null) {
|
|
|
+ synchronized (Singleton.class) {
|
|
|
+ if (instance == null) {
|
|
|
+ instance = new Singleton();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return instance;
|
|
|
+ }
|
|
|
+
|
|
|
+ // Example method
|
|
|
+ public void showMessage() {
|
|
|
+ System.out.println("Hello from Singleton instance!");
|
|
|
+ }
|
|
|
+}
|