Lab 6 Singleton
Lab 6 Singleton
For instance:
If there are too many instances of a class representing the same thing with
identical properties used only as read-only, the Singleton pattern can be
chosen to ensure a single instance for the entire application, reducing
memory usage.
If classes are overly dependent on each other, resulting in changes in one
class affecting all dependent classes, patterns like Bridge, Mediator, or
Command can be applied.
In cases where there are incompatible interfaces in different parts of the code
and conversion is needed to make the code work, the Adapter pattern can be
used.
Categorization of patterns
Design patterns can be categorized in the following categories:
• Creational patterns
• Structural patterns
• Behavior patterns
The below tables show the list of patterns under their respective categories:
Singleton Design Pattern
When to use Singleton Method Design Pattern?
Use the Singleton method Design Pattern when:
There must be exactly one instance of a class (single object) and it must
be accessible to clients from a well-known access point.
When the sole instance should be extensible by subclassing and clients
should be able to use an extended instance without modifying
Singleton classes are used for logging, driver objects, caching, and
thread pool, database connections
2. Private Constructor:
The Singleton pattern or pattern singleton incorporates a private constructor,
which serves as a barricade against external attempts to create instances of the
Singleton class. This ensures that the class has control over its instantiation
process.
// Private constructor to
// prevent external instantiation
class Singleton {
The implementation of the singleton Design pattern is very simple and consists of
a single class. To ensure that the singleton instance is unique, all the singleton
constructors should be made private. Global access is done through a static
method that can be globally accesed to a single instance as shown in the code.
class GFG {
public static void main(String[] args)
{
Singleton.getInstance().doSomething();
}
}
Output
Singleton is Instantiated.
Something is Done.
The getInstance method, we check whether the instance is null. If the instance is
not null, it means the object was created before; otherwise, we create it using the
new operator.
Lab Task:
Solve the following questions
3. How does the Singleton pattern ensure that only one instance of a class is
available in an application?
6. What alternative design patterns can be used to achieve the same goals as the
Singleton Pattern?
7. How can you ensure thread safety when implementing a Singleton Pattern?
9. How can you test a class designed with the Singleton Pattern?
12.Describe how the Singleton Pattern can help reduce resource consumption.