{"id":1377,"date":"2017-05-07T14:32:36","date_gmt":"2017-05-07T14:32:36","guid":{"rendered":"http:\/\/www.testingdocs.com\/questions\/?p=1377"},"modified":"2024-09-04T15:42:18","modified_gmt":"2024-09-04T15:42:18","slug":"how-to-create-a-singleton-class","status":"publish","type":"post","link":"https:\/\/www.testingdocs.com\/questions\/how-to-create-a-singleton-class\/","title":{"rendered":"How to create a Singleton class?"},"content":{"rendered":"<h2>How to create a Singleton class?<\/h2>\n<p>Using the Singleton pattern, you should have only one object of a particular class throughout your code. The Singleton class design is to make sure that you can instantiate only one object of a particular class. You need to restrict the new operator by creating more objects than 1 for the Singleton class.<\/p>\n<p>Let&#8217;s see how we can achieve this with step by step approach.<\/p>\n<h3><strong>Sample class<\/strong><\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class Singleton {\r\n \/\/ Only one object instance is allowed for this class.\r\n private String name;\r\n\r\npublic String getName(){\r\n return name;\r\n }\r\n\r\npublic Singleton(String name){\r\n this.name = name;\r\n }\r\n\r\npublic void display() {\r\n System.out.println(\"This is singleton \"+ name);\r\n }\r\n}<\/pre>\n<p>&nbsp;<\/p>\n<p>Try to use the singleton and obvious problem:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class UseSingleton {\r\n\/\/ This class will try to use singleton class\r\n public static void main(String[] args) {\r\n Singleton s1 = new Singleton(\"s1\");\r\n Singleton s2 = new Singleton(\"s2\");\r\n \/\/ Oops.. we have created 2 objects...\r\n s1.display();\r\n s2.display();\r\n }\r\n}<\/pre>\n<p>&nbsp;<\/p>\n<p>You need to avoid creating a new object each time with the new operator on your class.Make the constructor of Singleton private. You can block the use of the new operator from any code that is not inside the Singleton class. Create a method to create one object and return the instance.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">private Singleton(String name){\r\n    this.name = name;\r\n  }<\/pre>\n<p>&nbsp;<\/p>\n<p>Calling the getInstance method gives you an instance of Singleton class.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public static Singleton getInstance(String name)\r\n  {\r\n    if (singleInstance == null){\r\n      singleInstance = new Singleton(name);\r\n    }\r\n    return singleInstance;\r\n  }<\/pre>\n<p>&nbsp;<\/p>\n<p>Another aspect to keep in mind is that , when two or more threads invoke the getInstance at the same time, it is possible for both threads will create Singleton objects.<\/p>\n<h3><strong>Synchronization<\/strong><\/h3>\n<p>You can use to restrict access to getInstance to one thread at a time using Synchronization. Using the synchronized blocks access to the getInstance method, any new threads attempting to get in have to wait until the current thread is finished.Synchronization can be used for thread safety and to make sure single-threaded execution.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class Singleton {\r\n \/\/ Only one object instance is allowed for this class.\r\n private String name;\r\n private static Singleton singleInstance = new Singleton(\"single\");\r\n public String getName(){\r\n return name;\r\n }\r\n\r\nprivate Singleton(String name){\r\n this.name = name;\r\n }\r\n\r\npublic static synchronized Singleton getInstance(String name)\r\n {\r\n return singleInstance;\r\n }\r\n\r\npublic void display() {\r\n System.out.println(\"This is singleton \"+ name);\r\n }\r\n}\r\n\r\n\r\npublic class UseSingleton implements Runnable {\r\n \/\/ This class will try to use singleton class\r\n Thread t;\r\n\r\npublic UseSingleton()\r\n {\r\n Singleton s;\r\n s = Singleton.getInstance(\"single\");\r\n t = new Thread(this, \"2\");\r\n t.start(); \r\n s.display();\r\n }\r\n\r\npublic void run() \r\n {\r\n Singleton s;\r\n s = Singleton.getInstance(\"1\");\r\n s.display();\r\n }\r\n\r\npublic static void main(String[] args) {\r\n new UseSingleton();\r\n }\r\n}<\/pre>\n<p>&nbsp;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1578\" src=\"http:\/\/www.testingdocs.com\/questions\/wp-content\/uploads\/Singleton-Java-program.png\" alt=\"Singleton Java program\" width=\"1178\" height=\"636\" title=\"\"><\/p>\n<div id=\"themify_builder_content-1576\" class=\"themify_builder_content themify_builder_content-1576 themify_builder\" data-postid=\"1576\"><\/div>\n","protected":false},"excerpt":{"rendered":"<p>How to create a Singleton class? Using the Singleton pattern, you should have only one object of a particular class throughout your code. The Singleton class design is to make sure that you can instantiate only one object of a particular class. You need to restrict the new operator by creating more objects than 1 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-1377","post","type-post","status-publish","format-standard","hentry","category-automation","has-post-title","has-post-date","has-post-category","has-post-tag","has-post-comment","has-post-author",""],"_links":{"self":[{"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/posts\/1377","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/comments?post=1377"}],"version-history":[{"count":5,"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/posts\/1377\/revisions"}],"predecessor-version":[{"id":24194,"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/posts\/1377\/revisions\/24194"}],"wp:attachment":[{"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/media?parent=1377"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/categories?post=1377"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/tags?post=1377"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}