0% found this document useful (0 votes)
7 views11 pages

Lab#06 Singleton Design Pattern

The document outlines the Singleton Design Pattern, a creational pattern ensuring a class has only one instance with a global access point, useful for resource management and coordination. It details the structure, characteristics, and implementation of the pattern, emphasizing its benefits in simplifying design and enhancing reusability. Additionally, it provides examples of applications and comparisons with conventional implementations, along with lab tasks for practical application.

Uploaded by

Ahsan Ali
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)
7 views11 pages

Lab#06 Singleton Design Pattern

The document outlines the Singleton Design Pattern, a creational pattern ensuring a class has only one instance with a global access point, useful for resource management and coordination. It details the structure, characteristics, and implementation of the pattern, emphasizing its benefits in simplifying design and enhancing reusability. Additionally, it provides examples of applications and comparisons with conventional implementations, along with lab tasks for practical application.

Uploaded by

Ahsan Ali
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/ 11

Department of Software Engineering

Mehran University of Engineering and Technology, Jamshoro

SW227 – SOFTWARE DESIGN AND ARCHITECTURE


Instructor Ms. Afifah Jalbani Practical/Lab No. 06
Date 06-03-2025 CLOs 3
Signature Assessment Score 1 Mark

Topic
Objectives - To implement Singleton Pattern

Lab Discussion: Theoretical concepts and Procedural steps

Understanding Design Patterns in Object-Oriented Software:

 Designing Object-Oriented Software:

 Designing object-oriented software is challenging, and creating reusable designs is even


more difficult.
 Key challenges include identifying relevant objects, structuring classes appropriately,
defining interfaces, and establishing relationships among classes.

 Balancing Specificity and Generality:

 Designs should address the current problem but be general enough to accommodate future
needs.
 Redesign should be minimized to ensure flexibility and reusability.

 Learning Through Experience:

 Experienced designers recognize that good design is rarely achieved on the first attempt.
 They frequently reuse and refine their designs based on past successes, which contributes to
their expertise.

 Pattern Recognition in Design:

 Expert designers do not solve problems from scratch; they apply proven solutions that have
worked previously.
 Recurrent patterns of classes and object interactions solve specific design issues and enhance
flexibility and reusability.

 Design Patterns as Reusable Solutions:

 Patterns in object-oriented systems help designers by providing established solutions for


common design problems.
 Familiarity with design patterns allows designers to apply them directly without
rediscovering solutions.

1
 Analogy with Storytelling:

 Just as writers use familiar plot patterns (e.g., "Tragically Flawed Hero"), designers use
design patterns to guide their decisions.
 Knowing a design pattern allows many design decisions to follow naturally.

 Capturing and Reusing Design Experience:

 Design patterns systematically document important and recurring designs in object-oriented


systems.
 Patterns help record design experiences in a form that others can use effectively.

 Benefits of Design Patterns:

 They simplify the reuse of successful designs and architectures.


 Design patterns assist in selecting alternatives that enhance reusability while avoiding
choices that hinder it.
 They improve documentation and maintenance by explicitly specifying class and object
interactions.

 Proven and Established Patterns:

 The patterns discussed are not new or untested; they have been applied multiple times in
different systems.
 Patterns documented are either well-known in the object-oriented community or are elements
of successful systems.

What is a Design Pattern?

 Design patterns offer reusable solutions to recurring design problems in software


development, expressed through objects and interfaces rather than physical structures.
 Each design pattern consists of four essential elements:

 Pattern Name: A concise handle that identifies the design problem, solution, and
consequences, enhancing communication and understanding among developers.
 Problem: Defines the context and conditions where the pattern applies, helping to recognize
situations that require the pattern's application.
 Solution: Provides an abstract template of the design elements, their relationships, and
responsibilities, allowing adaptation to various specific implementations.
 Consequences: Explores the results, trade-offs, and impacts of applying the pattern,
including considerations of space, time, flexibility, extensibility, and portability.

Design patterns provide a vocabulary for describing and discussing complex design issues, allowing
designers to leverage proven solutions rather than reinventing from scratch.
They are not concrete designs like data structures or complete systems, but rather abstract templates
that describe communicating objects and classes tailored to solve general design problems. A design
pattern identifies and abstracts the key aspects of a common design structure, focusing on how
participating classes and instances interact, collaborate, and distribute responsibilities. Patterns
address specific object-oriented design problems, guiding when and how to apply them and
evaluating their suitability given other design constraints and trade-offs.

2
Describing Design Patterns

To effectively describe design patterns, it’s essential to go beyond graphical notations. While these
diagrams illustrate the end relationships between classes and objects, they don't capture the thought
process behind the design. To make the design reusable, one must also document the following:

 Decisions: The key choices that shaped the design.


 Alternatives: Different solutions that were considered.
 Trade-offs: The compromises made between various options.

Additionally, concrete examples are important for showing how the design works in practice. A
standardized template is used for describing design patterns, ensuring a consistent and easily
comparable format. This template includes multiple sections such as the pattern’s name, intent,
motivation, applicability, structure, and consequences, among others, making it easier for developers
to learn, compare, and implement design patterns.

1. Pattern Name and Classification

The pattern's name summarizes its purpose and functionality in one or two words. This name
becomes part of your design vocabulary and helps simplify discussions around design decisions.

2. Intent

The intent describes what the pattern is designed to do, the design problem it solves, and the
motivation for using it.

3. Also Known As

Some patterns are known by different names in various domains, so it’s helpful to include any
alternative names.

4. Motivation

This section provides a scenario or problem description that demonstrates how and why the pattern
is useful. It’s meant to help the reader understand the design challenge and how the pattern resolves
it.

5. Applicability

This section highlights the conditions under which the pattern can be applied and the problems it
solves. It also helps you recognize poor design situations where this pattern can bring improvement.

6. Structure

This section provides a visual representation of the pattern, typically through UML diagrams. It
demonstrates how classes and objects in the pattern are structured and how they interact.

7. Participants

This section lists the classes or objects involved in the pattern and their responsibilities.

3
8. Collaborations

This section explains how the participants (classes/objects) interact and collaborate to achieve the
pattern's intent.

9. Consequences

This section explains the benefits and trade-offs of using the pattern, including potential side effects,
performance concerns, and impact on system flexibility or maintainability.

10. Implementation

This section addresses any considerations for implementing the pattern, such as pitfalls or tips for
specific programming languages.

11. Sample Code

This section provides code snippets to illustrate how to implement the pattern.

12. Known Uses

This section lists real-world use cases of the pattern in different systems or applications to provide
evidence of its practicality.

13. Related Patterns

This section identifies patterns related to the current one and explains how they differ or how they
can be combined.

The Catalog of Design Patterns

The Catalog of Design Patterns is typically a collection of common design patterns used in software
development. It serves as a reference guide to help developers understand and implement these
patterns effectively. The most famous catalog comes from the "Gang of Four" book, "Design
Patterns: Elements of Reusable Object-Oriented Software," which categorizes patterns into three
main types:

1. Creational Patterns: Deal with object creation mechanisms. Examples include Singleton,
Factory Method, and Abstract Factory.
2. Structural Patterns: Focus on how classes and objects are composed to form larger
structures. Examples include Adapter, Composite, and Decorator.
3. Behavioral Patterns: Concerned with object interaction and responsibility. Examples
include Observer, Strategy, and Command.

4
Singleton Design Pattern
The Singleton pattern is a creational design pattern that ensures a class has only one instance and
provides a global point of access to that instance. This is particularly useful in scenarios where a
single instance of a class is required to control actions, manage resources, or coordinate events
across the system.
Intent: The intent of the Singleton design pattern is to ensure that a class has only one instance and
to provide a global point of access to that instance. This is particularly useful in scenarios where
having multiple instances would lead to undesirable behavior or resource consumption.
Motivation: The motivation for implementing the Singleton pattern typically stems from the
following scenarios

 Resource Management: In situations where a resource (like a database connection, file


handler, or configuration manager) is expensive to create and should be reused, the Singleton
pattern ensures that only one instance manages that resource, preventing resource wastage.
 Global State: Sometimes, it's necessary to maintain a global state that can be accessed by
various parts of an application. The Singleton pattern provides a centralized object that
manages this state, making it easier to coordinate actions across different components.
 Coordination: In systems where multiple components need to coordinate their actions (like
event management, logging, or configuration settings), the Singleton ensures that there’s a
single coordinator that maintains consistency and integrity of the operations.
 Controlled Access: By controlling the instantiation of the class, the Singleton pattern
prevents external entities from creating additional instances, ensuring that access to the
instance is managed and consistent throughout the application.

Key Characteristics

5
1. Single Instance: The Singleton pattern restricts the instantiation of a class to one single instance.
2. Global Access Point: It provides a global point of access to that instance.
3. Lazy Initialization: Often, the instance is created only when it is needed (lazy initialization).

When to Use the Singleton Pattern

 When you need exactly one instance of a class and no more, e.g., for logging, configuration
management, or database connections.
 When the instance should be available globally across the application.

Applications of Singleton Pattern

 Print Spooler: A print spooler manages print jobs from multiple applications. By using the
Singleton pattern, you ensure that all print jobs are coordinated through a single spooler instance,
preventing conflicts and managing the order of print jobs efficiently.

 File System: In many operating systems, the file system is managed through a single instance that
provides access to files and directories. This ensures that file operations are synchronized,
preventing issues like file corruption due to concurrent access.

 Window Manager: A window manager controls the layout and appearance of windows on a
display. By implementing it as a Singleton, it ensures that all windows are managed consistently and
that resources (like screen space) are allocated effectively without conflicts.

 One Input/Output Socket: In network applications, you might want a single socket connection
for communication. The Singleton pattern can be used to ensure that only one socket instance exists,
simplifying connection management and preventing resource exhaustion

Ensuring a Single Instance

To ensure that a class has only one instance and that the instance is easily accessible, the following
strategies are employed:

1. Private Constructor: Make the constructor of the class private. This prevents external code
from creating instances directly.

2. Static Variable: Use a static variable within the class to hold the instance. This variable will be
responsible for storing the sole instance of the class.

3. Static Method for Access: Provide a public static method that allows access to the instance.
This method checks if the instance is null, and if so, it creates it. This way, the instance is
created only when needed (lazy initialization).

Global Variables vs. Singleton

6
 Global Variables: While global variables can make an object accessible from anywhere in the
code, they can lead to multiple instances if not managed properly. They can also introduce
complexities such as dependency management, making the code harder to maintain and test.

 Singleton Class: The Singleton pattern allows the class itself to manage its instance, ensuring
that only one instance exists and is accessed through a controlled interface. This encapsulation
promotes better code organization and reduces potential errors associated with global state.

Singleton Pattern: Applicability


Use the Singleton pattern when there must be exactly one instance of a class, and it must be
accessible to clients from a well-known access point
SINGLETON Pattern: Structure

Singleton
static uniqueInstance
singletonData
static instance()
singletonOperation()
return uniqueInstance

Structure Explanation:

 Singleton: The class marked as Singleton is the class that will restrict the instantiation of itself
to only one object.

 static uniqueInstance: This is a static member variable that holds the single instance of the
Singleton class. It is usually private to prevent direct access from outside the class.

 singletonData: This represents the data or attributes of the Singleton class. These could be any
variables or states that need to be shared globally but should only exist once in the application.

 static instance(): This is a static method that controls access to the Singleton instance. It ensures
that if the instance does not already exist, it is created. If it does exist, it returns the existing instance.

 singletonOperation(): This represents methods that can be performed on the Singleton instance.
These operations work on singletonData.

 return uniqueInstance: This refers to the instance() method returning the single instance
(represented by uniqueInstance) when called.

Singleton Pattern Participants & Collaboration

7
Participants:
◦ Singleton
◦ Defines an instance() operation that lets clients access its unique instance.
◦ Instance is a class operation (i.e.: static)
◦ May be responsible for creating its own unique instance
◦ Collaboration:
◦ Clients access a Singleton instance solely through Singleton's Instance operation.

Singleton Pattern: Consequences

◦ Controlled access to sole instance


◦ As the constructor is private, the class controls when an instance is created
◦ Reduced name space
◦ Eliminates the need for global variables that store single instances
◦ Permits a variable number of instances
◦ The class is easily modified to allow n instances when n is not 1

Singleton Pattern: Implementation (Example in Code)

Example Usage:

8
Key Points:

 Private Constructor: The constructor is private, which prevents direct instantiation of the
class from outside.
 Static Instance Method: A static method (instance()) ensures that only one instance of
the class is created (Lazy Initialization).
 Global Access: The instance() method provides a global point of access to the single
instance of the class.
 Lazy Initialization: The Singleton instance is created only when it is needed (first call to
instance()).

The following image compares two different types of implementations: Singleton implementation
vs. Conventional implementation. It shows how objects interact with a central resource in both
cases.

Singleton Implementation (Left Side)

9
 Shared Resource: At the top of the diagram is a shared resource (likely a database or a
central configuration) that is used by multiple clients (represented by students or users).
 Single Instance: Only one instance of the object (the professor) interacts with the shared
resource. All clients (students) rely on this single instance to access the resource.
 Arrow Flow: The arrows represent the flow of communication, showing that the clients do
not directly interact with the shared resource but access it through the single instance
(professor).

Characteristics of Singleton Implementation:

1. Single Point of Access: The professor (Singleton instance) is the only one who interacts
directly with the resource, ensuring consistency and controlled access.
2. Efficient Resource Management: Since there is only one instance of the professor
managing the resource, it avoids unnecessary duplication of effort or resources.
3. Global Access: All clients (students) can access the shared resource through the professor,
but they are using the same professor instance.

Conventional Implementation (Right Side)

 Multiple Instances: In this case, there are multiple professors, each interacting directly with
the shared resource (such as a database).
 Individual Client Interaction: Every client (student) interacts with a different professor,
and each professor accesses the shared resource independently.
 Arrow Flow: The arrows show that each professor has its own path to the resource,
indicating independent control and access.

Characteristics of Conventional Implementation:

1. Multiple Points of Access: Every professor (object instance) interacts directly with the
resource, which can lead to inconsistency if the resource isn't managed properly.
2. Higher Resource Usage: Since there are multiple professors (instances), the system uses
more memory and resources. Each instance can introduce overhead due to repeated resource
access.
3. Decentralized Control: Each instance of the professor has its own state and access, making
it harder to coordinate and synchronize actions between the instances.

Related Patterns: Many patterns can be implemented using the Singleton pattern. Abstract Factory,
Builder, Prototype.

Lab Tasks:

10
Implement the singleton pattern in a class which returns database connections to the clients.

11

You might also like