<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sanjaya Senadheera on Medium]]></title>
        <description><![CDATA[Stories by Sanjaya Senadheera on Medium]]></description>
        <link>https://medium.com/@smssena1110?source=rss-1a08dad515f5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NQQJFMyJ00-94xYV.jpg</url>
            <title>Stories by Sanjaya Senadheera on Medium</title>
            <link>https://medium.com/@smssena1110?source=rss-1a08dad515f5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 15:57:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@smssena1110/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The singleton design pattern]]></title>
            <link>https://medium.com/@smssena1110/the-singleton-design-pattern-6423d5a77c68?source=rss-1a08dad515f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6423d5a77c68</guid>
            <category><![CDATA[java-design-pattern]]></category>
            <category><![CDATA[singleton-pattern]]></category>
            <category><![CDATA[singleton-design-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[singleton]]></category>
            <dc:creator><![CDATA[Sanjaya Senadheera]]></dc:creator>
            <pubDate>Mon, 26 Dec 2022 11:52:46 GMT</pubDate>
            <atom:updated>2022-12-26T11:52:46.349Z</atom:updated>
            <content:encoded><![CDATA[<p>The singleton design pattern is a design pattern that ensures that a class has only one instance, and provides a global access point to that instance. Here are ten points to consider when using the singleton design pattern:</p><h4><strong>The singleton class is responsible for creating and maintaining its own unique instance.</strong></h4><p>This is typically done by providing a private constructor, which prevents other classes from instantiating the singleton class directly. Instead, other classes must access the singleton instance through a public static method provided by the singleton class.</p><pre>public class Singleton {<br>    private static Singleton instance;<br><br>    private Singleton() {}<br><br>    public static Singleton getInstance() {<br>        if (instance == null) {<br>            instance = new Singleton();<br>        }<br>        return instance;<br>    }<br>}</pre><p>In this example, the Singleton class has a private constructor, which prevents other classes from instantiating it directly. Instead, other classes must use the getInstance() method to access the singleton instance. The getInstance() method uses lazy initialization to create the singleton instance only when it is first needed, and then it returns the same instance for all subsequent requests. This ensures that there is only one instance of the Singleton class in the application.</p><h4>The singleton class has a private constructor to prevent other classes from instantiating it.</h4><p>This ensures that the singleton class has full control over the creation and initialization of its instance, and that no other class can create additional instances of the singleton class.</p><h4>The singleton class provides a public static method that allows other classes to access its instance.</h4><p>In above example, the Singleton class has a private constructor, which prevents other classes from instantiating it directly. Instead, other classes must use the getInstance() method to access the singleton instance. This method uses lazy initialization to create the singleton instance only when it is first needed, and then it returns the same instance for all subsequent requests. This ensures that there is only one instance of the Singleton class in the application, and that it can be accessed globally through the getInstance() method.</p><p>Other classes can access the singleton instance by calling the getInstance() method like this.</p><pre>Singleton s = Singleton.getInstance();</pre><p>This will return the singleton instance, allowing the calling class to access the methods and properties of the singleton class.</p><h4>The singleton class ensures that its instance is created lazily, only when it is first needed.</h4><p>This means that the instance is not created until it is actually requested by a calling class. This is in contrast to eager initialization, where the instance is created as soon as the singleton class is loaded.</p><p>Lazy initialization has several benefits, including reduced memory usage and improved performance, since the instance is only created when it is actually needed. It also allows the singleton class to perform any necessary initialization or setup before the instance is used.</p><h4>The singleton class ensures that its instance is thread-safe, even in the presence of multiple threads.</h4><p>This is important because multiple threads may attempt to access the singleton instance simultaneously, which could lead to race conditions and other synchronization issues if the instance is not thread-safe.</p><p>There are several ways to ensure thread safety in a singleton class, including the use of synchronization, the use of volatile fields, and the use of the double-checked locking pattern.</p><pre>public class Singleton {<br>    private static volatile Singleton instance;<br><br>    private Singleton() {}<br><br>    public static Singleton getInstance() {<br>        if (instance == null) {<br>            synchronized (Singleton.class) {<br>                if (instance == null) {<br>                    instance = new Singleton();<br>                }<br>            }<br>        }<br>        return instance;<br>    }<br>}</pre><p>This approach ensures that the Singleton class is thread-safe, even in the presence of multiple threads. It also allows the Singleton class to be implemented as a lazy singleton, since the instance is only created when it is first needed.</p><h4>The singleton class ensures that its instance is serializable, so that it can be persisted and later restored.</h4><p>To make a singleton class serializable, it should implement the java.io.Serializable interface and provide a special readResolve() method. The readResolve() method is called when the singleton instance is deserialized, and it allows the singleton class to return the correct instance instead of a new instance created by the serialization process.</p><pre>public class Singleton implements Serializable {<br>    private static final long serialVersionUID = 1L;<br>    private static Singleton instance;<br><br>    private Singleton() {}<br><br>    public static Singleton getInstance() {<br>        if (instance == null) {<br>            instance = new Singleton();<br>        }<br>        return instance;<br>    }<br><br>    private Object readResolve() {<br>        return getInstance();<br>    }<br>}</pre><p>In this example, the Singleton class implements the Serializable interface and provides a readResolve() method. When the Singleton instance is serialized and then deserialized, the readResolve() method is called to return the correct instance. This ensures that the singleton instance is correctly restored, even after being persisted to a file or database.</p><p>It’s important to note that the singleton pattern may not be the best choice if you need to persist the singleton instance, since it can make it more difficult to change the implementation of the singleton class or the data it contains. In such cases, it may be better to use a different design pattern, such as the Memento pattern, which is specifically designed for persisting objects.</p><h4>The singleton pattern is useful when you need to ensure that a class has only one instance, and you want to provide a global access point to that instance.</h4><p>This can be useful in a variety of situations, such as when you need to implement a global state or configuration for an application, or when you need to ensure that only one instance of a resource-intensive class is created.</p><p>For example, consider an application that needs to maintain a global configuration object. The configuration object might contain settings such as the application’s theme, the location of the data files, or the default language. To ensure that there is only one instance of the configuration object, and to provide a global access point to that instance, you can use the singleton pattern.</p><pre>public class Configuration implements Serializable {<br>    private static final long serialVersionUID = 1L;<br>    private static Configuration instance;<br><br>    private String theme;<br>    private String dataDirectory;<br>    private String defaultLanguage;<br><br>    private Configuration() {}<br><br>    public static Configuration getInstance() {<br>        if (instance == null) {<br>            instance = new Configuration();<br>        }<br>        return instance;<br>    }<br><br>    public String getTheme() {<br>        return theme;<br>    }<br><br>    public void setTheme(String theme) {<br>        this.theme = theme;<br>    }<br><br>    public String getDataDirectory() {<br>        return dataDirectory;<br>    }<br><br>    public void setDataDirectory(String dataDirectory) {<br>        this.dataDirectory = dataDirectory;<br>    }<br><br>    public String getDefaultLanguage() {<br>        return defaultLanguage;<br>    }<br><br>    public void setDefaultLanguage(String defaultLanguage) {<br>        this.defaultLanguage = defaultLanguage;<br>    }<br>}</pre><p>In this example, the Configuration class is a singleton class that maintains the global configuration for the application. It has a private constructor, which prevents other classes from instantiating it directly. Instead, other classes must use the getInstance() method to access the singleton instance. This ensures that there is only one instance of the Configuration class in the application, and that it can be accessed globally through the getInstance() method.</p><p>Other classes can access the Configuration instance and modify the configuration like this:</p><pre>Configuration config = Configuration.getInstance();<br>config.setTheme(&quot;dark&quot;);<br>config.setDataDirectory(&quot;/var/data&quot;);<br>config.setDefaultLanguage(&quot;en-US&quot;);</pre><p>This allows the Configuration class to act as a global state or configuration object for the application, and ensures that there is only one instance of the Configuration class that is shared by all classes in the application.</p><h4>The singleton pattern can be implemented in several ways, including the use of a static field, a static factory method, or an enum.</h4><p><strong>Static field:</strong> In this approach, the singleton class maintains a static field that holds the singleton instance. The singleton instance is created when the class is first loaded, and it is accessed through a public static method. This approach is simple and easy to understand, but it does not support lazy initialization and it may not be thread-safe.</p><p><strong>Static factory method:</strong> In this approach, the singleton class provides a public static factory method that creates and returns the singleton instance. The factory method uses lazy initialization to create the instance only when it is first needed, and it returns the same instance for all subsequent requests. This approach is more flexible than the static field approach, and it supports lazy initialization, but it may not be thread-safe.</p><p><strong>Enum:</strong> In this approach, the singleton class is implemented as an enum, with a single instance of the enum representing the singleton instance. This approach is thread-safe and supports serialization, but it does not allow for lazy initialization and it may be more verbose than other approaches.</p><p>Each of these approaches has its own trade-offs, and the best choice will depend on the specific requirements of your application. It’s important to choose the approach that best meets your needs and to consider factors such as thread safety, lazy initialization, and serialization support when making your decision.</p><h4>The singleton pattern can be overused, leading to tight coupling and difficulties in testing and maintaining the code. It should be used with caution, and only when necessary.</h4><p>Some common reasons to use the singleton pattern include:</p><ul><li>Maintaining a global state or configuration for an application</li><li>Ensuring that only one instance of a resource-intensive class is created</li><li>Providing a global access point to a shared resource or service</li></ul><p>However, it is important to consider the drawbacks of the singleton pattern as well. Some potential drawbacks of the singleton pattern include:</p><ul><li>Tight coupling: The singleton pattern can lead to tight coupling between the singleton class and the classes that depend on it, making it more difficult to change or replace the singleton class.</li><li>Difficulty in testing: The singleton pattern can make it more difficult to test the classes that depend on the singleton class, since they cannot be instantiated independently.</li><li>Difficulty in maintenance: The singleton pattern can make it more difficult to maintain the code, since it is difficult to change or replace the singleton class without affecting the rest of the application.</li></ul><p>In general, it is best to use the singleton pattern only when it is truly necessary, and to consider alternative patterns, such as dependency injection, when possible. This can help to reduce tight coupling and improve the maintainability and testability of the code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6423d5a77c68" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>