Lec12 Pattern design (1)
Lec12 Pattern design (1)
Bridge, Observer,
Façade Strategy,
Template method,
Iterator
Singleton
Singleton
static uniqueInstance
data //Instance()
return uniqueInstance;
static Instance()
operation()
getData()
2
reference
s to
Singleton
object
Private Constructor
Prevents a class from being subclassed
Prevents the creation of an object outside the class
If all the methods are static, then a private constructor
can be used
If we try to extend a class that has a private
constructor, a compile-time error will occur
Use case: it’s useful when the system needs to determine which
class to instantiate at runtime, based on different conditions or
input
12/06/2024 Design patterns Page 12
1. Creational
It is used when there are multiple related products, and the system
needs to remain decoupled from their concrete implementations
Factory method Abstract factory
Use when the focus on creating Use when you need to create a group of related
one specific product objects with different implementation
system
Adapter
Composite
Decorator
Adapter pattern
Helps objects with incompatible interfaces collaborate by
acting as a bridge between them
Composite pattern
Provides a way to organize and manipulate objects in a
hierarchical structure
It’s useful when the structure contains objects from
manipulate classes (e.g., a directory containing both files
and subdirectories)
Components
The abstraction for all objects in the structure
Composite pattern
Leaf
Represents individual objects in the hierarchy that don’t have children
Implements all methods defined in the Component interface
E.g., File
Composite
Represents composite objects that can have children (other
components)
Implements methods to add, remove, and manipulate children, as well
as Component methods
E.g., Directory
Composite
Component interface Leaf class
Decorator
Is a structural design pattern that allows you to dynamically add
new functionality to an object without altering its structure or
modifying its code
Key concepts
Decorator class: wraps the core component and adds extra behavior
or responsibilities while still conforming to the same interface
Decorator
How it works?
Both core component and decorator implement a shared
interface or inherit from the same base class
The decorator class contains a reference to the core
component and delegates method calls to it, adding additional
behavior either before or after the delegation
Decorator
Key concepts