<?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 Susith Hemathilaka on Medium]]></title>
        <description><![CDATA[Stories by Susith Hemathilaka on Medium]]></description>
        <link>https://medium.com/@susithrj?source=rss-ba668c7ed967------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fOI0w5o__evgeEdsFcubmA.jpeg</url>
            <title>Stories by Susith Hemathilaka on Medium</title>
            <link>https://medium.com/@susithrj?source=rss-ba668c7ed967------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 04:21:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@susithrj/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[Database Indexing In A Nutshell]]></title>
            <link>https://susithrj.medium.com/database-indexing-in-a-nutshell-b525b73eadef?source=rss-ba668c7ed967------2</link>
            <guid isPermaLink="false">https://medium.com/p/b525b73eadef</guid>
            <category><![CDATA[database-optimization]]></category>
            <category><![CDATA[indexing]]></category>
            <category><![CDATA[nonclustered-index]]></category>
            <category><![CDATA[clustered-index]]></category>
            <dc:creator><![CDATA[Susith Hemathilaka]]></dc:creator>
            <pubDate>Mon, 14 Nov 2022 05:19:29 GMT</pubDate>
            <atom:updated>2022-11-14T05:19:29.683Z</atom:updated>
            <content:encoded><![CDATA[<h4>Indexing is a performance-tuning method of allowing faster retrieval of records. An index creates an entry point for each value in indexed column(s).</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gGCPNwYuLxDXV3I5" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Indexes</em> are lookup tables used in the background of a database to speed up querying. Indexes power queries by providing a method to quickly lookup the requested data.</p><p>Simply , an index is a pointer to data in a table. An index in a database is very similar to an index page of a book.</p><h4>Index helps the database to find the row by providing a pointer to the associated value quickly.</h4><h4>Why Indexing?</h4><p>When database tables get bigger, scanning through millions, billions or trillions of rows to return just two or three rows is a huge waste.</p><p>Imagine when your teacher had asked you to open chapter number five and read some particular sub-topic from that particular chapter. You obviously didn’t scroll page by page to reach that particular sub-topic. You would go to the ‘index’ page, find page number for that particular sub-topic from chapter number five and directly open that page number.</p><p>In the same manner databases use their index to find the requested data when you ask for a specific row, In case DBMS haven’t a index, when you ask for a specific row, it will go sequentially and check with every row; “<em>Is this the row that I need?</em>”, If yes return it, if no, keep searching till the end.</p><p>An index is simply a data structure which is stored inside the DBMS, most commonly as a B- tree or hash table.</p><blockquote><em>By default, Most of the DBMS automatically create an index on primary and unique columns.</em></blockquote><p>In this article we will talk about two very popular indexing techniques.</p><h3><strong>Clustered Index</strong></h3><p>A clustered index defines the order in which data is stored in the table which can be sorted in only one way. So, there can be <strong>only a single clustered index per table.</strong> In an RDBMS, usually, the primary key allows you to create a clustered index based on that specific column. Any column values which are <strong>sorted and unique</strong> can be used as clustered index and binary search algorithm is used most of the time to retrieve the data efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*-YN1BsP3-36pzhPBxQIBRA.png" /><figcaption>Clustered Index on EmployeeId</figcaption></figure><h3><strong>Non-Clustered Index</strong></h3><p>When you need to query the data using another column, we can create a secondary index called a non-clustered index. Let’s say we want to create a secondary index for the<em> first</em> <em>name </em>in the <em>employee table</em>,<em> </em>while the clustered index is the<em> employee id.</em></p><p>For tables with higher number of insert/update operations, non-clustered indexing should be preferred, since it would not require extra time and CPU computations required for sorting the rows after every insert/update on the actual table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*H3-VBVXpbcdNakL4YqbhmA.png" /><figcaption>Non-clustered index on FirstName</figcaption></figure><p><strong><em>But Non Clustered index is lower than Clustered index</em></strong> since we still need to read from the table created for secondary index then jump to the employee table to get to a specific employee. But, it’s much faster than a full table scan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*ZheKqKov9ZQTB4UIkSWHRg.png" /><figcaption><strong>Speed Comparison of Operations</strong></figcaption></figure><h4><strong>How Index works?</strong></h4><p>Let’s say that you have an index for a primary key (<em>employee id</em>). This will create an ordered list of primary key values in a separate table, each entry has a pointer to the relative value in the original table.</p><p>Whenever you want to access a table using the primary key, it will use the binary search algorithm (takes time of O(LogN)) to access the required value in the Index table, and then, go to the relative value in the original table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0iA205Wx6sph2APmf0BynQ.png" /><figcaption><strong>Clustered Index</strong></figcaption></figure><p><strong>In clustered index </strong>created on <em>employee id,</em> <em>employee ids are stored in several data pages/ page files. </em>when you ask for a specific <em>employee id</em>, it will navigate to the relevant page file to pick the value.</p><blockquote><em>Page file is the basic and smallest unit where database systems save their data. All of the raw data stored in page files no matter how big your database is.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*oLsD4fXFop-Pk40vkcBusg.png" /><figcaption><strong>Non-Clustered Index</strong></figcaption></figure><p><strong>Non clustered indexes</strong> are created in a separate table; it has two columns, one for the last name, and one for the corresponding <em>employee id</em>. The created table is now sorted by <em>last name</em>, the way that we can’t actually do in the employee table, because we’re already sorted by the <em>employee id</em>.</p><p>When querying through a non clustered index it finds the relevant row using row locator associated with <em>employee Id</em>. Then it navigates through the clustered index and finds the relevant data row in the actual table.</p><h3><strong>Creating a Index</strong></h3><pre>CREATE INDEX employee_idx<br>  ON employee(employee_id);</pre><h3>Final thoughts</h3><p>Indexing a database requires a good understanding of the data, the user functions, and how the database is indexed. Opening a database terminal and running a query on a table both with and without indexes will notice a significant speed difference, when dealing with large datasets.</p><p>Indexing can greatly increase search speeds but they have associated drawbacks too. Each insert, update, or delete operation requires an update to the indexes. if you add more and more data it will consume more time and take up lots of space. When tables include multiple indexes, each index can increase the time it takes to process table updates. Creating indexes only on columns used for search purposes is a great choice so far.</p><h3>Wrapping Things Up</h3><p>Finally, I hope you got a clear idea on database indexing.</p><p><em>If there is anything that I have mentioned incorrectly, feel free to comment down below!</em>. <em>If you liked the post, click the 👏 below so more people can see it! Make sure that you follow me on </em><a href="https://medium.com/@susithrj"><strong><em>Medium</em></strong></a><strong><em> </em></strong><em>or on</em><a href="https://susithrj.wordpress.com/"><strong><em> My Blog</em></strong></a><strong><em> </em></strong><em>to get updates whenever a new article gets published.</em></p><p><em>Happy </em><strong>Indexing</strong><em>!👌</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b525b73eadef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improve Scalability Using Factory Method Design Pattern]]></title>
            <link>https://medium.com/javarevisited/improve-scalability-using-factory-method-design-pattern-4c6a166f0c0?source=rss-ba668c7ed967------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c6a166f0c0</guid>
            <category><![CDATA[creational-patterns]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Susith Hemathilaka]]></dc:creator>
            <pubDate>Mon, 07 Mar 2022 15:54:14 GMT</pubDate>
            <atom:updated>2022-03-07T15:54:14.702Z</atom:updated>
            <content:encoded><![CDATA[<h4>Factory pattern makes our code more robust, less coupled, and highly scalable.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CG6gbcR5Pad7s3fH" /><figcaption>Photo by <a href="https://unsplash.com/@kvtepov?utm_source=medium&amp;utm_medium=referral">Vlad Kutepov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Factory design pattern is a creational design pattern also known as Virtual Constructor. It delegates object creation and provides an interface for creating objects in a superclass and altering the sub classes without affecting the existing client implementation. It promotes the <strong>loose-coupling</strong> by eliminating the need to bind application-specific classes into the code.</p><blockquote><strong>Coupling</strong> means how tightly a class is related to another class. Coupling must be kept low. Modules anyway depend little on each other. All classes and methods must have small direct visible and flexible relations to other classes. But one module must be easily used by other modules.</blockquote><p><a href="http://javarevisited.blogspot.sg/2013/01/difference-between-factory-and-abstract-factory-design-pattern-java.html">Factory pattern</a> removes the instantiation of actual implementation classes from client code. The code interacts solely with the resultant interface or abstract class so that it will work with any classes that implement that interface or that extend that <a href="https://javarevisited.blogspot.com/2013/05/difference-between-abstract-class-vs-interface-java-when-prefer-over-design-oops.html">abstract class</a>. It decouples client code from concrete classes and you need to instantiate by allowing the sub-classes to choose the type of objects to create and alter the type of objects that will be created.</p><h4><strong>When to use?</strong></h4><p><em>1.Use the </em><a href="https://javarevisited.blogspot.com/2011/12/factory-design-pattern-java-example.html#axzz7CAMs6DOi"><em>Factory Method </em></a><em>when you don’t know beforehand the exact types and dependencies of the objects your code should work with.</em></p><p><em>2.Use the Factory Method when you want to extend its internal components without breaking the initial client implementation.</em></p><p><em>3. Use the Factory Method when you want to save system resources by reusing existing objects instead of rebuilding them each time.</em></p><h3><strong>Real-world System-Design Analogy</strong></h3><h3>Problem</h3><p>Think our application has 3 types of data which are categorized by the usage. The application should support different types of data connections according to the situation. Creating a <a href="https://javarevisited.blogspot.com/2012/06/jdbc-database-connection-pool-in-spring.html#axzz6ggCCT42g">data connection</a> each and every time is not sensible from design aspects. It makes boilerplate code and tight coupling. The following data types are used in our example.</p><p><strong>Hot data</strong> - data that have frequent access. stores in an in-memory cache store.</p><p><strong>Warm data </strong>- less frequent access. stores in a database.</p><h3>Solution</h3><p>If we applied the factory design pattern, Then we only have to pass a parameter from client code. Then the factory comes into play and it knows which type of data connection instance should return to us.</p><p>The client source is only written to give the data viewpoint. Client asks from factory request from the abstract class. the <a href="https://www.java67.com/2014/06/why-abstract-class-is-important-in-java.html">abstract class </a>gives the selected object.</p><figure><a href="https://javarevisited.blogspot.com/2018/02/top-5-java-design-pattern-courses-for-developers.html"><img alt="" src="https://cdn-images-1.medium.com/max/751/1*zt1WT2sKvRLb8RD4r5xAMw.png" /></a><figcaption>Class Diagram</figcaption></figure><h3>Implementation</h3><ol><li>Create an abstract class.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec9b04056c7b0ade12c6f6b4dfe999ae/href">https://medium.com/media/ec9b04056c7b0ade12c6f6b4dfe999ae/href</a></iframe><p>2.Create concrete classes extending the same abstract class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b40ec2e9c5a67223402acebbbd9ffc5/href">https://medium.com/media/9b40ec2e9c5a67223402acebbbd9ffc5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b00d877254b8a61140b75655e8898ee3/href">https://medium.com/media/b00d877254b8a61140b75655e8898ee3/href</a></iframe><p>3. Factory Class- Create a factory to generate objects of concrete class based on given information.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dba04854b10db07d899c9cae1f6929e0/href">https://medium.com/media/dba04854b10db07d899c9cae1f6929e0/href</a></iframe><p>4. Demo- Use the factory to get objects of the concrete class by passing information such as type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/585b2bcc7c1f7661a848a166b61dd34a/href">https://medium.com/media/585b2bcc7c1f7661a848a166b61dd34a/href</a></iframe><h4>Factory Design Pattern Advantages</h4><ol><li>Factory design pattern provides an approach to <a href="https://medium.com/javarevisited/10-oop-design-principles-you-can-learn-in-2020-f7370cccdd31">code for interface rather than implementation</a>.</li><li>Factory pattern removes the instantiation of actual implementation classes from client code. The factory pattern makes our code more robust, less coupled and easy to extend. As example, we can easily change the HotData class implementation because the client program is unaware of this.</li><li>Factory pattern provides <a href="http://www.java67.com/2015/05/difference-between-abstraction-and.html">abstraction </a>between implementation and client classes through inheritance.</li></ol><h3>Wrapping Things Up</h3><p>Finally, I hope you got a clear idea of the factory-method design pattern and its applicability. This article attempts to consolidate most of the common designs approach of the Factory method.</p><p>If you willing to learn about other design patterns I wrote,</p><ul><li><a href="https://susithrj.medium.com/demystifying-singleton-design-pattern-in-java-96887744d40a">Demystifying Singleton Design Pattern in Java</a></li><li><a href="https://medium.com/javarevisited/toned-down-code-complexity-using-facade-design-pattern-6f21d1e762d">Toned-down Code Complexity Using Facade Design Pattern</a></li></ul><p><em>If there is anything that I have mentioned incorrectly, feel free to comment down below!</em>. <em>If you liked the post, click the 👏 below so more people can see it! Make sure that you follow me on </em><a href="https://medium.com/@susithrj"><strong><em>Medium</em></strong></a><strong><em> </em></strong><em>or on</em><a href="https://susithrj.wordpress.com/"><strong><em> My Blog</em></strong></a><strong><em> </em></strong><em>to get updates whenever new article gets published.</em></p><p><em>Happy Coding!👌</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c6a166f0c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/improve-scalability-using-factory-method-design-pattern-4c6a166f0c0">Improve Scalability Using Factory Method Design Pattern</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Toned-down Code Complexity Using Facade Design Pattern]]></title>
            <link>https://medium.com/javarevisited/toned-down-code-complexity-using-facade-design-pattern-6f21d1e762d?source=rss-ba668c7ed967------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f21d1e762d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[facade-pattern]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Susith Hemathilaka]]></dc:creator>
            <pubDate>Tue, 01 Mar 2022 14:41:16 GMT</pubDate>
            <atom:updated>2022-03-01T14:41:16.008Z</atom:updated>
            <content:encoded><![CDATA[<h4>Giving a “Face/Facade” makes the code simple and clear to understand.</h4><figure><img alt="Sportmode Facade DesignPattern CodeExample Java" src="https://cdn-images-1.medium.com/max/1024/0*mbj7301zvEj9PEfg" /><figcaption>Photo by <a href="https://unsplash.com/@thevanegmond?utm_source=medium&amp;utm_medium=referral">Nathan Van Egmond</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A facade is a class that provides a simple interface to a complex subsystem (large body of code) that contains lots of moving parts. It’s a structural design pattern and hides too much complexity to improve readability, understandability and maintenance.</p><p>Facade Class is working as structure and chain of the necessary methods into one caller method to decouple client implementation from sub-systems. It delegates most of the work to other classes. Usually, <a href="https://javarevisited.blogspot.com/2015/01/adapter-vs-decorator-vs-facade-vs-proxy-pattern-java.html">facades </a>manage the full life cycle of objects they use. Key intentions of the design pattern is to hide much of the complexity and make the subsystem easy to use and decouple the client implementation from the complex subsystem.</p><h3>When do we use facade?</h3><p><strong>1. When you need to have a straightforward interface to a complex subsystem.</strong></p><p>ideal for very complex or difficult to understand due to the system having many interdependent classes.</p><p>further, subsystems get more complex over time. Even applying <a href="https://medium.com/javarevisited/7-best-online-courses-to-learn-object-oriented-design-pattern-in-java-749b6399af59">design patterns</a> typically leads to creating more classes. A subsystem may become more flexible and easier to reuse in various contexts, but <strong>the amount of configuration and boilerplate code it demands from a client grows ever larger.</strong> The Facade attempts to fix this problem by providing a shortcut to the most-used features of the subsystem which fit most client requirements.</p><p><strong>2. Use the Facade when you want to structure a subsystem into layers.</strong></p><p>Create facades to define entry points to each level of a subsystem. You can reduce coupling between multiple subsystems by requiring them to communicate only through facades.</p><figure><a href="https://javarevisited.blogspot.com/2018/02/top-5-java-design-pattern-courses-for-developers.html"><img alt="" src="https://cdn-images-1.medium.com/max/500/1*NWZhS0nKqbrC1XTe_f3Qkw.png" /></a></figure><p><strong>Real-world Analogy</strong></p><blockquote>Let’s say that we want to switch car driving mode manually. Then you have to perform the following operations in order to achieve the goal. The following diagram represents the process.</blockquote><figure><a href="https://javarevisited.blogspot.com/2013/06/5-must-read-books-to-learn-object.html"><img alt="" src="https://cdn-images-1.medium.com/max/931/1*eslVqOGSYpXwIZf9rjMgBg.png" /></a></figure><blockquote><strong>It can be quite complex and does require some knowledge to switching the modes correctly.</strong></blockquote><p><em>Most people like to do things with a single click. This is where </em><a href="https://medium.com/javarevisited/6-best-figma-ui-ux-design-courses-for-beginners-94711d31ce61"><em>user experience</em></a><em>(UX) comes into play. We like to just press one button and don’t worry about the complexities. That’s the concept behind the facade design pattern.</em></p><h3>Implementation</h3><p>Step 1 : create the interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65635f179d033a7e9107f719d70b4ad0/href">https://medium.com/media/65635f179d033a7e9107f719d70b4ad0/href</a></iframe><p>Step 2 : Create concrete classes implementing the same interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22db3d18893b8a8a63b0758deb8a9557/href">https://medium.com/media/22db3d18893b8a8a63b0758deb8a9557/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c47b624279f9b255a89e41224394cbc7/href">https://medium.com/media/c47b624279f9b255a89e41224394cbc7/href</a></iframe><p>Step 3 : Create a facade class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8532e67071b064fe29c449f16e0652e4/href">https://medium.com/media/8532e67071b064fe29c449f16e0652e4/href</a></iframe><p>Step 4: Add the Driver Code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bbd89b77a1f132a94c37c3ed538d2bf/href">https://medium.com/media/7bbd89b77a1f132a94c37c3ed538d2bf/href</a></iframe><p>Step 5: Verify the output.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5403a47e24803f28d694aaeae2aee8b8/href">https://medium.com/media/5403a47e24803f28d694aaeae2aee8b8/href</a></iframe><h3>Conclusion</h3><p>Let’s retrospect to find out if the intentions behind the facade design pattern are satisfied through the above implementation. Sport mode and Comfort mode classes are used as subsystems to hide the complexity. DrivingModeFacade Class decouples the client and the client can switch driving mode using a single step.</p><p>The facade pattern doesn’t force us to unwanted tradeoffs, because it only adds additional layers of <a href="https://javarevisited.blogspot.com/2010/10/abstraction-in-java.html#axzz6oOeSmpNw">abstraction</a>.</p><p>Sometimes the pattern can be overused in simple scenarios, which will lead to redundant implementations. Before Making it up decide the applicability by studying the objectives of a facade design pattern are satisfied.</p><h3>Wrapping Things Up</h3><p>Finally, I hope you got a clear idea of the facade design pattern and its use cases.</p><p><em>If there is anything that I have mentioned incorrectly, feel free to comment down below!</em>. <em>If you liked the post, click the 👏 below so more people can see it! Make sure that you follow me on </em><a href="https://medium.com/@susithrj"><strong><em>Medium</em></strong></a><strong><em> </em></strong><em>or on</em><a href="https://susithrj.wordpress.com/"><strong><em> My Blog</em></strong></a><strong><em> </em></strong><em>to get updates whenever a new article gets published.</em></p><p><em>Happy Coding!👌</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f21d1e762d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/toned-down-code-complexity-using-facade-design-pattern-6f21d1e762d">Toned-down Code Complexity Using Facade Design Pattern</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Singleton Design Pattern in Java]]></title>
            <link>https://susithrj.medium.com/demystifying-singleton-design-pattern-in-java-96887744d40a?source=rss-ba668c7ed967------2</link>
            <guid isPermaLink="false">https://medium.com/p/96887744d40a</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[creational-design-pattern]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Susith Hemathilaka]]></dc:creator>
            <pubDate>Thu, 08 Apr 2021 04:26:03 GMT</pubDate>
            <atom:updated>2021-08-31T16:27:25.781Z</atom:updated>
            <content:encoded><![CDATA[<h4>Design pattern is a solution at the design level for recurrent problems that we software engineers experience frequently. This article addresses the Singleton Pattern, which many consider to be the most basic but is still one of the most commonly used design patterns.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SM7VeVkx06zLmmkFmVirFA.jpeg" /><figcaption>Image Courtesy: <a href="https://unsplash.com/@ripato">Ricardo </a>on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><h3>Types of Design Patterns</h3><p>There are 23 design patterns in total. They are classified into three categories.</p><ol><li><strong>Creational Design Patterns</strong>- These patterns designed for class instantiation with class-creation patterns or object-creational patterns.</li><li><strong>Structural Design Patterns</strong>- These patterns deal with class structure and object composition. main objective is to increase the functionality of the classes while keeping it’s structure efficient and flexible.</li><li><strong>Behavioral Design Patterns</strong>- These patterns are designed with regard to Object communication and how they interact with each other.</li></ol><h3>Singleton Design Pattern</h3><p>Singleton design pattern is a creational design pattern and it focus on creation of objects. singleton pattern used to ensure only one instance can be created from a class. Cool! ✌.</p><p><strong><em>Where we use Singleton?</em></strong></p><p>To ensure only one instance created to provide global point of access to the resource costly objects. In terms of practical singleton patterns are used when connecting to external resource such as database through DB driver or DB Manager, logger, application configurations and caching.</p><p>Moreover singleton design pattern is building block of many other design patterns like factory, builder, prototype, facade and etc.</p><h4><strong>Implementing Singleton</strong></h4><p>we will look at few thing before implement singleton class. There are Common components in Singleton class.</p><p>A class using the singleton design pattern will include,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*D2Amd7KPJ86BQ7gBDIZs5A.png" /><figcaption>Singleton Class Diagram</figcaption></figure><p><strong><em>private constructor</em></strong>- to avoid others classes from creating new instances.</p><p><strong><em>private static variable</em></strong>- to store the constructed instance.</p><p><strong><em>public static method</em></strong>- to return the class instance we stored in private static variable.</p><p>All right, let’s gets dirty our hands with coding. There is more than one ways to implement singleton design pattern. We will discuss about only 3 mostly used implementation according to the different scenarios.</p><h3><strong>Eager Initialization</strong></h3><p>Eager initialization is the easiest way to create a singleton class. In eager initialization, the instance of singleton created at the time of class loading. Simply, It make a instance before getting request to initialize from other class. Then it leads to a drawback that instance is created even though client application might not be using it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37697ed5370104dd2a50f67299e8531c/href">https://medium.com/media/37697ed5370104dd2a50f67299e8531c/href</a></iframe><h3><strong>Lazy Initialization</strong></h3><p>Lazy initialization only create instance when some other class request for instance. The only instantiated static variable is initially declared null, and it is only instantiated when null at the time of the check.</p><p><em>getInstance() method </em>will check if there is any instance of that class is already created. If yes, then our method<em> getInstance()</em> will return that old instance and if not then it creates a new instance of the singleton class in JVM and returns that instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/567dfeb6def5fb0c77ca85d931d51165/href">https://medium.com/media/567dfeb6def5fb0c77ca85d931d51165/href</a></iframe><h3><strong>Dealing with multi threaded environments</strong></h3><p>Singletons created using eager or lazy initialization are not thread safe. Then we need to write thread safe code when dealing with multi threaded programs.</p><p><strong><em>Where the problem occurs?</em></strong></p><p>If both the threads calls out <em>getInstance()</em> method at the same time, the i<em>nstance == null</em> condition will return for both the thread. So, two different instances of the same class will be created. That will break the singleton principle.</p><p>Synchronized block can be used to ensure singleton works fine and only one instance created to share between many threads. It avoids two or more threads try to create objects in same time. Let’s look how we can make thread safe singleton.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ba11a23da1773e88f162ce1479dcc50/href">https://medium.com/media/0ba11a23da1773e88f162ce1479dcc50/href</a></iframe><h3>Enhance Performance</h3><p>Now code is totally safe right! But performance is critical aspect whilst writing safe code. if we synchronized in above way threads will acquires lock everytime when it try to get instance. Our next effort is reduce the count of acquring lock and enchance performance. For that we use double check lock singleton pattern. In here it acquire lock only when instance is null wchich means first and only time creating the singleton instance. Let’s move to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55a75dd68da72ff782acbc721974c816/href">https://medium.com/media/55a75dd68da72ff782acbc721974c816/href</a></iframe><h3>Wrapping Things Up</h3><p>Finally, hope you got an clear idea of singleton principle and its’ uses. This article attempts to consolidate most of the common designs approaches of singleton. Although singleton is criticized for associated drawbacks too. To make perfect singleton based on the scenario you can use more advanced techniques.</p><p><em>If there is anything that I have mentioned incorrectly, feel free to comment down below!</em>. <em>If you liked the post, click the 👏 below so more people can see it! Make sure that you follow me on </em><a href="https://medium.com/@susithrj"><strong><em>Medium</em></strong></a><strong><em> </em></strong><em>or on</em><a href="https://susithrj.wordpress.com/"><strong><em> My Blog</em></strong></a><strong><em> </em></strong><em>to get update whenever new article gets published.</em></p><p><em>Happy Coding!👌</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96887744d40a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>