0% found this document useful (0 votes)
25 views

Lab 6 Singleton

Uploaded by

Ayesha Asad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Lab 6 Singleton

Uploaded by

Ayesha Asad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

LAB SESSION # 6: Design Pattern I

[Introduction to Design Patterns: Creational & Structural Patterns]


Design patterns help to solve common design issues in object-oriented software.
You will learn what they are and how they can be applied. In this module you will
learn the creational and structural design patterns. You will continue to learn and
practice expressing designs in UML, and code some of these patterns in Java.

1. Introduction to Design Patterns


Design patterns, originating from Christopher Alexander's architectural concepts,
were adapted into software engineering by innovators like Kent Beck and Ward
Cunningham. They represent distilled expertise and solutions for recurring design
problems in software development, fostering a community-driven approach to
problem-solving and promoting reusable, maintainable code.

2. What are Design Patterns?


Design patterns are reusable solutions to common design problems in object-
oriented programming, providing best practices derived from experienced
developers. Each pattern consists of a name, problem description, solution, and
consequences, facilitating flexible, maintainable, and reusable code.

3. Why use them


Design patterns offer several benefits to object-oriented developers:

1. Flexibility: Implementing design patterns enhances code flexibility by


promoting the correct level of abstraction, leading to loosely coupled
objects. This loose coupling facilitates easier modifications to the codebase.

2. Reusability: Design patterns encourage the creation of loosely coupled and


cohesive objects and classes, making the code more reusable. This
reusability simplifies testing and maintenance compared to highly coupled
codebases.

3. Shared Vocabulary: Design patterns establish a shared vocabulary among


team members, aiding in code communication and fostering better
understanding and collaboration within the team.

4. Capture Best Practices: Design patterns encapsulate proven solutions to


recurring problems, providing valuable insights into software design for
inexperienced developers. By learning and applying these patterns,
developers can gain a deeper understanding of software design principles
and best practices.

5. Improved Reusability and Documentation: Design patterns promote the


reuse of successful designs and architectures, making them more accessible
to developers working on new systems. Additionally, design patterns help in
documenting and maintaining existing systems by specifying class and
object interactions explicitly, thus improving system documentation and
maintenance efficiency.

4. How to select and use one


To effectively choose a design pattern, developers need a comprehensive
understanding of each pattern and the ability to identify the specific design
problem they are facing. Design problems can be categorized into creational,
structural, or behavioral issues.

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

1. Creational patterns Creational design patterns manage object instantiation,


providing flexibility in creation processes while hiding implementation
details. They encapsulate knowledge about concrete classes and allow for
variations in object creation through inheritance. Sometimes, multiple
patterns may seem applicable, and they can complement each other, such as
when using the Builder pattern alongside others to determine component
creation.

2. Structural patterns Structural patterns focus on composing classes and


objects to form larger structures. Class patterns use inheritance to compose
interfaces or implementations, while object patterns describe ways to
compose objects to achieve new functionality. Class patterns, like multiple
inheritance, merge classes into one, while object patterns offer runtime
flexibility in composition, enabling dynamic changes impossible with static
class composition.

3. Behavior patterns Behavioral patterns manage algorithms and


responsibilities among objects, emphasizing communication patterns. They
simplify complex control flows at runtime and promote loose coupling
between objects. By employing object composition instead of inheritance,
these patterns enable peer objects to collaborate effectively, as seen in the
Mediator pattern, which facilitates indirect communication between peers to
minimize inter-object dependencies.

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

Initialization Types of Singletons


Singleton class can be instantiated by two methods:
 Early initialization: In this method, class is initialized whether it is to
be used or not. The main advantage of this method is its simplicity. You
initiate the class at the time of class loading. Its drawback is that class is
always initialized whether it is being used or not.
 Lazy initialization: In this method, class in initialized only when it is
required. It can save you from instantiating the class when you don’t
need it. Generally, lazy initialization is used when we create a singleton
class.
1. Static Member:
The Singleton pattern or pattern Singleton employs a static member within the
class. This static member ensures that memory is allocated only once, preserving
the single instance of the Singleton class.

// Static member to hold the single instance


private static Singleton instance;

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 {

// Making the constructor as Private


private Singleton()
{
// Initialization code here
}
}

3. Static Factory Method:


A crucial aspect of the Singleton pattern is the presence of a static factory
method. This method acts as a gateway, providing a global point of access to the
Singleton object. When someone requests an instance, this method either creates
a new instance (if none exists) or returns the existing instance to the caller.
Java
// Static factory method for global access
public static Singleton getInstance()
{
// Check if an instance exists
if (instance == null) {
// If no instance exists, create one
instance = new Singleton();
}
// Return the existing instance
return instance;
}

Implementation of Singleton Method Design Pattern

The implementation of a Singleton Design Pattern or Pattern Singleton is


described in the following class diagram:

Implementation of Singleton Method Design Pattern

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.

/*package whatever //do not write package name here */


import java.io.*;
class Singleton {
// static class
private static Singleton instance;
private Singleton()
{
System.out.println("Singleton is Instantiated.");
}
public static Singleton getInstance()
{
if (instance == null)
instance = new Singleton();
return instance;
}
public static void doSomething()
{
System.out.println("Something is Done.");
}
}

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

1. Explore the four methods for initializing the Singleton method

2. What is Singleton Design Pattern?

3. How does the Singleton pattern ensure that only one instance of a class is

available in an application?

4. What are the advantages of using the Singleton Design Pattern?

5. What are the disadvantages of using the Singleton Design Pattern?

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?

8. Describe a good use case for the Singleton Pattern?

9. How can you test a class designed with the Singleton Pattern?

10.What is the difference between an eager and a lazy Singleton?

11.How should the Singleton Pattern be used in a distributed system?

12.Describe how the Singleton Pattern can help reduce resource consumption.

13.Is the Singleton Pattern a good choice for every scenario?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy