{"id":195,"date":"2017-10-04T22:38:16","date_gmt":"2017-10-04T19:38:16","guid":{"rendered":"http:\/\/chernihiv.ddns.net\/?page_id=195"},"modified":"2025-08-30T10:55:53","modified_gmt":"2025-08-30T07:55:53","slug":"java-learn","status":"publish","type":"page","link":"https:\/\/chernihiv.ddns.net\/?page_id=195","title":{"rendered":"Learn &#8230;"},"content":{"rendered":"\n<p><strong><strong>Singleton<\/strong><\/strong><\/p>\n\n\n\n<p><strong>Intro<\/strong><\/p>\n\n\n\n<p>      The <strong>Singleton<\/strong> design pattern is a crucial concept in Java programming that ensures the existence of only one instance of a class and provides a global point of access to it. This pattern is particularly useful in scenarios where you want to control access to resources, manage configuration settings, or implement logging functionalities efficiently. In this post, we will explore the Singleton pattern in Java and discuss how it can enhance resource management in your applications.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Understanding the Singleton Pattern<\/h3>\n\n\n\n<p>The <strong>Singleton<\/strong> pattern follows several key principles:<\/p>\n\n\n\n<ol>\n<li><strong>Private Constructor:<\/strong> The class with the Singleton pattern has a private constructor, preventing external classes from creating instances.<\/li>\n\n\n\n<li><strong>Static Method for Instance Retrieval:<\/strong> The class provides a static method to access the single instance. If the instance doesn&#8217;t exist, it creates one; otherwise, it returns the existing instance.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits of Singleton Pattern in Java:<\/h3>\n\n\n\n<ol>\n<li><strong>Resource Management:<\/strong> The Singleton pattern is valuable when managing resources such as database connections, thread pools, or file systems. By having a single point of control, you can avoid resource contention and efficiently allocate resources.<\/li>\n\n\n\n<li><strong>Configuration Settings:<\/strong> If your application relies on configuration settings, a Singleton instance can ensure that these settings are loaded only once and are easily accessible throughout the application.<\/li>\n\n\n\n<li><strong>Logging and Tracing:<\/strong> Singleton is beneficial for implementing logging and tracing mechanisms. A single instance can manage log files or maintain a centralized log repository.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Implementing Singleton in Real-world Scenarios:<\/h3>\n\n\n\n<p>Consider the following example of a Logger class using the Singleton pattern:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public class Singleton {\n    private static Singleton instance;\n\n    private Singleton() {\n        \/\/ private constructor\n    }\n\n    public static synchronized Singleton getInstance() {\n        if (instance == null) {\n            instance = new Singleton();\n        }\n        return instance;\n    }\n\n    \/\/ other methods and properties\n}<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Factory Method Pattern<\/h3>\n\n\n\n<p>The <strong>Factory Method<\/strong> is a creational design pattern that provides an interface for creating objects but allows subclasses to alter the type of objects that will be created. Instead of instantiating objects directly using the <code>new<\/code> keyword, the Factory Method delegates this responsibility to subclasses or specialized creator classes.<\/p>\n\n\n\n<p>This pattern is especially useful when a system needs to be independent of how its objects are created, composed, or represented. It helps to follow the <strong>Open\/Closed Principle<\/strong>: classes are open for extension but closed for modification.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h4 class=\"wp-block-heading\">Key Concepts<\/h4>\n\n\n\n<ol>\n<li><strong>Creator (Factory)<\/strong><br>Declares the factory method that returns objects of a certain type. The base implementation may provide a default product, but subclasses can override the method to change the product type.<\/li>\n\n\n\n<li><strong>Concrete Creator<\/strong><br>Implements the factory method and specifies which concrete class will be instantiated.<\/li>\n\n\n\n<li><strong>Product<\/strong><br>Defines the interface of the objects the factory method creates.<\/li>\n\n\n\n<li><strong>Concrete Product<\/strong><br>Implements the product interface.<\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h4 class=\"wp-block-heading\">Example<\/h4>\n\n\n\n<p>Suppose you are building a system that generates different types of dialog boxes (Windows dialog, Web dialog, etc.). Each dialog needs to create a button, but the button style depends on the environment.<\/p>\n\n\n\n<ul>\n<li><strong>Product:<\/strong> <code>Button<\/code> interface<\/li>\n\n\n\n<li><strong>Concrete Products:<\/strong> <code>WindowsButton<\/code>, <code>HTMLButton<\/code><\/li>\n\n\n\n<li><strong>Creator:<\/strong> <code>Dialog<\/code> (abstract class with <code>createButton()<\/code> method)<\/li>\n\n\n\n<li><strong>Concrete Creators:<\/strong> <code>WindowsDialog<\/code>, <code>WebDialog<\/code><\/li>\n<\/ul>\n\n\n\n<p>The <code>Dialog<\/code> class relies on <code>createButton()<\/code> but doesn\u2019t know what specific button it gets. Each subclass decides what button to create.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h4 class=\"wp-block-heading\">Benefits<\/h4>\n\n\n\n<ul>\n<li>Promotes <strong>loose coupling<\/strong> by relying on abstractions instead of concrete classes.<\/li>\n\n\n\n<li>Makes code more <strong>flexible<\/strong> and <strong>extensible<\/strong> without modifying existing classes.<\/li>\n\n\n\n<li>Centralizes object creation logic.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h4 class=\"wp-block-heading\">Drawbacks<\/h4>\n\n\n\n<ul>\n<li>Introduces additional classes and complexity.<\/li>\n\n\n\n<li>May be overkill if there is only one or very few concrete products.<\/li>\n<\/ul>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/ Product interface\ninterface Button {\n    void render();\n    void onClick();\n}\n\n\/\/ Concrete Product 1\nclass WindowsButton implements Button {\n    public void render() {\n        System.out.println(\"Rendering a Windows-style button.\");\n    }\n\n    public void onClick() {\n        System.out.println(\"Windows button clicked!\");\n    }\n}\n\n\/\/ Concrete Product 2\nclass HTMLButton implements Button {\n    public void render() {\n        System.out.println(\"&amp;lt;button>HTML Button&amp;lt;\/button>\");\n    }\n\n    public void onClick() {\n        System.out.println(\"HTML button clicked!\");\n    }\n}\n\n\/\/ Creator (defines the Factory Method)\nabstract class Dialog {\n    \/\/ Factory Method\n    public abstract Button createButton();\n\n    \/\/ Some business logic that uses the factory method\n    public void renderWindow() {\n        Button okButton = createButton();\n        okButton.render();\n        okButton.onClick();\n    }\n}\n\n\/\/ Concrete Creator 1\nclass WindowsDialog extends Dialog {\n    public Button createButton() {\n        return new WindowsButton();\n    }\n}\n\n\/\/ Concrete Creator 2\nclass WebDialog extends Dialog {\n    public Button createButton() {\n        return new HTMLButton();\n    }\n}\n\n\/\/ Client code\npublic class FactoryMethodDemo {\n    private static Dialog dialog;\n\n    public static void main(String[] args) {\n        \/\/ Configuration could come from settings\/environment\n        String osType = System.getProperty(\"os.name\").toLowerCase();\n\n        if (osType.contains(\"win\")) {\n            dialog = new WindowsDialog();\n        } else {\n            dialog = new WebDialog();\n        }\n\n        dialog.renderWindow();\n    }\n}\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Singleton Intro The Singleton design pattern is a crucial concept in Java programming that ensures the existence of only one instance of a class and provides a global point of access to it. This pattern is particularly useful in scenarios where you want to control access to resources, manage configuration settings, or implement logging functionalities&hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":[],"_links":{"self":[{"href":"https:\/\/chernihiv.ddns.net\/index.php?rest_route=\/wp\/v2\/pages\/195"}],"collection":[{"href":"https:\/\/chernihiv.ddns.net\/index.php?rest_route=\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/chernihiv.ddns.net\/index.php?rest_route=\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/chernihiv.ddns.net\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/chernihiv.ddns.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=195"}],"version-history":[{"count":11,"href":"https:\/\/chernihiv.ddns.net\/index.php?rest_route=\/wp\/v2\/pages\/195\/revisions"}],"predecessor-version":[{"id":787,"href":"https:\/\/chernihiv.ddns.net\/index.php?rest_route=\/wp\/v2\/pages\/195\/revisions\/787"}],"wp:attachment":[{"href":"https:\/\/chernihiv.ddns.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=195"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}