0% found this document useful (0 votes)
4 views45 pages

5 Lecture 2 Patterns - UPDATED

This document discusses design patterns in object-oriented programming (OOP), focusing on their importance in software design, particularly in banking systems. It covers concepts like cohesion, coupling, and the Model-View-Controller (MVC) architecture, along with various design patterns such as Singleton, Adapter, and Strategy patterns. The document emphasizes the benefits of using design patterns for creating maintainable, scalable, and efficient software solutions.

Uploaded by

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

5 Lecture 2 Patterns - UPDATED

This document discusses design patterns in object-oriented programming (OOP), focusing on their importance in software design, particularly in banking systems. It covers concepts like cohesion, coupling, and the Model-View-Controller (MVC) architecture, along with various design patterns such as Singleton, Adapter, and Strategy patterns. The document emphasizes the benefits of using design patterns for creating maintainable, scalable, and efficient software solutions.

Uploaded by

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

Design Patterns

in OOP
(GoF, Model-View-Controller)
Learning Objectives
By the end of this lecture, you will be able to:
❑Design Patterns, in banking system

❑Model-View-Controller

❑Understand why patterns are important


Summary from previous lecture
Cohesion:
Refers to how related and focused the responsibilities of a class or module are.

➢ Low Cohesion: Class handles unrelated functionalities, leading to maintenance challenges. (Bad design)

➢ High Cohesion: Class has focused single responsibilities, improving clarity and ease of maintenance. (Good Design)

Example in Banking System:


•Low Cohesion: AccountManager class responsible for both account creation and transaction history management. (Bad design)

•High Cohesion: Account class responsible for just account-related functionalities like deposits and withdrawals. (Good Design)
What is Coupling?
• Coupling is how much one class/module knows about another.

• Its degree of interdependence between software modules.

• Higher the coupling, the harder it is to change one class without affecting another.

• Lower the coupling better would the design.

Uncoupled: No dependencies Loosely coupled: Some dependencies Highly coupled: Many dependencies
Software Design, Tactics and Design Patterns in OOP
It is a conceptual, structural, logical organization of a computer-based system.

Software design:
▪ Planning, process of defining or guidelines to produce high quality products.

▪ Address quality attributes.

Tactics:
◦ Use single mechanism, or structure.

◦ Address single architecture force.

◦ Used to make design patterns, also address quality attributes.

Design Patterns:
➢ Reusable solution: recurring solutions to common problems in a given context in OOP.

➢ Description.

➢ Template.
Software design
• Defining the architecture, components/interfaces/characteristics of a system/component.

• Structured solution to meet all requirements.

• Objective is to optimizing common quality attributes.

1. High-Level Design (Architectural Design): Focuses on how the system, components, and modules
interact with each other. It defines system architecture, data flow, and protocols.

2. Low-Level Design (Detailed Design): Focuses on the internal structure of individual components. It
includes detailed algorithms, data structures, and coding standards.

Example: In a high-level design for an Banking application, you might define modules like user
management, account management, notifications , and payment gateway. Each module's interactions
and data flow are defined at this stage.
Software tactics
• Low-level strategies, ensure the system's architecture follow certain quality attributes.

• To achieve specific quality attributes (like performance, security, maintainability) in a software design.

Examples of Software Tactics:


o Performance Tactics: Caching data, load balancing, and using efficient algorithms.
o Security Tactics: Input validation, authentication, and encryption.
o Availability Tactics: Redundancy, failover, and replication.

E.g: To improve the performance of a online Banking application,

Caching tactic can be implemented

Frequently accessed data is stored in memory for quicker retrieval.


Design Patterns in OOPs
• It provides general, reusable solutions to common problems in software design in OOP.
he term

• Gang of Four" (GoF) design patterns comes from the book titled "Design Patterns: Elements of Reusable
Object-Oriented Software" written by four authors in 1994, 23 DPs:

Erich Gamma
Richard Helm
Ralph Johnson
John Vlissides

• They are best practices that the developer can use to solve common problems while designing a software
application or system.

• They are more about templates to solve certain design problems in a particular context.
Software Patterns Design Patterns in OOP Software Tactics

Reusable solutions for specific


General reusable solutions for design problems (OOP) within Techniques for achieving specific
Definition
common problems. software architecture. quality attributes.
Architectural solutions/templates.

Focused on specific quality


Broad (includes S/W architectural Narrow, focusing on specific design
Scope attributes like performance,
and design patterns). issues.
security, etc.

Applies to both architecture and Applied during the detailed design Applied at a tactical level to
Application
design levels. phase. achieve quality goals.

MVC, Layered Architecture, Singleton, Observer, Factory, Caching, load balancing,


Examples
Microservices. Builder. Model-View-Contoller authentication.

High-level patterns for architecture Focuses on specific design Focuses on achieving desired
Focus
and system design. problems. quality attributes.
Why are these Important?
• Making them easier to maintain, understand, and scale (S/W Pattern).

• Help solve recurring problems and improve communication among developers by providing a shared
vocabulary (DP).

• Help to achieve desired qualities in a system (e.g., performance, security) and address specific concerns
efficiently(S/W Tactics).

Use These Concepts For:


✓ Designing robust, scalable, and maintainable software.
✓ Addressing common challenges in software development.
✓ Improving the quality and performance of software systems.
✓ Reducing the time and cost of development by reusing proven solutions.
Motivation– Why Do We Need?

• Imagine you're in a bank.


• The clerk listens to your request.
• Your account contains and manages your money.
• The receipt/screen shows your transaction status.

Note: You don’t directly manipulate your account — the clerk


handles your request, updates the account, and shows you a
result.
Motivation (MVC)– Why Do We Need? Cont..
account

Component Role
Model Handles data and business
rules (e.g., Account)
View Displays data to the user (e.g.,
Balance screen)
Screen/receipt clerk Controller Manages user input and
updates Model/View

o The clerk (Controller) listens to your request.


o Your account (Model) contains and manages your money.
o The receipt or screen (View) shows your transaction status.
Motivation– Why Do We Need? Cont..
account

Component Role
Model Handles data and business
rules (e.g., Account)
View Displays data to the user (e.g.,
Balance screen)
Screen/receipt clerk Controller Manages user input and
updates Model/View

o The clerk (Controller) listens to your request.


o Your account (Model) contains and manages your money.
o The receipt or screen (View) shows your transaction status.
Motivation– Why Do We Need? Cont..
account

Component Role
Model Handles data and business
rules (e.g., Account)
View Displays data to the user (e.g.,
Balance screen)
Screen/receipt clerk Controller Manages user input and
updates Model/View

o The clerk (Controller) listens to your request.


o Your account (Model) contains and manages your money.
o The receipt or screen (View) shows your transaction status.
Motivation– Why Do We Need? Cont..
account

Component Role
Model Handles data and business
rules (e.g., Account)
View Displays data to the user (e.g.,
Balance screen)
Screen/receipt clerk Controller Manages user input and
updates Model/View

o The clerk (Controller) listens to your request.


o Your account (Model) contains and manages your money.
o The receipt or screen (View) shows your transaction status.
Motivation– Why Do We Need? Cont..
account

Screen/receipt clerk

User Controller Model View User


Model (account) for Banking
System
• Model class defines data and business logic

Data

Business
logic-1
Business
logic-2

Model – Account.java
View (Screen/receipt) for Banking System
• The View class handles all display/output logic

Display logic

View- AccountView.java
Controller (clerk) for Banking System
• The Controller class is middle-man of Model and View

• It uses methods/functions/data of both Model and View

Model logic
View logic
Object of both
Model and View

Controller- AccountController.java
MVC concept
Banking App:
•Different views for customer and admin.

•REST API Controller instead of Command-Line Interface (CLI).

•Model connects to a database (JDBC)

•Multiple controllers (LoginController, TransactionController).

Testability:
❑ Model tested easily.
❑ Controllers tested for user actions.
MVC concept
•It was introduced in Smalltalk in the 1970s

•But became popular in modern UI frameworks and web development (e.g., Java
Swing,Django).

•MVC is not a framework —it's a design pattern. Frameworks (pre-built collection of tools,
libraries) implement it.

Extensions:
▪ MVVM (Model-View-ViewModel): Used in Android.

▪ MVP (Model-View-Presenter): Used in older Android and Swing apps.


Quick Question (1 min) (more than 1 correct)
Which of the following are true about the Controller in the MVC design pattern?

A. It manipulates the Model based on user input


B. It formats the data to be displayed in the View
C. It can directly modify the View without involving the Model
D. It helps decouple the View from the Model

Explanation:
A: Correct – The Controller handles user actions (like button clicks), and based on that, modifies the Model.
B: Incorrect – Formatting data is generally the View’s responsibility.
C: Incorrect – While the Controller can trigger updates to the View indirectly, it should not directly modify it.
D: Correct – The Controller acts as an intermediary, helping to decouple the View from the Model.

Correct Answers: A and D


Types of Object-Oriented Design Patterns cont..

https://onurdesk.com/why-we-need-design-patterns-in-3-category/

1. Creational patterns deal with object creation logic, hiding complexities and making code more flexible.

2. Structural patterns help build relationships between different parts of the system.

3. Behavioral patterns focus on communication and responsibility delegation between objects.


Types of Object-Oriented Design Patterns
Type Purpose Real-world Analogy Banking Example

Creational How objects are created Factory Producing object Creating a single config object

Structural How classes/objects are Adapters/converters in Using 3rd-party loan API


compose or organized hardware

Behavioral How objects Interchangeable


communicate roles/strategies Different interest strategies
Types of Object-Oriented Design Patterns
Type Purpose Real-world Analogy Banking Example

Creational How objects are created Factory Producing object Creating a single config object

Structural How classes/objects are Adapters/converters in Using 3rd-party loan API


compose or organized hardware

Behavioral How objects Interchangeable


communicate roles/strategies Different interest strategies
Types of Object-Oriented Design Patterns
Type Purpose Real-world Analogy Banking Example

Creational How objects are created Factory Producing object Creating a single config object

Structural How classes/objects are Adapters/converters in Using 3rd-party loan API


compose or organized hardware

Behavioral How objects Interchangeable


communicate roles/strategies Different interest strategies
Types of Object-Oriented Design Patterns
Type Purpose Real-world Analogy Banking Example

Creational How objects are created Factory Producing object Creating a single config object

Structural How classes/objects are Adapters/converters in Using 3rd-party loan API


compose or organized hardware

Behavioral How objects Interchangeable


communicate roles/strategies Different interest strategies
Pattern 1: Singleton (Creational DP)
• It ensure a class has only one instance and provides a global point of access to it.

• We want only one object (instance) of a class.

• To achieve this, we store that single instance in a static variable, so it can be shared globally and
accessed without creating new objects.

• E.g interest rate, max withdrawal limit.


Singleton Example:
Interest Rate and Max
Withdrawal Limit
• Want only one object, i.e., stored in a static
variable.

• Only this class access these variables,


and variables are used to store
globally.

• Private constructor to prevent outside


instantiation.
• Public method for single object is created
only when needed.

• But we still need to access and sometimes update


the global values inside an object.
Singleton DP
Benefit
• Global access point
• Controlled instantiation
• Consistent State
• Lazy initiliasation

Limitation
• Tightly coupled code
• Concurrency issues
Quick Question (1 min) (more than 1 correct)
Which of the following are characteristics or consequences of using the Singleton pattern?
A. Ensures a class has only one instance
B. Increases testability due to easy mocking
C. Provides global access to the instance
D. May introduce hidden dependencies and global state

Explanation:
A: Correct – Singleton restricts instantiation to only one object.
B: Incorrect – In fact, Singleton decreases testability because it is difficult to replace with a mock or
stub.
C: Correct – Singleton provides a globally accessible instance via a static method.
D: Correct – This global access can lead to hidden dependencies and tight coupling, harming
testability and maintainability.
Correct Answers: A, C, and D
Structural Pattern – Adapter Pattern
(How classes/objects are organized)
• Sometimes we want to use an existing class, but its interface doesn’t
match.

• Instead of changing the original code (which may be 3rd-party or legacy),


we create an adapter class to compatible.

• It allows objects with incompatible interfaces to work together by acting


as a bridge between them.

• Also know as Wrapper.

• E.g: You have a European charger but a US socket.


Adapter Pattern
• Situation: “Let’s say our banking app wants to integrate a third-party
customer verification system, but its interface doesn’t match ours.”

Our System’s Interface: Old system(Incompatible Interface)


Adapter Pattern
• Adapter class implements our interface

• Contructor store the object of old interface

• Now method is overidden by our new


method from legacy interface.
Adapter Pattern

Usage in the banking system


Adapter Pattern
Benefits
➢Allows code reuse of incompatible classes
➢Promotes decoupling between systems
➢Helps in system integration/scale

Limitations
•Adds a layer of indirection (more classes)
•Can become complex if too many adapters are needed.
Quick Question (1 min) (more than 1 correct)
Which of the following statements about the Adapter Design Pattern are correct?
A. The Adapter pattern allows incompatible interfaces to work together
B. The Adapter modifies the legacy system's source code to match the new interface.
C. The Adapter implements the expected interface and internally calls the legacy methods.
D. Adapter pattern can only be used if the legacy system implements the new interface.

Explanation:
A) Correct. This is the fundamental purpose of the Adapter pattern.
B) Incorrect. The Adapter does not modify legacy code; it wraps it.
C) Correct. The Adapter class implements the new interface and delegates calls to the legacy system.
D) Incorrect. The legacy system need not always implement the new interface.

Correct answer: A, C
Behavioral Pattern – Strategy Pattern
(How objects communicate)
Scenario: Imagine a bank app that can calculate interest differently for different account types — say:
• SavingsAccount
• CurrentAccount
• FixedDepositAccount

• No need of hardcoding.

• This DP helps us extract that into separate strategy classes.

• This DP allows you to define a family of algorithms.

• You can keep them in a separate class.

• And make their objects interchangeable.

• It lets the algorithm vary independently from the clients that use it.
Strategy Pattern (context, interface,
strategies)
Structure:
1. Context: The class that uses a strategy (e.g., BankAccount).

2. Strategy Interface: Common interface for all algorithms (e.g., InterestCalculator).

3. Concrete Strategies: Different implementations (e.g., SavingsInterest, FixedDepositInterest).


Strategy Pattern
Concrete Strategy 1

Strategy Interface

Concrete Strategy 2
Strategy Pattern cont..

Context Class (use strategy)

Main Class
Strategy Pattern cont..
Benefits
❑Add new strategies without changing existing code.

❑Avoids conditionals: Clean design without if-else or switch.

❑Flexible: Change behavior at runtime.

Drawbacks
• More classes.
• May add slight overhead due to indirection.
Quick Question (1 min) (more than 1 correct)
Which of the following are advantages of using the Strategy design pattern?
A. It eliminates the need for inheritance by using composition
B. It allows algorithms to be selected at runtime
C. It tightly couples the context class with specific strategies
D. It promotes the adding new strategies with modifying others.

Explanation:
A: Correct – Strategy promotes composition over inheritance, enabling behavior change
without subclassing.
B: Correct – Different strategies (algorithms) can be swapped at runtime.
C: Incorrect – Strategy reduces coupling by separating algorithms from the context class.
D: Correct – You can add new strategies without modifying existing ones.
Correct Answers: A, B, and D
Key Takeaways
• Use design patterns to solve common design problems cleanly.

• Design patterns promote reusability, testability, and readability.

• Practice makes patterns easier to spot and apply.

You might also like