Skip to content

Commit ff2855e

Browse files
SOLID Priciples, New example for Strategy Pattern
1 parent f52ff18 commit ff2855e

File tree

8 files changed

+191
-24
lines changed

8 files changed

+191
-24
lines changed

content/Strategy Pattern.md

Lines changed: 62 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
#behavioral
22
## Definition
33

4-
It Defines a family of algorithms encapsulates each one, and makes them interchangeable. Strategy Lets the algorithms vary independently from clients that use it.
4+
It defines a family of algorithms, encapsulates each one, and makes them interchangeable. The **Strategy Pattern** allows algorithms to vary independently from the clients that use them.
55

66
---
77
## Real World Analogy - 1
88

9-
Consider creating a Duck application with different types of ducks that can quack and fly. A simple approach would be to create a base class called `Duck` with methods like `fly` and `quack`, and then implement these methods in the specific types of ducks.
9+
Consider creating a **Duck** application with different types of ducks that can quack and fly. A simple approach would be to create a base class called `Duck` with methods like `fly()` and `quack()`, then implement these methods in specific duck types.
1010

1111
```mermaid
1212
---
@@ -31,7 +31,9 @@ classDiagram
3131
```
3232

3333
> [!Question] What is Wrong With These Approach ?
34-
> You have implemented a base class called `Duck`, where methods like `fly` and `quack` are already defined. For example, the base class `Duck` has a default implementation of flying. However, in the case of a `RubberDuck` class, the duck cannot quack or fly. To modify this behavior, you would need to rewrite the `fly` and `quack` methods, which becomes inefficient when dealing with dozens of duck types. To address this issue, you can use the **Strategy Pattern**.
34+
> You have implemented a base class called `Duck`, where methods like `fly()` and `quack()` are already defined. For example, the base class `Duck` has a default implementation of flying. However, in the case of a `RubberDuck` class, the duck **cannot** quack or fly.
35+
>
36+
>To modify this behavior, you would need to override the `fly()` and `quack()` methods, which becomes inefficient when dealing with dozens of duck types. To address this issue, you can use the **Strategy Pattern**.
3537
3638
Let's see the Implementation via Strategy Pattern:
3739
```mermaid
@@ -93,10 +95,16 @@ classDiagram
9395
Duck <|-- MallardDuck
9496
Duck <|-- RubberDuck
9597
```
96-
Here, we create two interfaces: `FlyBehavior` and `QuackBehavior`, which define the methods for flying and quacking. By implementing these interfaces, you can create new behaviors. In the abstract base class `Duck`, you use these interfaces in the constructor, allowing you to change the behavior dynamically or even implement a new duck type by passing specific behaviors or custom behaviors.
98+
Here, we create two interfaces:
99+
- `FlyBehavior`, which defines different flying behaviors.
100+
- `QuackBehavior`, which defines different quacking behaviors.
101+
102+
By implementing these interfaces, you can create new behaviors independently. The **abstract base class `Duck`** uses these interfaces in the constructor, allowing you to dynamically change behaviors or even create a new duck type by passing specific or custom behaviors.
103+
104+
Now, instead of modifying the base `Duck` class for every new type, you can simply create new behavior implementations and **plug them in**—making the system more flexible and scalable!
97105

98106
---
99-
## Code in Java
107+
### Code in Java
100108

101109
Below is the Code for the above Strategy Pattern we discussed over Here.
102110
```java
@@ -207,4 +215,52 @@ public class Index {
207215
---
208216
## Real World Analogy - 2
209217

210-
Let's take the another Example of the Logging Framework.
218+
Let's take another example: the **Logging Framework**.
219+
220+
This type of pattern is commonly used in logging frameworks, where you only pass the **Logger Interface** and call the `log()` method. The rest is handled by the class that implements the interface.
221+
222+
Suppose an application uses an `ILogger` interface, which declares methods like `LogInfo()`, `LogError()`, and `LogDebug()`. The logger can have multiple implementations, such as `ConsoleLogger`, `FileLogger`, `JsonLogger`, or `DBLogger`.
223+
224+
Using this approach, there is **no need to modify** all the methods in the application when changing the type of logger. You only need to **switch to a new logger** by defining it in the configuration section, while the rest is managed by the respective logging class.
225+
226+
Below is the **class diagram** illustrating this approach.
227+
```mermaid
228+
---
229+
title: Logger Framework Design
230+
---
231+
232+
classDiagram
233+
class ILogger{
234+
<<interface>>
235+
+LogInf() void
236+
+LogError() void
237+
+LogWarning() void
238+
+LogDubug() void
239+
}
240+
241+
class FileLogger{
242+
+LogInf() void
243+
+LogError() void
244+
+LogWarning() void
245+
+LogDubug() void
246+
}
247+
248+
class ConsoleLogger{
249+
+LogInf() void
250+
+LogError() void
251+
+LogWarning() void
252+
+LogDubug() void
253+
}
254+
255+
ILogger <|-- FileLogger
256+
ILogger <|-- ConsoleLogger
257+
258+
class Application{
259+
-logger ILogger
260+
+PerformOperation() void
261+
+KillProcess() void
262+
}
263+
264+
265+
```
266+
---

content/index.md

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ title: Design Patterns
44
### What is Design Pattern ?
55

66
**Design patterns** are typical solutions to commonly occurring problems in software design. They are like pre-made blueprints that you can customize to solve a recurring design problem in your code.
7-
87
## Three Main Patterns
98

109
- **Creational patterns** provide object creation mechanisms that increase flexibility and reuse of existing code.
@@ -81,9 +80,38 @@ class MessageService {
8180
Now, you can add as many providers as needed, and `MessageService` will continue to work without being tightly coupled to `EmailClient`.
8281

8382
---
84-
## SOLID Principle
85-
86-
83+
## ## SOLID Principles
84+
85+
The **SOLID** principles are five key object-oriented design principles that should be followed when creating a class structure. Let’s go through each principle one by one:
86+
### 1. Single Responsibility Principle (SRP)
87+
This principle states that a class should have only one responsibility and, therefore, only one reason to change.
88+
89+
**Example:**
90+
Consider a `Book` class that contains all the methods and variables related to a book. You should not include code related to a `Student` class or methods that are not relevant to the `Book` class.
91+
### 2. Open-Closed Principle (OCP)
92+
This principle states that a class should be **open for extension but closed for modification**. Modification refers to changing the code of an existing class, while extension means adding new functionality without altering the existing code.
93+
94+
**Example:**
95+
If you have a well-tested and reliable class, modifying its code can introduce bugs and potential system crashes. Instead, you should extend the functionality using **abstract classes** or **interfaces** rather than modifying the tested code directly.
96+
### 3. Liskov Substitution Principle (LSP)
97+
This principle states that **subtypes of a base class must be substitutable without altering the correctness of the program**.
98+
99+
**Example:**
100+
Consider an abstract or base class `Shape` with a method to calculate the area. If you create a `Rectangle` class by inheriting from `Shape`, calling the area calculation method on a `Rectangle` object (using a `Shape` reference) should return the expected result without requiring changes to the base class.
101+
### 4. Interface Segregation Principle (ISP)
102+
This principle states that **a class should not be forced to implement interfaces it does not use**. It is better to have multiple **smaller, specific interfaces** rather than a large, general-purpose interface.
103+
104+
**Example:**
105+
Consider a `Programmer` class with methods like `work()`, `eat()`, `test()`, and `assign()`, all declared in an `IEmployee` interface. The problem arises when you introduce `Manager` and `TeamLead` classes—they require the `assign()` method, but it doesn't belong in the `Programmer` class. To fix this, you can **segregate** the interfaces:
106+
- Common employee methods go in the `IEmployee` interface.
107+
- Management-related methods go in an `IManage` interface.
108+
109+
This way, only relevant methods are implemented by each class.
110+
### 5. Dependency Inversion Principle (DIP)
111+
This principle states that **high-level modules should not depend on low-level modules; instead, both should depend on abstractions (interfaces or abstract classes)**.
112+
113+
**Example:**
114+
Consider an `SQLManager` class that performs CRUD operations. It has an `ILogger` interface for logging, which allows you to use different loggers like `FileLogger`, `ConsoleLogger`, or `TableLogger`. Since the `SQLManager` depends on the abstraction (`ILogger`) rather than a specific logging implementation, you can switch loggers without breaking the system.
87115

88116
---
89117
## Contents:

public/Strategy-Pattern.html

Lines changed: 58 additions & 8 deletions
Large diffs are not rendered by default.

public/index.html

Lines changed: 29 additions & 3 deletions
Large diffs are not rendered by default.

public/index.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
<title>Strategy Pattern</title>
2222
<link>https://https://prathameshdhande22.github.io/Java-Tutorial/Strategy-Pattern</link>
2323
<guid>https://https://prathameshdhande22.github.io/Java-Tutorial/Strategy-Pattern</guid>
24-
<description>behavioral Definition It Defines a family of algorithms encapsulates each one, and makes them interchangeable. Strategy Lets the algorithms vary independently from clients that use it.</description>
24+
<description>behavioral Definition It defines a family of algorithms, encapsulates each one, and makes them interchangeable. The Strategy Pattern allows algorithms to vary independently from the clients that use them.</description>
2525
<pubDate>Tue, 14 Jan 2025 18:41:56 GMT</pubDate>
2626
</item><item>
2727
<title>Design Patterns</title>

public/static/contentIndex.json

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

public/tags.html

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<!DOCTYPE html>
2+
<html lang="en"><head><title>Tag: </title><meta charset="utf-8"/><link rel="preconnect" href="https://fonts.googleapis.com"/><link rel="preconnect" href="https://fonts.gstatic.com"/><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM Plex Mono&amp;family=Schibsted Grotesk:wght@400;700&amp;family=Source Sans Pro:ital,wght@0,400;0,600;1,400;1,600&amp;display=swap"/><link rel="preconnect" href="https://cdnjs.cloudflare.com" crossorigin="anonymous"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><meta name="og:site_name" content="🛠️ Design Patterns"/><meta property="og:title" content="Tag: "/><meta property="og:type" content="website"/><meta name="twitter:card" content="summary_large_image"/><meta name="twitter:title" content="Tag: "/><meta name="twitter:description" content="No description provided"/><meta property="og:description" content="No description provided"/><meta property="og:image:type" content="image/webp"/><meta property="og:image:alt" content="No description provided"/><meta property="og:image:width" content="1200"/><meta property="og:image:height" content="630"/><meta property="og:image:url" content="https://https://prathameshdhande22.github.io/Java-Tutorial//static/og-image.png"/><meta name="twitter:image" content="https://https://prathameshdhande22.github.io/Java-Tutorial//static/og-image.png"/><meta property="og:image" content="https://https://prathameshdhande22.github.io/Java-Tutorial//static/og-image.png"/><meta property="twitter:domain" content="https://prathameshdhande22.github.io/Java-Tutorial/"/><meta property="og:url" content="https://https//prathameshdhande22.github.io/Java-Tutorial/tags"/><meta property="twitter:url" content="https://https//prathameshdhande22.github.io/Java-Tutorial/tags"/><link rel="icon" href="./static/icon.png"/><meta name="description" content="No description provided"/><meta name="generator" content="Quartz"/><link href="./index.css" rel="stylesheet" type="text/css" spa-preserve/><link href="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css" rel="stylesheet" type="text/css" spa-preserve/><script src="./prescript.js" type="application/javascript" spa-preserve></script><script type="application/javascript" spa-preserve>const fetchData = fetch("./static/contentIndex.json").then(data => data.json())</script></head><body data-slug="tags"><div id="quartz-root" class="page"><div id="quartz-body"><div class="left sidebar"><h2 class="page-title"><a href=".">🛠️ Design Patterns</a></h2><div class="spacer mobile-only"></div><div class="search"><button class="search-button" id="search-button"><p>Search</p><svg role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 19.9 19.7"><title>Search</title><g class="search-path" fill="none"><path stroke-linecap="square" d="M18.5 18.3l-5.4-5.4"></path><circle cx="8" cy="8" r="7"></circle></g></svg></button><div id="search-container"><div id="search-space"><input autocomplete="off" id="search-bar" name="search" type="text" aria-label="Search for something" placeholder="Search for something"/><div id="search-layout" data-preview="true"></div></div></div></div><button class="darkmode" id="darkmode"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="dayIcon" x="0px" y="0px" viewBox="0 0 35 35" style="enable-background:new 0 0 35 35" xml:space="preserve" aria-label="Dark mode"><title>Dark mode</title><path d="M6,17.5C6,16.672,5.328,16,4.5,16h-3C0.672,16,0,16.672,0,17.5 S0.672,19,1.5,19h3C5.328,19,6,18.328,6,17.5z M7.5,26c-0.414,0-0.789,0.168-1.061,0.439l-2,2C4.168,28.711,4,29.086,4,29.5 C4,30.328,4.671,31,5.5,31c0.414,0,0.789-0.168,1.06-0.44l2-2C8.832,28.289,9,27.914,9,27.5C9,26.672,8.329,26,7.5,26z M17.5,6 C18.329,6,19,5.328,19,4.5v-3C19,0.672,18.329,0,17.5,0S16,0.672,16,1.5v3C16,5.328,16.671,6,17.5,6z M27.5,9 c0.414,0,0.789-0.168,1.06-0.439l2-2C30.832,6.289,31,5.914,31,5.5C31,4.672,30.329,4,29.5,4c-0.414,0-0.789,0.168-1.061,0.44 l-2,2C26.168,6.711,26,7.086,26,7.5C26,8.328,26.671,9,27.5,9z M6.439,8.561C6.711,8.832,7.086,9,7.5,9C8.328,9,9,8.328,9,7.5 c0-0.414-0.168-0.789-0.439-1.061l-2-2C6.289,4.168,5.914,4,5.5,4C4.672,4,4,4.672,4,5.5c0,0.414,0.168,0.789,0.439,1.06 L6.439,8.561z M33.5,16h-3c-0.828,0-1.5,0.672-1.5,1.5s0.672,1.5,1.5,1.5h3c0.828,0,1.5-0.672,1.5-1.5S34.328,16,33.5,16z M28.561,26.439C28.289,26.168,27.914,26,27.5,26c-0.828,0-1.5,0.672-1.5,1.5c0,0.414,0.168,0.789,0.439,1.06l2,2 C28.711,30.832,29.086,31,29.5,31c0.828,0,1.5-0.672,1.5-1.5c0-0.414-0.168-0.789-0.439-1.061L28.561,26.439z M17.5,29 c-0.829,0-1.5,0.672-1.5,1.5v3c0,0.828,0.671,1.5,1.5,1.5s1.5-0.672,1.5-1.5v-3C19,29.672,18.329,29,17.5,29z M17.5,7 C11.71,7,7,11.71,7,17.5S11.71,28,17.5,28S28,23.29,28,17.5S23.29,7,17.5,7z M17.5,25c-4.136,0-7.5-3.364-7.5-7.5 c0-4.136,3.364-7.5,7.5-7.5c4.136,0,7.5,3.364,7.5,7.5C25,21.636,21.636,25,17.5,25z"></path></svg><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="nightIcon" x="0px" y="0px" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100" xml:space="preserve" aria-label="Light mode"><title>Light mode</title><path d="M96.76,66.458c-0.853-0.852-2.15-1.064-3.23-0.534c-6.063,2.991-12.858,4.571-19.655,4.571 C62.022,70.495,50.88,65.88,42.5,57.5C29.043,44.043,25.658,23.536,34.076,6.47c0.532-1.08,0.318-2.379-0.534-3.23 c-0.851-0.852-2.15-1.064-3.23-0.534c-4.918,2.427-9.375,5.619-13.246,9.491c-9.447,9.447-14.65,22.008-14.65,35.369 c0,13.36,5.203,25.921,14.65,35.368s22.008,14.65,35.368,14.65c13.361,0,25.921-5.203,35.369-14.65 c3.872-3.871,7.064-8.328,9.491-13.246C97.826,68.608,97.611,67.309,96.76,66.458z"></path></svg></button><div class="explorer desktop-only"><button type="button" id="explorer" data-behavior="collapse" data-collapsed="collapsed" data-savestate="true" data-tree="[]" aria-controls="explorer-content" aria-expanded="false"><h2>Explorer</h2><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="5 8 14 8" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="fold"><polyline points="6 9 12 15 18 9"></polyline></svg></button><div id="explorer-content"><ul class="overflow" id="explorer-ul"><li><div class="folder-outer open"><ul style="padding-left:0;" class="content" data-folderul><li><div class="folder-outer "><ul style="padding-left:0;" class="content" data-folderul></ul></div></li><li><a href="./Decorator-Pattern" data-for="Decorator-Pattern">Decorator Pattern</a></li><li><a href="./Observer-Pattern" data-for="Observer-Pattern">Observer Pattern</a></li><li><a href="./Strategy-Pattern" data-for="Strategy-Pattern">Strategy Pattern</a></li></ul></div></li><li id="explorer-end"></li></ul></div></div></div><div class="center"><div class="page-header"><div class="popover-hint"><nav class="breadcrumb-container" aria-label="breadcrumbs"><div class="breadcrumb-element"><a href="./">Home</a><p></p></div><div class="breadcrumb-element"><a href>Tag: </a></div></nav><h1 class="article-title">Tag: </h1></div></div><div class="popover-hint"><article class><p></p></article><p>Found 2 total tags.</p><div><div><h2><a class="internal tag-link" href="../tags/"></a></h2><div class="page-listing"><p>1 item with this tag.</p><ul class="section-ul"><li class="section-li"><div class="section"><p class="meta"><time datetime="2025-01-14T18:41:56.563Z">Jan 15, 2025</time></p><div class="desc"><h3><a href="./" class="internal">Design Patterns</a></h3></div><ul class="tags"><li><a class="internal tag-link" href="./tags/"></a></li></ul></div></li></ul></div></div><div><h2><a class="internal tag-link" href="../tags/behavioral">behavioral</a></h2><div class="page-listing"><p>1 item with this tag.</p><ul class="section-ul"><li class="section-li"><div class="section"><p class="meta"><time datetime="2025-01-14T18:41:56.563Z">Jan 15, 2025</time></p><div class="desc"><h3><a href="./Strategy-Pattern" class="internal">Strategy Pattern</a></h3></div><ul class="tags"><li><a class="internal tag-link" href="./tags/behavioral">behavioral</a></li></ul></div></li></ul></div></div></div></div><hr/><div class="page-footer"></div></div><div class="right sidebar"></div><footer class><p style="text-align:center;">Created with ❤️ by Prathamesh Dhande</p><ul style="text-align:center;"><li><a href="https://prathameshdhande22.github.io/Java-Tutorial/">GitHub</a></li><li><a href="https://www.linkedin.com/in/prathamesh-dhande-3a039721a/">LinkedIn</a></li></ul><div style="text-align: center; padding: 20px; font-family: Arial, sans-serif;"><p style="color: #007acc; font-size: 16px; margin: 5px;">Written on <a href="https://obsidian.md" target="_blank" style="color: #00bfff; text-decoration: none;">Obsidian</a></p><p style="color: #ff9800; font-size: 16px; margin: 5px;">Powered by <a href="https://github.com/jackyzha0/quartz" target="_blank" style="color: #ffcc33; text-decoration: none;">Quartz</a></p><p style="color: #4caf50; font-size: 16px; margin: 5px;">Hosted on <a href="https://pages.github.com/" target="_blank" style="color: #66bb6a; text-decoration: none;">GitHub Pages</a></p></div></footer></div></div></body><script type="application/javascript">function c(){let t=this.parentElement;t.classList.toggle("is-collapsed");let l=t.classList.contains("is-collapsed")?this.scrollHeight:t.scrollHeight;t.style.maxHeight=l+"px";let o=t,e=t.parentElement;for(;e;){if(!e.classList.contains("callout"))return;let n=e.classList.contains("is-collapsed")?e.scrollHeight:e.scrollHeight+o.scrollHeight;e.style.maxHeight=n+"px",o=e,e=e.parentElement}}function i(){let t=document.getElementsByClassName("callout is-collapsible");for(let s of t){let l=s.firstElementChild;if(l){l.addEventListener("click",c),window.addCleanup(()=>l.removeEventListener("click",c));let e=s.classList.contains("is-collapsed")?l.scrollHeight:s.scrollHeight;s.style.maxHeight=e+"px"}}}document.addEventListener("nav",i);window.addEventListener("resize",i);
3+
</script><script src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/copy-tex.min.js" type="application/javascript"></script><script type="application/javascript">
4+
const socket = new WebSocket('ws://localhost:3001')
5+
// reload(true) ensures resources like images and scripts are fetched again in firefox
6+
socket.addEventListener('message', () => document.location.reload(true))
7+
</script><script src="./postscript.js" type="module"></script></html>

0 commit comments

Comments
 (0)