Design Pattern (2)
Design Pattern (2)
OUTLINE
▰ Creational Patterns
▰ Patterns
▰ Behavioral Patterns
2
INTRODUCTIO
N
Design patterns are common solutions to recurring
problems in software design. They help create flexible
and reusable software systems by offering best
practices for different programming situations. Here are
some of the most commonly used design patterns,
divided into three categories: Creational, Structural,
and Behavioral.
4
Creational
Patterns
These patterns deal with object creation mechanisms, trying to create
objects in a way that suits the situation.
Singleton
When to use:
When you need only one instance of a class throughout your application, such as managing a shared
resource (e.g., a logging class or a configuration manager).
Pros:
• Ensures control over resource management.
• Saves memory by avoiding multiple instance creation.
Cons:
• Can make unit testing difficult since the global instance cannot be easily reset or replaced.
• Violates the Single Responsibility Principle (SRP) since it controls both instance management and
business logic.
6
Real-world examples:
o Database connections: A database connection pool often uses a singleton pattern to manage
connections, ensuring only one instance manages the pool of connections across the entire
application.
o Logging service: A logging framework that requires a single log file to be written globally across the
application can implement the Singleton pattern.
o Configuration manager: Managing configuration settings of an application that are accessed globally
is another common Singleton use.
How to use:
Define a class with a private constructor, a static method that returns the singleton instance, and prevent
cloning or creating new instances by reflection.
7
Singleton
8
Factory Method
When to use:
o When a class cannot anticipate the type of object it needs to create or when the exact class of
objects to create is determined at runtime.
o When the exact type of object to create depends on conditions.
Pros:
o Promotes loose coupling between client code and object creation.
o Follows Open/Closed Principle by allowing new types to be added without altering existing code.
Cons:
o Increases code complexity by introducing a layer of abstraction for object creation.
9
Factory Method
How to use:
Subclasses override the factory method to
create different product types.
Real-world examples:
o GUI toolkits: Different operating systems use different
user interface styles. A factory method can abstract the
creation of buttons, windows, etc., allowing the
application to run on multiple platforms.
o Payment gateways: Online payment systems that offer
various payment methods (PayPal, Stripe, etc.) use a
factory method to create payment processors based on
user selection.
o Document generation: A word processor might use a
factory to generate different document formats (e.g.,
PDF, Word, HTML).
Builder
When to use:
• When creating a complex object requires step-by-step construction (e.g.,
constructing a complex form or assembling multiple sub-components).
Pros:
• Constructs complex objects step-by-step.
• Improves code readability and maintains consistency.
Cons:
• May lead to increased complexity if the object has fewer parameters.
11
Builder
Real-world examples:
o Complex forms: In web applications, complex forms with
many conditional fields can be built using the Builder
pattern.
o Car assembly: When building a car with different
configurations, a builder can assemble parts (engine,
tires, body) in a controlled manner.
o Meal preparation: Fast food restaurants use a builder
pattern when offering customers the ability to "build their
meal" (custom burgers, sandwiches, etc.).
How to use:
• Create a builder class that assembles different
parts of the product.
12
Structural
Patterns
These patterns are concerned with how classes and
objects are composed to form larger structures.
Adapter
When to use:
• When you need to make two incompatible interfaces work
together without changing their existing code.
Pros:
• Provides flexibility by making existing code reusable with new
libraries.
Cons:
• Can introduce complexity if overused.
How to use:
• Create an adapter class that wraps one class and provides the
interface expected by the client.
14
Adapter
Real-world examples:
• Power adapters: A power adapter that allows
an electronic device to plug into various
electrical outlets (e.g., converting US plugs to
EU sockets).
• Legacy system integration: Adapting a
legacy system interface so that modern
systems can interact with it, like an old CRM
integrated with a new billing system.
• Payment gateways: Adapting different
payment systems (PayPal, Stripe) to a
common interface so that they can be used
interchangeably in an e-commerce platform.
15
Decorator
When to use:
• When you need to add functionality to an object dynamically, without
altering its structure.
Pros:
• Allows adding behavior without modifying original code.
• More flexible than inheritance.
Cons:
• Can complicate the design if many decorators are stacked.
How to use:
• Wrap an object with a decorator that adds new behavior.
16
Decorator
Real-world examples:
• Java I/O streams: The Java InputStream
and OutputStream classes use decorators
to add behavior like buffering,
compression, or encryption without
modifying the core functionality.
• Web request handlers: HTTP request
handlers can use decorators to add
logging, authentication, or caching
behavior to basic request handling.
• Social media filters: A photo-sharing app
can use decorators to apply filters
(grayscale, sepia, etc.) to an image
dynamically.
17
Facade
When to use:
• When you want to simplify the interaction between complex systems or
provide a unified interface to a set of interfaces in a subsystem.
Pros:
• Simplifies the client code by hiding complex implementations.
• Decouples client code from the subsystem.
Cons:
• Can become a god object if it becomes too complex, handling too many
responsibilities.
How to use:
• Create a facade class that wraps the complex subsystems and provides a
simple interface.
18
Facade
Real-world examples:
• Home theater system: A universal
remote control provides a facade for
controlling different devices like a TV,
DVD player, and sound system with a
single interface.
• Car dashboard: Modern cars have
complex systems (air conditioning,
navigation, radio) controlled via a
simple dashboard interface.
• Simplified API access: Facade
patterns are used in web services to
provide a simple interface to a complex
backend system, such as a cloud
provider that simplifies access to
multiple services (e.g., compute, 19
storage, etc.).
Behavioral Patterns
These patterns are concerned with communication
between objects, focusing on interaction and
responsibility among them.
Observer
When to use:
• When an object’s state change should trigger updates in other dependent
objects without tight coupling between the objects.
Pros:
• Promotes loose coupling between the subject and observers.
• Good for event-driven systems.
Cons:
• Can lead to memory leaks if observers are not properly managed (e.g., not
removed when no longer needed).
How to use:
• Define a subject that notifies observers whenever its state changes.
21
Observer
Real-world examples:
• Social media notifications: When you follow
someone, you get notified when they post new
content. You are the observer, and the subject is
the user you follow.
• Stock market updates: A stock price monitoring
app might notify users (observers) when certain
stock prices change (subject).
• Email subscribers: Email systems use the
observer pattern to notify subscribers of new blog
posts, news articles, or product updates.
22
Strategy
When to use:
• When you want to choose an algorithm’s behavior at runtime based on the
client’s needs, allowing you to easily swap strategies.
Pros:
• Makes algorithms interchangeable and improves flexibility.
• Adheres to Open/Closed Principle.
Cons:
• Clients must be aware of different strategies.
How to use:
• Define a family of algorithms (strategies) and encapsulate them in classes.
23
Strategy
Real-world examples:
• Navigation apps: Apps like Google Maps use
different algorithms (car, walking, public transport)
to calculate routes based on user preferences.
• Video compression: Different compression
algorithms (H.264, HEVC) can be applied
dynamically based on the file format or device.
• Payment processors: E-commerce systems
switch between different payment strategies (credit
card, PayPal, cryptocurrency) depending on
customer preference.
24