Singleton Pattern is regarded as one of the most fundamental design patterns of JAVA. The name draws from the mathematical idea of a singleton set that only has one element in it. It is its own super-set as well as subset.
On mapping it to JAVA, by definition, a Singleton pattern is established when a particular class has no more than one object or instance. The design pattern also restricts future instances of that class from being created. As this pattern does not involve much sophistication, it is frequently used in JAVA codes. However, the Singleton Pattern sometimes creates more problems than give solutions by blocking behavioral flow between objects. It also brings with it the concept of global state in an application using the Singleton pattern.
Table of Contents
Real Life Example
A prime example where the Singleton pattern finds use is in database manipulations. Sometimes establishing one database connection proves to be more economical and storage efficient as compared to making a new connection for every object that is created. In such cases, inputs and information flow from the single database connection is effectively shared between all the other objects. This pattern also works well when your program has a uni-polar governing manager that controls the secondary and tertiary parts of the program.
Example with Code
Below is a simple code for a Coin Collector machine that adds or deducts coin balance from your account. This code will implement the Singleton design pattern by initiating the class only once.
public class Coin_Collector { private static final int add_coin_balance = 40; private int balance; private static Coin_Collector single = new Coin_Collector (); //Class being instantiated only once public static Coin_Collector getSingle(){ return single; } public int getBalance(){ return balance; } public void addBalance(){ balance = balance + add_coin_balance; } // adding coin balance public void subtractBalance(){ balance--; } //subtracting coin balance }
When to Use Singleton Pattern
This design pattern should be used only when a situation arises in your code where more than one instance of a class will negatively impact the program. In such cases, hide the class constructor and add a static function that will return the only instance of the class as shown in the code above.
0 Comments