Repository: keertipurswani/LLD-Design-Patterns
Branch: main
Commit: ef16e1e20456
Files: 97
Total size: 125.6 KB
Directory structure:
gitextract__e0g9rmv/
├── .gitignore
├── Abstract Factory Design Pattern/
│ ├── Furniture /
│ │ ├── C++/
│ │ │ ├── furniture
│ │ │ └── furniture.cpp
│ │ ├── JAVA/
│ │ │ └── furniture.java
│ │ ├── Javascript/
│ │ │ └── furniture.js
│ │ └── Python/
│ │ └── furniture.py
│ └── UI/
│ ├── C++/
│ │ ├── ui
│ │ └── ui.cpp
│ └── JAVA/
│ └── UI.java
├── Adapter Design Pattern/
│ ├── Class Adapter/
│ │ └── C++/
│ │ └── xml_to_json.cpp
│ └── Object Adapter/
│ ├── C++/
│ │ └── xml_to_json.cpp
│ └── JAVA/
│ └── XmlToJson.java
├── Bridge Design Pattern/
│ ├── C++/
│ │ └── uber.cpp
│ └── JAVA/
│ └── UberDemo.java
├── Builder Design Pattern/
│ ├── Builder with Chaining/
│ │ ├── C++/
│ │ │ ├── desktop
│ │ │ └── desktop.cpp
│ │ └── JAVA/
│ │ └── DesktopBuilderDemo.java
│ ├── C++/
│ │ ├── desktop
│ │ └── desktop.cpp
│ └── JAVA/
│ └── DesktopBuilderDemo.java
├── Chain of Responsibility Design Pattern/
│ ├── C++/
│ │ └── swiggy_order.cpp
│ └── JAVA/
│ └── SwiggyOrder.java
├── Command Design Pattern/
│ ├── C++/
│ │ ├── document.cpp
│ │ └── uber_rides.cpp
│ └── JAVA/
│ ├── DocumentDemo.java
│ └── UberRidesDemo.java
├── Composite Design Pattern/
│ ├── C++/
│ │ ├── directorystructure.cpp
│ │ └── employee.cpp
│ └── JAVA/
│ ├── EmployeesDemo.java
│ └── directorystructure.java
├── Decorator Design Pattern/
│ ├── C++/
│ │ └── swiggy.cpp
│ └── JAVA/
│ └── Swiggy.java
├── Facade Design Pattern/
│ ├── C++/
│ │ └── computer.cpp
│ └── JAVA/
│ └── ComputerDemo.java
├── Factory Method Design Pattern/
│ ├── Furniture/
│ │ ├── C++/
│ │ │ └── furniture.cpp
│ │ ├── JAVA/
│ │ │ └── furniture.java
│ │ ├── Javascript/
│ │ │ └── furniture.js
│ │ └── Python/
│ │ └── furniture.py
│ └── Logger/
│ ├── C++/
│ │ ├── common.hpp
│ │ ├── debug_logger.cpp
│ │ ├── debug_logger.hpp
│ │ ├── debug_logger_factory.hpp
│ │ ├── error_logger.cpp
│ │ ├── error_logger.hpp
│ │ ├── error_logger_factory.hpp
│ │ ├── furniture
│ │ ├── ilogger.hpp
│ │ ├── info_logger.cpp
│ │ ├── info_logger.hpp
│ │ ├── info_logger_factory.hpp
│ │ ├── logger
│ │ ├── logger_factory.hpp
│ │ └── main.cpp
│ └── JAVA/
│ └── LoggerDemo.java
├── Iterator Design Pattern/
│ ├── C++/
│ │ └── amazon_inventory.cpp
│ └── JAVA/
│ └── AmazonInventory.java
├── Observer Design Pattern/
│ ├── C++/
│ │ └── order_status.cpp
│ └── JAVA/
│ └── OrderStatus.java
├── Prototype Design Pattern/
│ ├── C++/
│ │ ├── product
│ │ ├── product.cpp
│ │ ├── router
│ │ └── router.cpp
│ └── JAVA/
│ ├── ProductDemo.java
│ └── RouterDemo.java
├── Proxy Design Pattern/
│ ├── C++/
│ │ └── image.cpp
│ └── JAVA/
│ └── ImageDemo.java
├── Simple Factory Design Pattern/
│ ├── C++/
│ │ ├── common.hpp
│ │ ├── debug_logger.cpp
│ │ ├── debug_logger.hpp
│ │ ├── error_logger.cpp
│ │ ├── error_logger.hpp
│ │ ├── furniture
│ │ ├── ilogger.hpp
│ │ ├── info_logger.cpp
│ │ ├── info_logger.hpp
│ │ ├── logger
│ │ ├── logger_factory.cpp
│ │ ├── logger_factory.hpp
│ │ └── main.cpp
│ └── JAVA/
│ ├── Main.java
│ └── logger/
│ ├── DebugLogger.java
│ ├── ErrorLogger.java
│ ├── ILogger.java
│ ├── InfoLogger.java
│ ├── LogLevel.java
│ └── LoggerFactory.java
├── Singleton Design Pattern/
│ ├── C++/
│ │ ├── payment_gateway.cpp
│ │ └── pg
│ └── JAVA/
│ └── PaymentGateway.java
├── State Design Pattern/
│ ├── C++/
│ │ └── state.cpp
│ └── JAVA/
│ └── StateDemo.java
├── Strategy Design Pattern/
│ ├── C++/
│ │ └── payment.cpp
│ └── JAVA/
│ └── PaymentDemo.java
├── Strategy and Factory Design Pattern/
│ ├── C++/
│ │ └── payment.cpp
│ └── JAVA/
│ └── PaymentDemo.java
└── Template Design Pattern/
├── C++/
│ └── amazon_order.cpp
└── JAVA/
└── AmazonOrderProcessor.java
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so
# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
# Logs and databases #
######################
*.log
*.sql
*.sqlite
# OS generated files #
######################
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
================================================
FILE: Abstract Factory Design Pattern/Furniture /C++/furniture.cpp
================================================
#include <iostream>
// Abstract Product: Sofa
class Sofa {
public:
virtual void sitOn() = 0;
};
// Abstract Product: Chair
class Chair {
public:
virtual void sitOn() = 0;
};
// Abstract Product: Table
class Table {
public:
virtual void place() = 0;
};
// Concrete Products: Modern Furniture Items
class ModernSofa : public Sofa {
public:
void sitOn() override {
std::cout << "Sitting on a Modern Sofa" << std::endl;
}
};
class ModernChair : public Chair {
public:
void sitOn() override {
std::cout << "Sitting on a Modern Chair" << std::endl;
}
};
class ModernTable : public Table {
public:
void place() override {
std::cout << "Placing items on a Modern Table" << std::endl;
}
};
// Concrete Products: Traditional Furniture Items
class TraditionalSofa : public Sofa {
public:
void sitOn() override {
std::cout << "Sitting on a Traditional Sofa" << std::endl;
}
};
class TraditionalChair : public Chair {
public:
void sitOn() override {
std::cout << "Sitting on a Traditional Chair" << std::endl;
}
};
class TraditionalTable : public Table {
public:
void place() override {
std::cout << "Placing items on a Traditional Table" << std::endl;
}
};
// Abstract Factory: Furniture Factory
class FurnitureFactory {
public:
virtual Sofa* createSofa() = 0;
virtual Chair* createChair() = 0;
virtual Table* createTable() = 0;
static FurnitureFactory* CreateFurnitureFactory(std::string type) {
if (type == "modern") {
return new ModernFurnitureFactory();
}
else if (type == "traditional") {
return new TraditionalFurnitureFactory();
}
else return nullptr;
}
};
// Concrete Factory: Modern Furniture Factory
class ModernFurnitureFactory : public FurnitureFactory {
public:
Sofa* createSofa() override {
return new ModernSofa();
}
Chair* createChair() override {
return new ModernChair();
}
Table* createTable() override {
return new ModernTable();
}
};
// Concrete Factory: Traditional Furniture Factory
class TraditionalFurnitureFactory : public FurnitureFactory {
public:
Sofa* createSofa() override {
return new TraditionalSofa();
}
Chair* createChair() override {
return new TraditionalChair();
}
Table* createTable() override {
return new TraditionalTable();
}
};
int main() {
FurnitureFactory* modernFactory = FurnitureFactory::CreateFurnitureFactory("modern");
//use the abstract factory to create factories
// Create Modern furniture items
Sofa* modernSofa = modernFactory->createSofa();
Chair* modernChair = modernFactory->createChair();
Table* modernTable = modernFactory->createTable();
// Use Modern furniture items
modernSofa->sitOn();
modernChair->sitOn();
modernTable->place();
// Clean up Modern Factory objects
delete modernFactory;
delete modernSofa;
delete modernChair;
delete modernTable;
// Create a Traditional Furniture Factory
FurnitureFactory* traditionalFactory = FurnitureFactory::CreateFurnitureFactory("traditional");
// FurnitureFactory* traditionalFactory = new TraditionalFurnitureFactory();
// Create Traditional furniture items
Sofa* traditionalSofa = traditionalFactory->createSofa();
Chair* traditionalChair = traditionalFactory->createChair();
Table* traditionalTable = traditionalFactory->createTable();
// Use Traditional furniture items
traditionalSofa->sitOn();
traditionalChair->sitOn();
traditionalTable->place();
// Clean up Traditional Factory objects
delete traditionalFactory;
delete traditionalSofa;
delete traditionalChair;
delete traditionalTable;
return 0;
}
================================================
FILE: Abstract Factory Design Pattern/Furniture /JAVA/furniture.java
================================================
interface Sofa {
void sitOn();
}
// Abstract Product: Chair
interface Chair {
void sitOn();
}
// Abstract Product: Table
interface Table {
void place();
}
// Concrete Products: Modern Furniture Items
class ModernSofa implements Sofa {
public void sitOn() {
System.out.println("Sitting on a Modern Sofa");
}
}
class ModernChair implements Chair {
public void sitOn() {
System.out.println("Sitting on a Modern Chair");
}
}
class ModernTable implements Table {
public void place() {
System.out.println("Placing items on a Modern Table");
}
}
// Concrete Products: Traditional Furniture Items
class TraditionalSofa implements Sofa {
public void sitOn() {
System.out.println("Sitting on a Traditional Sofa");
}
}
class TraditionalChair implements Chair {
public void sitOn() {
System.out.println("Sitting on a Traditional Chair");
}
}
class TraditionalTable implements Table {
public void place() {
System.out.println("Placing items on a Traditional Table");
}
}
// Abstract Factory: Furniture Factory
interface FurnitureFactory {
Sofa createSofa();
Chair createChair();
Table createTable();
public static FurnitureFactory createFurnitureFactory(String type) {
if (type.equals("modern")) {
return new ModernFurnitureFactory();
} else if (type.equals("traditional")) {
return new TraditionalFurnitureFactory();
} else {
return null;
}
}
}
// Concrete Factory: Modern Furniture Factory
class ModernFurnitureFactory implements FurnitureFactory {
public Sofa createSofa() {
return new ModernSofa();
}
public Chair createChair() {
return new ModernChair();
}
public Table createTable() {
return new ModernTable();
}
}
// Concrete Factory: Traditional Furniture Factory
class TraditionalFurnitureFactory implements FurnitureFactory {
public Sofa createSofa() {
return new TraditionalSofa();
}
public Chair createChair() {
return new TraditionalChair();
}
public Table createTable() {
return new TraditionalTable();
}
}
public class furniture {
public static void main(String[] args) {
FurnitureFactory modernFactory = FurnitureFactory.createFurnitureFactory("modern");
// use the abstract factory to create factories
// Create Modern furniture items
Sofa modernSofa = modernFactory.createSofa();
Chair modernChair = modernFactory.createChair();
Table modernTable = modernFactory.createTable();
// Use Modern furniture items
modernSofa.sitOn();
modernChair.sitOn();
modernTable.place();
// Create a Traditional Furniture Factory
FurnitureFactory traditionalFactory = FurnitureFactory.createFurnitureFactory("traditional");
// Create Traditional furniture items
Sofa traditionalSofa = traditionalFactory.createSofa();
Chair traditionalChair = traditionalFactory.createChair();
Table traditionalTable = traditionalFactory.createTable();
// Use Traditional furniture items
traditionalSofa.sitOn();
traditionalChair.sitOn();
traditionalTable.place();
}
}
================================================
FILE: Abstract Factory Design Pattern/Furniture /Javascript/furniture.js
================================================
// Abstract Product: Sofa
class Sofa {
sitOn() {}
}
// Abstract Product: Chair
class Chair {
sitOn() {}
}
// Abstract Product: Table
class Table {
place() {}
}
// Concrete Products: Modern Furniture Items
class ModernSofa extends Sofa {
sitOn() {
console.log("Sitting on a Modern Sofa");
}
}
class ModernChair extends Chair {
sitOn() {
console.log("Sitting on a Modern Chair");
}
}
class ModernTable extends Table {
place() {
console.log("Placing items on a Modern Table");
}
}
// Concrete Products: Traditional Furniture Items
class TraditionalSofa extends Sofa {
sitOn() {
console.log("Sitting on a Traditional Sofa");
}
}
class TraditionalChair extends Chair {
sitOn() {
console.log("Sitting on a Traditional Chair");
}
}
class TraditionalTable extends Table {
place() {
console.log("Placing items on a Traditional Table");
}
}
// Abstract Factory: Furniture Factory
class FurnitureFactory {
createSofa() {}
createChair() {}
createTable() {}
static createFurnitureFactory(type) {
if (type === "modern") {
return new ModernFurnitureFactory();
} else if (type === "traditional") {
return new TraditionalFurnitureFactory();
} else {
return null;
}
}
}
// Concrete Factory: Modern Furniture Factory
class ModernFurnitureFactory extends FurnitureFactory {
createSofa() {
return new ModernSofa();
}
createChair() {
return new ModernChair();
}
createTable() {
return new ModernTable();
}
}
// Concrete Factory: Traditional Furniture Factory
class TraditionalFurnitureFactory extends FurnitureFactory {
createSofa() {
return new TraditionalSofa();
}
createChair() {
return new TraditionalChair();
}
createTable() {
return new TraditionalTable();
}
}
function main() {
const modernFactory = FurnitureFactory.createFurnitureFactory("modern");
// Create Modern furniture items
const modernSofa = modernFactory.createSofa();
const modernChair = modernFactory.createChair();
const modernTable = modernFactory.createTable();
// Use Modern furniture items
modernSofa.sitOn();
modernChair.sitOn();
modernTable.place();
// Create a Traditional Furniture Factory
const traditionalFactory = FurnitureFactory.createFurnitureFactory("traditional");
// Create Traditional furniture items
const traditionalSofa = traditionalFactory.createSofa();
const traditionalChair = traditionalFactory.createChair();
const traditionalTable = traditionalFactory.createTable();
// Use Traditional furniture items
traditionalSofa.sitOn();
traditionalChair.sitOn();
traditionalTable.place();
}
main();
================================================
FILE: Abstract Factory Design Pattern/Furniture /Python/furniture.py
================================================
# Abstract Product: Sofa
class Sofa:
def sit_on(self):
pass
# Abstract Product: Chair
class Chair:
def sit_on(self):
pass
# Abstract Product: Table
class Table:
def place(self):
pass
# Concrete Products: Modern Furniture Items
class ModernSofa(Sofa):
def sit_on(self):
print("Sitting on a Modern Sofa")
class ModernChair(Chair):
def sit_on(self):
print("Sitting on a Modern Chair")
class ModernTable(Table):
def place(self):
print("Placing items on a Modern Table")
# Concrete Products: Traditional Furniture Items
class TraditionalSofa(Sofa):
def sit_on(self):
print("Sitting on a Traditional Sofa")
class TraditionalChair(Chair):
def sit_on(self):
print("Sitting on a Traditional Chair")
class TraditionalTable(Table):
def place(self):
print("Placing items on a Traditional Table")
# Abstract Factory: Furniture Factory
class FurnitureFactory:
def create_sofa(self):
pass
def create_chair(self):
pass
def create_table(self):
pass
@staticmethod
def create_furniture_factory(type):
if type == "modern":
return ModernFurnitureFactory()
elif type == "traditional":
return TraditionalFurnitureFactory()
else:
return None
# Concrete Factory: Modern Furniture Factory
class ModernFurnitureFactory(FurnitureFactory):
def create_sofa(self):
return ModernSofa()
def create_chair(self):
return ModernChair()
def create_table(self):
return ModernTable()
# Concrete Factory: Traditional Furniture Factory
class TraditionalFurnitureFactory(FurnitureFactory):
def create_sofa(self):
return TraditionalSofa()
def create_chair(self):
return TraditionalChair()
def create_table(self):
return TraditionalTable()
def main():
modern_factory = FurnitureFactory.create_furniture_factory("modern")
# Create Modern furniture items
modern_sofa = modern_factory.create_sofa()
modern_chair = modern_factory.create_chair()
modern_table = modern_factory.create_table()
# Use Modern furniture items
modern_sofa.sit_on()
modern_chair.sit_on()
modern_table.place()
traditional_factory = FurnitureFactory.create_furniture_factory("traditional")
# Create Traditional furniture items
traditional_sofa = traditional_factory.create_sofa()
traditional_chair = traditional_factory.create_chair()
traditional_table = traditional_factory.create_table()
# Use Traditional furniture items
traditional_sofa.sit_on()
traditional_chair.sit_on()
traditional_table.place()
if __name__ == "__main__":
main()
================================================
FILE: Abstract Factory Design Pattern/UI/C++/ui.cpp
================================================
#include <string>
#include <iostream>
using namespace std;
class Ibutton{
public :
virtual void press() = 0;
};
class ITextbox{
public :
virtual void settext() = 0;
};
class MacButton : public Ibutton{
public :
void press(){
cout<<"Mac button pressed"<<endl;
}
};
class WinButton : public Ibutton{
public :
void press(){
cout<<"Win button pressed"<<endl;
}
};
class MacTextBox : public ITextbox{
public :
void settext(){
cout<<"Setting text in Mac Textbox"<<endl;
}
};
class WinTextBox : public ITextbox{
public :
void settext(){
cout<<"Setting text in Win Textbox"<<endl;
}
};
class IFactory{
public :
virtual Ibutton* createbutton() = 0;
virtual ITextbox* createtextbox() = 0;
};
class WinFactory : public IFactory{
public :
Ibutton* createbutton(){
return new WinButton();
}
ITextbox* createtextbox(){
return new WinTextBox();
}
};
class MacFactory : public IFactory{
public :
Ibutton* createbutton(){
return new MacButton();
}
ITextbox* createtextbox(){
return new MacTextBox();
}
};
class GUIAbstractfactory{
public:
static IFactory* createfactory(string ostype){
if(ostype == "windows"){
return new WinFactory();
}
else if(ostype == "mac"){
return new MacFactory;
}
return nullptr;
}
};
int main(){
cout<<"Enter machine OS\n";
string ostype;
cin>>ostype;
IFactory* fact = GUIAbstractfactory::createfactory(ostype);
Ibutton* button = fact->createbutton();
button->press();
ITextbox* textBox = fact->createtextbox();
textBox->settext();
return 0;
}
================================================
FILE: Abstract Factory Design Pattern/UI/JAVA/UI.java
================================================
import java.util.Scanner;
interface IButton {
void press();
}
interface ITextbox {
void settext();
}
class MacButton implements IButton {
@Override
public void press() {
System.out.println("Mac button pressed");
}
}
class WinButton implements IButton {
@Override
public void press() {
System.out.println("Win button pressed");
}
}
class MacTextBox implements ITextbox {
@Override
public void settext() {
System.out.println("Setting text in Mac Textbox");
}
}
class WinTextBox implements ITextbox {
@Override
public void settext() {
System.out.println("Setting text in Win Textbox");
}
}
interface IFactory {
IButton createButton();
ITextbox createTextbox();
}
class WinFactory implements IFactory {
@Override
public IButton createButton() {
return new WinButton();
}
@Override
public ITextbox createTextbox() {
return new WinTextBox();
}
}
class MacFactory implements IFactory {
@Override
public IButton createButton() {
return new MacButton();
}
@Override
public ITextbox createTextbox() {
return new MacTextBox();
}
}
class GUIAbstractFactory {
public static IFactory createFactory(String osType) {
if (osType.equals("windows")) {
return new WinFactory();
} else if (osType.equals("mac")) {
return new MacFactory();
}
return null;
}
}
public class UI {
public static void main(String[] args) {
System.out.println("Enter machine OS");
Scanner scanner = new Scanner(System.in);
String osType = scanner.nextLine();
scanner.close();
IFactory factory = GUIAbstractFactory.createFactory(osType);
if (factory != null) {
IButton button = factory.createButton();
button.press();
ITextbox textBox = factory.createTextbox();
textBox.settext();
} else {
System.out.println("Invalid OS type");
}
}
}
================================================
FILE: Adapter Design Pattern/Class Adapter/C++/xml_to_json.cpp
================================================
#include <iostream>
using namespace std;
// Data analytics tool that expects JSON data
// Adaptee
class JSONAnalyticsTool
{
string pJsonData;
public:
void setJsonData(string jsonData) {
pJsonData = jsonData;
}
void AnalyzeData()
{
if (pJsonData.find("json") != string::npos) {
cout << "Analysing JSON Data - " << pJsonData << endl;
} else {
cout << "Not correct format. Can't analyse! " << endl;
}
}
};
// Interface Class
// Target
class AnalyticsTool {
public:
virtual void AnalyzeData() = 0;
virtual ~AnalyticsTool() {}
};
// Adapter
// Problem with Multiple Inheritance
class XMLToJSONAdapter : public AnalyticsTool, public JSONAnalyticsTool
{
public:
XMLToJSONAdapter(string xmlData) {
cout<<"Converting the XML Data '" << xmlData <<"' to JSON Data!"<<endl;
string newData = xmlData + " in json";
setJsonData(newData);
}
void AnalyzeData()
{
//Could convert here instead of the constructor
JSONAnalyticsTool::AnalyzeData();
}
};
int main()
{
string xmlData = "Sample Data";
JSONAnalyticsTool tool1;
tool1.setJsonData(xmlData);
tool1.AnalyzeData();
cout<<"----------------------------------------------"<<endl;
AnalyticsTool *tool2 = new XMLToJSONAdapter(xmlData);
tool2->AnalyzeData();
delete tool2;
return 0;
}
================================================
FILE: Adapter Design Pattern/Object Adapter/C++/xml_to_json.cpp
================================================
#include <iostream>
using namespace std;
// Data analytics tool that expects JSON data
// Adaptee
class JSONAnalyticsTool
{
string pJsonData;
public:
void setJsonData(string jsonData) {
pJsonData = jsonData;
}
void AnalyzeData()
{
if (pJsonData.find("json") != string::npos) {
cout << "Analysing JSON Data - " << pJsonData << endl;
} else {
cout << "Not correct format. Can't analyse! " << endl;
}
}
};
// Interface Class
// Target
class AnalyticsTool {
public:
virtual void AnalyzeData() = 0;
virtual ~AnalyticsTool() {}
};
// Adapter
class XMLToJSONAdapter : public AnalyticsTool
{
private:
JSONAnalyticsTool jsonAnalyticsTool;
public:
XMLToJSONAdapter(string xmlData) {
cout<<"Converting the XML Data '" << xmlData <<"' to JSON Data!"<<endl;
string newData = xmlData + " in json";
jsonAnalyticsTool.setJsonData(newData);
}
void AnalyzeData()
{
//Could convert here instead of the constructor
jsonAnalyticsTool.AnalyzeData();
}
};
int main()
{
string xmlData = "Sample Data";
JSONAnalyticsTool tool1;
tool1.setJsonData(xmlData);
tool1.AnalyzeData();
cout<<"----------------------------------------------"<<endl;
AnalyticsTool *tool2 = new XMLToJSONAdapter(xmlData);
tool2->AnalyzeData();
delete tool2;
return 0;
}
================================================
FILE: Adapter Design Pattern/Object Adapter/JAVA/XmlToJson.java
================================================
class JSONAnalyticsTool {
private String jsonData;
public void setJsonData(String jsonData) {
this.jsonData = jsonData;
}
public void AnalyzeData() {
if (jsonData.contains("json")) {
System.out.println("Analyzing JSON Data - " + jsonData);
} else {
System.out.println("Not in the correct format. Can't analyze!");
}
}
}
interface AnalyticsTool {
void AnalyzeData();
}
class XMLToJSONAdapter implements AnalyticsTool {
private JSONAnalyticsTool jsonAnalyticsTool;
public XMLToJSONAdapter(String xmlData) {
System.out.println("Converting the XML Data '" + xmlData + "' to JSON Data!");
String newData = xmlData + " in json";
jsonAnalyticsTool = new JSONAnalyticsTool();
jsonAnalyticsTool.setJsonData(newData);
}
public void AnalyzeData() {
jsonAnalyticsTool.AnalyzeData();
}
}
public class XmlToJson {
public static void main(String[] args) {
String xmlData = "Sample Data";
JSONAnalyticsTool tool1 = new JSONAnalyticsTool();
tool1.setJsonData(xmlData);
tool1.AnalyzeData();
System.out.println("----------------------------------------------");
AnalyticsTool tool2 = new XMLToJSONAdapter(xmlData);
tool2.AnalyzeData();
}
}
================================================
FILE: Bridge Design Pattern/C++/uber.cpp
================================================
#include <iostream>
using namespace std;
// Implementation Layer
class NavigationImpl
{
public:
virtual void navigateTo(string destination) = 0;
};
// Concrete Implementation: GoogleMaps
class GoogleMaps : public NavigationImpl
{
public:
void navigateTo(string destination)
{
cout << "Google Maps." << endl;
// Actual navigation logic using Google Maps API
}
};
// Concrete Implementation: AppleMaps
class AppleMaps : public NavigationImpl
{
public:
void navigateTo(string destination)
{
cout << "Apple Maps." << endl;
// Actual navigation logic using Apple Maps API
}
};
// Abstraction Layer
class NavigationSystem
{
protected:
NavigationImpl *navigationImpl;
public:
virtual void navigate(string destination) = 0;
};
// Concrete Abstraction: UberRide
class UberRide : public NavigationSystem
{
private:
string driverName;
public:
UberRide(string driverName) : driverName(driverName) {}
void navigate(string destination)
{
cout << "Uber ride with " << driverName << " to " << destination << " using ";
navigationImpl->navigateTo(destination);
}
void setNavigationImpl(NavigationImpl *impl)
{
navigationImpl = impl;
}
};
// Concrete Abstraction: UberEats
class UberEats : public NavigationSystem
{
private:
string restaurantName;
public:
UberEats(string restaurantName) : restaurantName(restaurantName) {}
void navigate(string destination)
{
cout << "Uber Eats delivery from " << restaurantName << " to " << destination << " using ";
navigationImpl->navigateTo(destination);
}
void setNavigationImpl(NavigationImpl *impl)
{
navigationImpl = impl;
}
};
int main()
{
// Create an UberRide with a driver
UberRide uber("Keerti");
// Create an UberEats delivery
UberEats uberEats("Pizza Palace");
// Create different navigation implementations
GoogleMaps googleMaps;
AppleMaps appleMaps;
// Set the navigation implementation for UberRide
uber.setNavigationImpl(&googleMaps);
// Request an Uber ride with Google Maps navigation
uber.navigate("Central Park");
// Switch to Apple Maps navigation for UberEats
uberEats.setNavigationImpl(&appleMaps);
// Request an Uber Eats delivery with Apple Maps navigation
uberEats.navigate("123 HSR");
return 0;
}
================================================
FILE: Bridge Design Pattern/JAVA/UberDemo.java
================================================
// Implementation Layer
interface NavigationImpl {
void navigateTo(String destination);
}
// Abstraction Layer
interface NavigationSystem {
void navigate(String destination);
}
// Concrete Abstraction: UberRide
class UberRide implements NavigationSystem {
private String driverName;
private NavigationImpl navigationImpl;
public UberRide(String driverName) {
this.driverName = driverName;
}
public void setNavigationImpl(NavigationImpl impl) {
this.navigationImpl = impl;
}
public void navigate(String destination) {
System.out.print("Uber ride with " + driverName + " to " + destination + " using ");
navigationImpl.navigateTo(destination);
}
}
// Concrete Abstraction: UberEats
class UberEats implements NavigationSystem {
private String restaurantName;
private NavigationImpl navigationImpl;
public UberEats(String restaurantName) {
this.restaurantName = restaurantName;
}
public void setNavigationImpl(NavigationImpl impl) {
this.navigationImpl = impl;
}
public void navigate(String destination) {
System.out.print("Uber Eats delivery from " + restaurantName + " to " + destination + " using ");
navigationImpl.navigateTo(destination);
}
}
// Concrete Implementation: GoogleMaps
class GoogleMaps implements NavigationImpl {
public void navigateTo(String destination) {
System.out.println("Google Maps.");
// Actual navigation logic using Google Maps API
}
}
// Concrete Implementation: AppleMaps
class AppleMaps implements NavigationImpl {
public void navigateTo(String destination) {
System.out.println("Apple Maps.");
// Actual navigation logic using Apple Maps API
}
}
public class UberDemo {
public static void main(String[] args) {
// Create an UberRide with a driver
UberRide uber = new UberRide("Keerti");
// Create an UberEats delivery
UberEats uberEats = new UberEats("Pizza Palace");
// Create different navigation implementations
GoogleMaps googleMaps = new GoogleMaps();
AppleMaps appleMaps = new AppleMaps();
// Set the navigation implementation for UberRide
uber.setNavigationImpl(googleMaps);
// Request an Uber ride with Google Maps navigation
uber.navigate("Central Park");
// Switch to Apple Maps navigation for UberEats
uberEats.setNavigationImpl(appleMaps);
// Request an Uber Eats delivery with Apple Maps navigation
uberEats.navigate("123 HSR");
}
}
================================================
FILE: Builder Design Pattern/Builder with Chaining/C++/desktop.cpp
================================================
#include <iostream>
using namespace std;
class Desktop
{
public:
string motherboard;
string processor;
string memory;
string storage;
string graphicsCard;
void display()
{
cout << "Desktop Specs:" << endl;
cout << "Motherboard: " << motherboard << endl;
cout << "Processor: " << processor << endl;
cout << "Memory: " << memory << endl;
cout << "Storage: " << storage << endl;
cout << "Graphics Card: " << graphicsCard << endl;
}
};
class DesktopBuilder
{
protected:
Desktop desktop;
public:
virtual DesktopBuilder &buildMotherboard() = 0;
virtual DesktopBuilder &buildProcessor() = 0;
virtual DesktopBuilder &buildMemory() = 0;
virtual DesktopBuilder &buildStorage() = 0;
virtual DesktopBuilder &buildGraphicsCard() = 0;
Desktop build()
{
return desktop;
}
};
class DellDesktopBuilder : public DesktopBuilder
{
public:
DesktopBuilder &buildMotherboard()
{
desktop.motherboard = "Dell Motherboard";
return *this;
}
DesktopBuilder &buildProcessor()
{
desktop.processor = "Dell Processor";
return *this;
}
DesktopBuilder &buildMemory()
{
desktop.memory = "32GB DDR4 RAM";
return *this;
}
DesktopBuilder &buildStorage()
{
desktop.storage = "1TB SSD + 2TB HDD";
return *this;
}
DesktopBuilder &buildGraphicsCard()
{
desktop.graphicsCard = "NVIDIA RTX 3080";
return *this;
}
};
class HpDesktopBuilder : public DesktopBuilder
{
public:
DesktopBuilder &buildMotherboard()
{
desktop.motherboard = "Hp Motherboard";
return *this;
}
DesktopBuilder &buildProcessor()
{
desktop.processor = "Intel Core i5";
return *this;
}
DesktopBuilder &buildMemory()
{
desktop.memory = "16GB DDR4 RAM";
return *this;
}
DesktopBuilder &buildStorage()
{
desktop.storage = "512GB SSD";
return *this;
}
DesktopBuilder &buildGraphicsCard()
{
desktop.graphicsCard = "Integrated Graphics";
return *this;
}
};
class DesktopDirector
{
public:
Desktop buildComputer(DesktopBuilder &builder)
{
return builder.buildMotherboard().buildProcessor().buildMemory().buildStorage().buildGraphicsCard().build();
}
};
int main()
{
DesktopDirector director;
DellDesktopBuilder dellDesktopBuilder;
Desktop highEndComputer = director.buildComputer(dellDesktopBuilder);
HpDesktopBuilder officeBuilder;
Desktop officeComputer = director.buildComputer(officeBuilder);
highEndComputer.display();
officeComputer.display();
return 0;
}
================================================
FILE: Builder Design Pattern/Builder with Chaining/JAVA/DesktopBuilderDemo.java
================================================
class Desktop {
String motherboard;
String processor;
String memory;
String storage;
String graphicsCard;
void display() {
System.out.println("Desktop Specs:");
System.out.println("Motherboard: " + motherboard);
System.out.println("Processor: " + processor);
System.out.println("Memory: " + memory);
System.out.println("Storage: " + storage);
System.out.println("Graphics Card: " + graphicsCard);
}
}
abstract class DesktopBuilder {
protected Desktop desktop;
abstract DesktopBuilder buildMotherboard();
abstract DesktopBuilder buildProcessor();
abstract DesktopBuilder buildMemory();
abstract DesktopBuilder buildStorage();
abstract DesktopBuilder buildGraphicsCard();
Desktop build() {
return desktop;
}
}
class DellDesktopBuilder extends DesktopBuilder {
DellDesktopBuilder() {
desktop = new Desktop();
}
@Override
DesktopBuilder buildMotherboard() {
desktop.motherboard = "Dell Motherboard";
return this;
}
@Override
DesktopBuilder buildProcessor() {
desktop.processor = "Dell Processor";
return this;
}
@Override
DesktopBuilder buildMemory() {
desktop.memory = "32GB DDR4 RAM";
return this;
}
@Override
DesktopBuilder buildStorage() {
desktop.storage = "1TB SSD + 2TB HDD";
return this;
}
@Override
DesktopBuilder buildGraphicsCard() {
desktop.graphicsCard = "NVIDIA RTX 3080";
return this;
}
}
class HpDesktopBuilder extends DesktopBuilder {
HpDesktopBuilder() {
desktop = new Desktop();
}
@Override
DesktopBuilder buildMotherboard() {
desktop.motherboard = "Hp Motherboard";
return this;
}
@Override
DesktopBuilder buildProcessor() {
desktop.processor = "Intel Core i5";
return this;
}
@Override
DesktopBuilder buildMemory() {
desktop.memory = "16GB DDR4 RAM";
return this;
}
@Override
DesktopBuilder buildStorage() {
desktop.storage = "512GB SSD";
return this;
}
@Override
DesktopBuilder buildGraphicsCard() {
desktop.graphicsCard = "Integrated Graphics";
return this;
}
}
class DesktopDirector {
Desktop buildDesktop(DesktopBuilder builder) {
return builder.buildMotherboard().buildProcessor().buildMemory().buildStorage().buildGraphicsCard().build();
}
}
public class DesktopBuilderDemo {
public static void main(String[] args) {
// Director
DesktopDirector director = new DesktopDirector();
// Build a high-end Desktop
DellDesktopBuilder DellBuilder = new DellDesktopBuilder();
Desktop DellDesktop = director.buildDesktop(DellBuilder);
// Build an Hp Desktop
HpDesktopBuilder HpBuilder = new HpDesktopBuilder();
Desktop HpDesktop = director.buildDesktop(HpBuilder);
// Display Desktop specifications
DellDesktop.display();
HpDesktop.display();
}
}
================================================
FILE: Builder Design Pattern/C++/desktop.cpp
================================================
#include <iostream>
using namespace std;
class Desktop
{
public:
string motherboard;
string processor;
string memory;
string storage;
string graphicsCard;
void display()
{
cout << "Desktop Specs:" << endl;
cout << "Motherboard: " << motherboard << endl;
cout << "Processor: " << processor << endl;
cout << "Memory: " << memory << endl;
cout << "Storage: " << storage << endl;
cout << "Graphics Card: " << graphicsCard << endl;
}
};
class DesktopBuilder
{
protected:
Desktop desktop;
public:
virtual void buildMotherboard() = 0;
virtual void buildProcessor() = 0;
virtual void buildMemory() = 0;
virtual void buildStorage() = 0;
virtual void buildGraphicsCard() = 0;
Desktop getDesktop()
{
return desktop;
}
};
class DellDesktopBuilder : public DesktopBuilder
{
public:
void buildMotherboard()
{
desktop.motherboard = "Dell Motherboard";
}
void buildProcessor()
{
desktop.processor = "Dell Processor";
}
void buildMemory()
{
desktop.memory = "32GB DDR4 RAM";
}
void buildStorage()
{
desktop.storage = "1TB SSD + 2TB HDD";
}
void buildGraphicsCard()
{
desktop.graphicsCard = "NVIDIA RTX 3080";
}
};
class HpDesktopBuilder : public DesktopBuilder
{
public:
void buildMotherboard()
{
desktop.motherboard = "HP Motherboard";
}
void buildProcessor()
{
desktop.processor = "Intel Core i5";
}
void buildMemory()
{
desktop.memory = "16GB DDR4 RAM";
}
void buildStorage()
{
desktop.storage = "512GB SSD";
}
void buildGraphicsCard()
{
desktop.graphicsCard = "Integrated Graphics";
}
};
class DesktopDirector
{
public:
Desktop buildDesktop(DesktopBuilder &builder)
{
builder.buildMotherboard();
builder.buildProcessor();
builder.buildMemory();
builder.buildStorage();
builder.buildGraphicsCard();
return builder.getDesktop();
}
};
int main()
{
DesktopDirector director;
DellDesktopBuilder dellDesktopBuilder;
Desktop dellDesktop = director.buildDesktop(dellDesktopBuilder);
HpDesktopBuilder hpDesktopBuilder;
Desktop hpDesktop = director.buildDesktop(hpDesktopBuilder);
dellDesktop.display();
hpDesktop.display();
return 0;
}
================================================
FILE: Builder Design Pattern/JAVA/DesktopBuilderDemo.java
================================================
class Desktop {
private String motherboard;
private String processor;
private String memory;
private String storage;
private String graphicsCard;
public void display() {
System.out.println("Desktop Specs:");
System.out.println("Motherboard: " + motherboard);
System.out.println("Processor: " + processor);
System.out.println("Memory: " + memory);
System.out.println("Storage: " + storage);
System.out.println("Graphics Card: " + graphicsCard);
}
public String getMotherboard() {
return motherboard;
}
public void setMotherboard(String motherboard) {
this.motherboard = motherboard;
}
public String getProcessor() {
return processor;
}
public void setProcessor(String processor) {
this.processor = processor;
}
public String getMemory() {
return memory;
}
public void setMemory(String memory) {
this.memory = memory;
}
public String getStorage() {
return storage;
}
public void setStorage(String storage) {
this.storage = storage;
}
public String getGraphicsCard() {
return graphicsCard;
}
public void setGraphicsCard(String graphicsCard) {
this.graphicsCard = graphicsCard;
}
}
abstract class DesktopBuilder {
protected Desktop desktop = new Desktop();
public abstract void buildMotherboard();
public abstract void buildProcessor();
public abstract void buildMemory();
public abstract void buildStorage();
public abstract void buildGraphicsCard();
public Desktop getDesktop() {
return desktop;
}
}
class DellDesktopBuilder extends DesktopBuilder {
public void buildMotherboard() {
desktop.setMotherboard("Dell Motherboard");
}
public void buildProcessor() {
desktop.setProcessor("Dell Processor");
}
public void buildMemory() {
desktop.setMemory("32GB DDR4 RAM");
}
public void buildStorage() {
desktop.setStorage("1TB SSD + 2TB HDD");
}
public void buildGraphicsCard() {
desktop.setGraphicsCard("NVIDIA RTX 3080");
}
}
class HpDesktopBuilder extends DesktopBuilder {
public void buildMotherboard() {
desktop.setMotherboard("HP Motherboard");
}
public void buildProcessor() {
desktop.setProcessor("Intel Core i5");
}
public void buildMemory() {
desktop.setMemory("16GB DDR4 RAM");
}
public void buildStorage() {
desktop.setStorage("512GB SSD");
}
public void buildGraphicsCard() {
desktop.setGraphicsCard("Integrated Graphics");
}
}
class DesktopDirector {
public Desktop buildDesktop(DesktopBuilder builder) {
builder.buildMotherboard();
builder.buildProcessor();
builder.buildMemory();
builder.buildStorage();
builder.buildGraphicsCard();
return builder.getDesktop();
}
}
public class DesktopBuilderDemo {
public static void main(String[] args) {
DesktopDirector director = new DesktopDirector();
DellDesktopBuilder dellDesktopBuilder = new DellDesktopBuilder();
Desktop dellDesktop = director.buildDesktop(dellDesktopBuilder);
HpDesktopBuilder hpDesktopBuilder = new HpDesktopBuilder();
Desktop hpDesktop = director.buildDesktop(hpDesktopBuilder);
dellDesktop.display();
hpDesktop.display();
}
}
================================================
FILE: Chain of Responsibility Design Pattern/C++/swiggy_order.cpp
================================================
#include <iostream>
using namespace std;
// Define the abstract base class for order handlers.
class OrderHandler {
protected:
OrderHandler* nextHandler;
public:
OrderHandler(OrderHandler* nextHandler) : nextHandler(nextHandler) {}
virtual void processOrder(const string& order) = 0;
};
// Concrete handler for order validation.
class OrderValidationHandler : public OrderHandler {
public:
OrderValidationHandler(OrderHandler* nextHandler) : OrderHandler(nextHandler) {}
void processOrder(const string& order) {
cout<<"Validating order: "<<order<<endl;
if(nextHandler)
nextHandler->processOrder(order);
}
~OrderValidationHandler() {
cout<<"validation handler dtor called"<<endl;
}
};
// Concrete handler for payment processing.
class PaymentProcessingHanlder : public OrderHandler {
public:
PaymentProcessingHanlder(OrderHandler* nextHandler) : OrderHandler(nextHandler) {}
void processOrder(const string& order) {
cout<<"Processing payment for order: "<<order<<endl;
if(nextHandler)
nextHandler->processOrder(order);
}
~PaymentProcessingHanlder() {
cout<<"PaymentProcessingHanlder dtor called"<<endl;
}
};
// Concrete handler for order preparation.
class OrderPreparationHandler : public OrderHandler {
public:
OrderPreparationHandler(OrderHandler* nexxtHandler) : OrderHandler(nextHandler) {}
void processOrder(const string& order) {
cout<<"Preparing order: "<<order<<endl;
if(nextHandler)
nextHandler->processOrder(order);
}
~OrderPreparationHandler() {
cout<<"OrderPreparationHandler dtor called"<<endl;
}
};
// Concrete handler for delivery assignment.
class DeliveryAssignmentHandler : public OrderHandler {
public:
DeliveryAssignmentHandler(OrderHandler* nexxtHandler) : OrderHandler(nextHandler) {}
void processOrder(const string& order) {
cout<<"Assigning delivery for order: "<<order<<endl;
if(nextHandler)
nextHandler->processOrder(order);
}
~DeliveryAssignmentHandler() {
cout<<"DeliveryAssignmentHandler dtor called"<<endl;
}
};
// Concrete handler for order tracking.
class OrderTrackingHandler : public OrderHandler {
public:
OrderTrackingHandler(OrderHandler* nexxtHandler) : OrderHandler(nextHandler) {}
void processOrder(const string& order) {
cout<<"Tracking order: "<<order<<endl;
if(nextHandler)
nextHandler->processOrder(order);
}
~OrderTrackingHandler() {
cout<<"OrderTrackingHandler dtor called"<<endl;
}
};
int main() {
// Create a chain of responsibility for order processing
OrderHandler* orderProcessingChain =
new OrderValidationHandler(
new PaymentProcessingHanlder(
new OrderPreparationHandler(
new DeliveryAssignmentHandler(
new OrderTrackingHandler(nullptr)))));
// Simulate an order being placed
string order = "Pizza";
orderProcessingChain->processOrder(order);
/*
OrderHandler* orderTrackingHandler = new OrderTrackingHandler(nullptr);
OrderHandler* deliveryAssignmentHandler = new DeliveryAssignmentHandler(orderTrackingHandler);
OrderHandler* orderPreparationHandler = new OrderPreparationHandler(deliveryAssignmentHandler);
OrderHandler* paymentProcessingHandler = new PaymentProcessingHandler(orderPreparationHandler);
OrderHandler* orderValidationHandler = new OrderValidationHandler(paymentProcessingHandler);
// Simulate an order being placed
std::string order = "Burger and Fries";
orderValidationHandler->processOrder(order);
// Clean up by deleting all handler objects
delete orderValidationHandler;
delete paymentProcessingHandler;
delete orderPreparationHandler;
delete deliveryAssignmentHandler;
delete orderTrackingHandler;
//Or use shared pointers so that we don't have to handle cleanup
*/
/*
//Add setters to choose successor or next handler on run-time
//Hanlder will have setSuccessor func
orderValidation.setSuccessor(paymentProcessing);
paymentProcessing.setSuccessor(shipping);
*/
return 0;
}
================================================
FILE: Chain of Responsibility Design Pattern/JAVA/SwiggyOrder.java
================================================
// Define the abstract base class for order handlers.
abstract class OrderHandler {
protected OrderHandler nextHandler;
public OrderHandler(OrderHandler nextHandler) {
this.nextHandler = nextHandler;
}
public abstract void processOrder(String order);
}
// Concrete handler for order validation.
class OrderValidationHandler extends OrderHandler {
public OrderValidationHandler(OrderHandler nextHandler) {
super(nextHandler);
}
@Override
public void processOrder(String order) {
System.out.println("Validating order: " + order);
// Perform order validation logic here
// If the order is valid, pass it to the next handler
if (nextHandler != null) {
nextHandler.processOrder(order);
}
}
}
// Concrete handler for payment processing.
class PaymentProcessingHandler extends OrderHandler {
public PaymentProcessingHandler(OrderHandler nextHandler) {
super(nextHandler);
}
@Override
public void processOrder(String order) {
System.out.println("Processing payment for order: " + order);
// Perform payment processing logic here
// If payment is successful, pass it to the next handler
if (nextHandler != null) {
nextHandler.processOrder(order);
}
}
}
// Concrete handler for order preparation.
class OrderPreparationHandler extends OrderHandler {
public OrderPreparationHandler(OrderHandler nextHandler) {
super(nextHandler);
}
@Override
public void processOrder(String order) {
System.out.println("Preparing order: " + order);
// Perform order preparation logic here
// If preparation is complete, pass it to the next handler
if (nextHandler != null) {
nextHandler.processOrder(order);
}
}
}
// Concrete handler for delivery assignment.
class DeliveryAssignmentHandler extends OrderHandler {
public DeliveryAssignmentHandler(OrderHandler nextHandler) {
super(nextHandler);
}
@Override
public void processOrder(String order) {
System.out.println("Assigning delivery for order: " + order);
// Perform delivery assignment logic here
// If delivery is assigned, pass it to the next handler
if (nextHandler != null) {
nextHandler.processOrder(order);
}
}
}
// Concrete handler for order tracking.
class OrderTrackingHandler extends OrderHandler {
public OrderTrackingHandler(OrderHandler nextHandler) {
super(nextHandler);
}
@Override
public void processOrder(String order) {
System.out.println("Tracking order: " + order);
// Perform order tracking logic here
}
}
public class SwiggyOrder {
public static void main(String[] args) {
// Create a chain of responsibility for order processing
OrderHandler orderProcessingChain = new OrderValidationHandler(
new PaymentProcessingHandler(
new OrderPreparationHandler(
new DeliveryAssignmentHandler(
new OrderTrackingHandler(null)))));
// The last handler has no next handler
// Simulate an order being placed
String order = "Pizza";
orderProcessingChain.processOrder(order);
}
}
================================================
FILE: Command Design Pattern/C++/document.cpp
================================================
#include <iostream>
using namespace std;
// Command Interface
class ActionListenerCommand {
public:
virtual void execute() = 0;
virtual ~ActionListenerCommand() {}
};
// Receiver - performing the operation
class Document {
public:
void open() {
cout << "Document Opened" << endl;
}
void save() {
cout << "Document Saved" << endl;
}
};
// Concrete Command
class ActionOpen : public ActionListenerCommand {
private:
Document* doc;
public:
ActionOpen(Document* document) : doc(document) {}
void execute() {
doc->open();
}
};
// Concrete Command
class ActionSave : public ActionListenerCommand {
private:
Document* doc;
public:
ActionSave(Document* document) : doc(document) {}
void execute() {
doc->save();
}
};
// Invoker
class MenuOptions {
private:
vector<ActionListenerCommand*> commands;
public:
void addCommand(ActionListenerCommand* command) {
commands.push_back(command);
}
void executeCommands() {
for (ActionListenerCommand* command : commands) {
command->execute();
}
}
};
int main() {
Document doc;
MenuOptions menu;
ActionListenerCommand* clickOpen = new ActionOpen(&doc);
ActionListenerCommand* clickSave = new ActionSave(&doc);
menu.addCommand(clickOpen);
menu.addCommand(clickSave);
// Client code only adds commands to the menu
// The invoker (menu) doesn't need to change when new commands are added
menu.executeCommands();
delete clickOpen;
delete clickSave;
return 0;
}
================================================
FILE: Command Design Pattern/C++/uber_rides.cpp
================================================
#include <iostream>
using namespace std;
// Receiver: RideService
class RideService {
public:
void requestRide(const string& passenger, const string& srcLoc, const string& destLoc) {
cout << "Requesting a ride for passenger: " << passenger
<< " from " << srcLoc << " to " << destLoc << endl;
// Additional ride request processing logic here
}
void cancelRide(const string& passenger) {
cout << "Canceling the ride for passenger: " << passenger << endl;
// Additional cancellation logic here
}
};
// Abstract Command interface
class Command {
public:
virtual void execute() = 0;
virtual ~Command() {}
};
// Concrete Command: RideRequestCommand
class RideRequestCommand : public Command {
private:
RideService* receiver;
string passenger;
string srcLoc;
string destLoc;
public:
RideRequestCommand(RideService* receiver, const string& passenger, const string& srcLoc, const string& destLoc)
: receiver(receiver), passenger(passenger), srcLoc(srcLoc), destLoc(destLoc) {}
void execute() override {
receiver->requestRide(passenger, srcLoc, destLoc);
}
};
// Concrete Command: CancelRideCommand
class CancelRideCommand : public Command {
private:
RideService* receiver;
string passenger;
public:
CancelRideCommand(RideService* receiver, const string& passenger)
: receiver(receiver), passenger(passenger) {}
void execute() override {
receiver->cancelRide(passenger);
}
};
// Invoker: RideRequestInvoker
class RideRequestInvoker {
public:
void processRequest(Command* command) {
command->execute();
}
};
int main() {
// Create a receiver
RideService rideService;
// Create an invoker
RideRequestInvoker rideRequestInvoker;
// Execute ride request and cancellation commands directly
Command* request1 = new RideRequestCommand(&rideService, "Keerti", "Sarjapur", "Koramangala");
Command* request2 = new RideRequestCommand(&rideService, "Amit", "Koramangala", "Indiranagar");
Command* cancel1 = new CancelRideCommand(&rideService, "Keerti");
// Process the ride requests and cancellations
rideRequestInvoker.processRequest(request1);
rideRequestInvoker.processRequest(request2);
rideRequestInvoker.processRequest(cancel1);
// Clean up
delete request1;
delete request2;
delete cancel1;
return 0;
}
================================================
FILE: Command Design Pattern/JAVA/DocumentDemo.java
================================================
import java.util.*;
//Command Interface
interface ActionListenerCommand {
void execute();
}
//Receiver - performing the operation
class Document {
public void open() {
System.out.println("Document Opened");
}
public void save() {
System.out.println("Document Saved");
}
}
//Concrete Command
class ActionOpen implements ActionListenerCommand {
private Document doc;
public ActionOpen(Document doc) {
this.doc = doc;
}
@Override
public void execute() {
doc.open();
}
}
//Concrete Command
class ActionSave implements ActionListenerCommand {
private Document doc;
public ActionSave(Document doc) {
this.doc = doc;
}
@Override
public void execute() {
doc.save();
}
}
// Invoker
class MenuOptions {
private List<ActionListenerCommand> commands = new ArrayList<>();
public void addCommand(ActionListenerCommand command) {
commands.add(command);
}
public void executeCommands() {
for (ActionListenerCommand command : commands) {
command.execute();
}
}
}
public class DocumentDemo {
public static void main(String[] args) {
Document doc = new Document(); // Receiver - performing action
// Create concrete commands
// Receiver with command
ActionListenerCommand clickOpen = new ActionOpen(doc);
ActionListenerCommand clickSave = new ActionSave(doc);
// Invoker
MenuOptions menu = new MenuOptions();
// Client code only adds commands to the menu
menu.addCommand(clickOpen);
menu.addCommand(clickSave);
menu.executeCommands();
}
}
================================================
FILE: Command Design Pattern/JAVA/UberRidesDemo.java
================================================
// Receiver: RideService
class RideService {
public void requestRide(String passenger, String srcLoc, String destLoc) {
System.out.println("Requesting a ride for passenger: " + passenger +
" from " + srcLoc + " to " + destLoc);
// Additional ride request processing logic here
}
public void cancelRide(String passenger) {
System.out.println("Canceling the ride for passenger: " + passenger);
// Additional cancellation logic here
}
}
// Abstract Command interface
interface Command {
void execute();
}
// Concrete Command: RideRequestCommand
class RideRequestCommand implements Command {
private RideService receiver;
private String passenger;
private String srcLoc;
private String destLoc;
public RideRequestCommand(RideService receiver, String passenger, String srcLoc, String destLoc) {
this.receiver = receiver;
this.passenger = passenger;
this.srcLoc = srcLoc;
this.destLoc = destLoc;
}
public void execute() {
receiver.requestRide(passenger, srcLoc, destLoc);
}
}
// Concrete Command: CancelRideCommand
class CancelRideCommand implements Command {
private RideService receiver;
private String passenger;
public CancelRideCommand(RideService receiver, String passenger) {
this.receiver = receiver;
this.passenger = passenger;
}
public void execute() {
receiver.cancelRide(passenger);
}
}
// Invoker: RideRequestInvoker
class RideRequestInvoker {
public void processRequest(Command command) {
command.execute();
}
}
public class UberRidesDemo {
public static void main(String[] args) {
// Create a receiver
RideService rideService = new RideService();
// Create an invoker
RideRequestInvoker rideRequestInvoker = new RideRequestInvoker();
// Execute ride request and cancellation commands directly
Command request1 = new RideRequestCommand(rideService, "Keerti", "Sarjapur", "Koramangala");
Command request2 = new RideRequestCommand(rideService, "Amit", "Koramangala", "Indiranagar");
Command cancel1 = new CancelRideCommand(rideService, "Keerti");
// Process the ride requests and cancellations
rideRequestInvoker.processRequest(request1);
rideRequestInvoker.processRequest(request2);
rideRequestInvoker.processRequest(cancel1);
// Clean up (not required in Java)
}
}
================================================
FILE: Composite Design Pattern/C++/directorystructure.cpp
================================================
#include <iostream>
using namespace std;
class FileSystemComponent {
public:
virtual void listContents() const = 0;
virtual int getSize() const = 0;
};
class File : public FileSystemComponent {
private:
string name;
int size;
public:
File(const string& fileName, int fileSize) : name(fileName), size(fileSize) {}
void listContents() const override {
cout << "File: " << name << endl;
}
int getSize() const override {
return size;
}
};
#include <vector>
class Directory : public FileSystemComponent {
private:
string name;
vector<FileSystemComponent*> contents;
public:
Directory(const string& dirName) : name(dirName) {}
void addComponent(FileSystemComponent* component) {
contents.push_back(component);
}
void listContents() const override {
cout << "Directory: " << name << endl;
for (const auto& component : contents) {
component->listContents();
}
}
int getSize() const override {
int totalSize = 0;
for (const auto& component : contents) {
totalSize += component->getSize();
}
return totalSize;
}
};
int main() {
Directory* root = new Directory("Root");
FileSystemComponent* file1 = new File("Document.txt", 100);
FileSystemComponent* file2 = new File("Image.jpg", 200);
Directory* subDir = new Directory("Subdirectory");
FileSystemComponent* file3 = new File("Data.csv", 150);
subDir->addComponent(file3);
root->addComponent(file1);
root->addComponent(file2);
root->addComponent(subDir);
// List contents and calculate total size for the directory structure
root->listContents();
int totalSize = root->getSize();
cout << "Total Size: " << totalSize << " KB" << endl;
// Clean up memory (consider using smart pointers in a real application)
delete root;
delete file1;
delete file2;
delete file3;
delete subDir;
return 0;
}
================================================
FILE: Composite Design Pattern/C++/employee.cpp
================================================
#include <iostream>
using namespace std;
class EmployeeComponent {
public:
virtual void displayInfo() = 0;
virtual double calculateSalary() = 0;
virtual ~EmployeeComponent() {}
};
class Employee : public EmployeeComponent {
private:
string name;
double salary;
public:
Employee(string empName, double empSalary) : name(empName), salary(empSalary) {}
void displayInfo() override {
cout << "Employee: " << name << " Salary: Rs." << salary << endl;
}
double calculateSalary() override {
return salary;
}
};
class Department : public EmployeeComponent {
private:
string name;
vector<EmployeeComponent*> members;
public:
Department(string deptName) : name(deptName) {}
void addMember(EmployeeComponent* member) {
members.push_back(member);
}
void displayInfo() override {
cout << "Department: " << name << endl;
for (auto member : members) {
member->displayInfo();
}
}
double calculateSalary() override {
double totalSalary = 0.0;
for (auto member : members) {
totalSalary += member->calculateSalary();
}
return totalSalary;
}
};
class Team : public EmployeeComponent {
private:
string name;
vector<EmployeeComponent*> members;
public:
Team(string teamName) : name(teamName) {}
void addMember(EmployeeComponent* member) {
members.push_back(member);
}
void displayInfo() override {
cout << "Team: " << name << endl;
for (auto& member : members) {
member->displayInfo();
}
}
double calculateSalary() override {
double totalSalary = 0.0;
for (auto member : members) {
totalSalary += member->calculateSalary();
}
return totalSalary;
}
};
int main() {
EmployeeComponent* keerti = new Employee("Keerti", 100.0);
EmployeeComponent* amit = new Employee("Amit", 200.0);
Team* sales = new Team("Sales");
sales->addMember(keerti);
sales->addMember(amit);
EmployeeComponent* bob = new Employee("Bob", 50.0);
Team* marketing = new Team("Marketing");
marketing->addMember(bob);
Department* headOffice = new Department("Head Office");
headOffice->addMember(sales);
headOffice->addMember(marketing);
// Display and calculate total salary for the organization hierarchy
headOffice->displayInfo();
double totalSalary = headOffice->calculateSalary();
cout << "Total Salary for the Organization: Rs." << totalSalary << endl;
// Clean up memory (consider using smart pointers in a real application)
delete keerti;
delete amit;
delete sales;
delete bob;
delete marketing;
delete headOffice;
return 0;
}
================================================
FILE: Composite Design Pattern/JAVA/EmployeesDemo.java
================================================
import java.util.*;
abstract class EmployeeComponent {
public abstract void displayInfo();
public abstract double calculateSalary();
}
class Employee extends EmployeeComponent {
private String name;
private double salary;
public Employee(String empName, double empSalary) {
name = empName;
salary = empSalary;
}
@Override
public void displayInfo() {
System.out.println("Employee: " + name + " Salary: Rs." + salary);
}
@Override
public double calculateSalary() {
return salary;
}
}
class Department extends EmployeeComponent {
private String name;
private List<EmployeeComponent> members;
public Department(String deptName) {
name = deptName;
members = new ArrayList<>();
}
public void addMember(EmployeeComponent member) {
members.add(member);
}
@Override
public void displayInfo() {
System.out.println("Department: " + name);
for (EmployeeComponent member : members) {
member.displayInfo();
}
}
@Override
public double calculateSalary() {
double totalSalary = 0.0;
for (EmployeeComponent member : members) {
totalSalary += member.calculateSalary();
}
return totalSalary;
}
}
class Team extends EmployeeComponent {
private String name;
private List<EmployeeComponent> members;
public Team(String teamName) {
name = teamName;
members = new ArrayList<>();
}
public void addMember(EmployeeComponent member) {
members.add(member);
}
@Override
public void displayInfo() {
System.out.println("Team: " + name);
for (EmployeeComponent member : members) {
member.displayInfo();
}
}
@Override
public double calculateSalary() {
double totalSalary = 0.0;
for (EmployeeComponent member : members) {
totalSalary += member.calculateSalary();
}
return totalSalary;
}
}
public class EmployeesDemo {
public static void main(String[] args) {
EmployeeComponent keerti = new Employee("Keerti", 100.0);
EmployeeComponent amit = new Employee("Amit", 200.0);
Team sales = new Team("Sales");
sales.addMember(keerti);
sales.addMember(amit);
EmployeeComponent bob = new Employee("Bob", 50.0);
Team marketing = new Team("Marketing");
marketing.addMember(bob);
Department headOffice = new Department("Head Office");
headOffice.addMember(sales);
headOffice.addMember(marketing);
// Display and calculate total salary for the organization hierarchy
headOffice.displayInfo();
double totalSalary = headOffice.calculateSalary();
System.out.println("Total Salary for the Organization: Rs." + totalSalary);
}
}
================================================
FILE: Composite Design Pattern/JAVA/directorystructure.java
================================================
import java.util.*;
// Abstraction Layer
interface FileSystemComponent {
void listContents();
int getSize();
}
// Concrete Implementation: File
class File implements FileSystemComponent {
private String name;
private int size;
public File(String fileName, int fileSize) {
this.name = fileName;
this.size = fileSize;
}
@Override
public void listContents() {
System.out.println("File: " + name);
}
@Override
public int getSize() {
return size;
}
}
// Concrete Implementation: Directory
class Directory implements FileSystemComponent {
private String name;
private List<FileSystemComponent> contents;
public Directory(String dirName) {
this.name = dirName;
this.contents = new ArrayList<>();
}
public void addComponent(FileSystemComponent component) {
contents.add(component);
}
@Override
public void listContents() {
System.out.println("Directory: " + name);
for (FileSystemComponent component : contents) {
component.listContents();
}
}
@Override
public int getSize() {
int totalSize = 0;
for (FileSystemComponent component : contents) {
totalSize += component.getSize();
}
return totalSize;
}
}
public class directorystructure {
public static void main(String[] args) {
Directory root = new Directory("Root");
FileSystemComponent file1 = new File("Document.txt", 100);
FileSystemComponent file2 = new File("Image.jpg", 200);
Directory subDir = new Directory("Subdirectory");
FileSystemComponent file3 = new File("Data.csv", 150);
subDir.addComponent(file3);
root.addComponent(file1);
root.addComponent(file2);
root.addComponent(subDir);
// List contents and calculate total size for the directory structure
root.listContents();
int totalSize = root.getSize();
System.out.println("Total Size: " + totalSize + " KB");
// Clean up memory (consider using automatic memory management in a real application)
// No need to explicitly delete objects in Java
}
}
================================================
FILE: Decorator Design Pattern/C++/swiggy.cpp
================================================
#include <iostream>
using namespace std;
// Base interface representing a food item.
// Component
class FoodItem
{
public:
virtual string getDescription() = 0;
virtual double getPrice() = 0;
virtual ~FoodItem() {}
};
// Concrete component
class Pizza : public FoodItem
{
public:
string getDescription()
{
return "Pizza";
}
double getPrice()
{
return 200.0;
}
};
// Concrete component
class Burger : public FoodItem
{
public:
string getDescription()
{
return "Burger";
}
double getPrice()
{
return 100.0;
}
};
class Decorator : public FoodItem
{
protected:
FoodItem *foodItem;
public:
Decorator(FoodItem *item) : foodItem(item) {}
};
// Concrete decorator for adding extra cheese.
class ExtraCheeseDecorator : public Decorator
{
private:
double extraCheesePrice;
public:
ExtraCheeseDecorator(FoodItem *item, double price)
: Decorator(item), extraCheesePrice(price) {}
string getDescription()
{
return foodItem->getDescription() + " with Extra Cheese";
}
double getPrice()
{
return foodItem->getPrice() + extraCheesePrice;
}
};
// Concrete decorator for adding extra sauce.
class ExtraSauceDecorator : public Decorator
{
private:
double extraSaucePrice;
public:
ExtraSauceDecorator(FoodItem *item, double price)
: Decorator(item), extraSaucePrice(price) {}
string getDescription()
{
return foodItem->getDescription() + " with Extra Sauce";
}
double getPrice()
{
return foodItem->getPrice() + extraSaucePrice;
}
};
// Concrete decorator for adding extra toppings.
class ExtraToppingsDecorator : public Decorator
{
private:
double extraToppingsPrice;
public:
ExtraToppingsDecorator(FoodItem *item, double price)
: Decorator(item), extraToppingsPrice(price) {}
string getDescription()
{
return foodItem->getDescription() + " with Extra Toppings";
}
double getPrice()
{
return foodItem->getPrice() + extraToppingsPrice;
}
};
int main()
{
// Order a Pizza and a Burger.
FoodItem *pizzaOrder = new Pizza();
FoodItem *burgerOrder = new Burger();
pizzaOrder = new ExtraCheeseDecorator(pizzaOrder, 10.0);
pizzaOrder = new ExtraSauceDecorator(pizzaOrder, 5.0);
burgerOrder = new ExtraCheeseDecorator(burgerOrder, 20.0);
burgerOrder = new ExtraToppingsDecorator(burgerOrder, 15.0);
cout << "Description of pizza order is " << pizzaOrder->getDescription() << endl;
cout << "Price of pizza order is : " << pizzaOrder->getPrice() << endl;
cout << "Description of burger order is " << burgerOrder->getDescription() << endl;
cout << "Price of burger order is : " << burgerOrder->getPrice() << endl;
// Clean up allocated memory
delete burgerOrder;
delete pizzaOrder;
return 0;
}
================================================
FILE: Decorator Design Pattern/JAVA/Swiggy.java
================================================
// Base interface representing a food item.
// Component
interface FoodItem {
String getDescription();
double getPrice();
}
// Concrete component
class Pizza implements FoodItem {
public String getDescription() {
return "Pizza";
}
public double getPrice() {
return 200.0;
}
}
// Concrete component
class Burger implements FoodItem {
public String getDescription() {
return "Burger";
}
public double getPrice() {
return 100.0;
}
}
// Decorator interface
abstract class Decorator implements FoodItem {
protected FoodItem foodItem;
public Decorator(FoodItem item) {
this.foodItem = item;
}
}
// Concrete decorator for adding extra cheese.
class ExtraCheeseDecorator extends Decorator {
private double extraCheesePrice;
public ExtraCheeseDecorator(FoodItem item, double price) {
super(item);
this.extraCheesePrice = price;
}
public String getDescription() {
return foodItem.getDescription() + " with Extra Cheese";
}
public double getPrice() {
return foodItem.getPrice() + extraCheesePrice;
}
}
// Concrete decorator for adding extra sauce.
class ExtraSauceDecorator extends Decorator {
private double extraSaucePrice;
public ExtraSauceDecorator(FoodItem item, double price) {
super(item);
this.extraSaucePrice = price;
}
public String getDescription() {
return foodItem.getDescription() + " with Extra Sauce";
}
public double getPrice() {
return foodItem.getPrice() + extraSaucePrice;
}
}
// Concrete decorator for adding extra toppings.
class ExtraToppingsDecorator extends Decorator {
private double extraToppingsPrice;
public ExtraToppingsDecorator(FoodItem item, double price) {
super(item);
this.extraToppingsPrice = price;
}
public String getDescription() {
return foodItem.getDescription() + " with Extra Toppings";
}
public double getPrice() {
return foodItem.getPrice() + extraToppingsPrice;
}
}
public class Swiggy {
public static void main(String[] args) {
// Order a Pizza and a Burger.
FoodItem pizzaOrder = new Pizza();
FoodItem burgerOrder = new Burger();
pizzaOrder = new ExtraCheeseDecorator(pizzaOrder, 10.0);
pizzaOrder = new ExtraSauceDecorator(pizzaOrder, 5.0);
burgerOrder = new ExtraCheeseDecorator(burgerOrder, 20.0);
burgerOrder = new ExtraToppingsDecorator(burgerOrder, 15.0);
System.out.println("Description of pizza order is " + pizzaOrder.getDescription());
System.out.println("Price of pizza order is: " + pizzaOrder.getPrice());
System.out.println("Description of burger order is " + burgerOrder.getDescription());
System.out.println("Price of burger order is: " + burgerOrder.getPrice());
}
}
================================================
FILE: Facade Design Pattern/C++/computer.cpp
================================================
#include <iostream>
using namespace std;
// Subsystem 1: CPU
class CPU {
public:
void powerOn() {
cout << "CPU is powered on." << endl;
}
void executeInstructions() {
cout << "CPU is executing instructions." << endl;
}
};
// Subsystem 2: Memory
class Memory {
public:
void initialize() {
cout << "Memory is initialized." << endl;
}
};
// Subsystem 3: GPU
class GPU {
public:
void enableGraphics() {
cout << "GPU graphics are enabled." << endl;
}
};
// Subsystem 4: Disk Drive
class DiskDrive {
public:
void bootFromDisk() {
cout << "Booting from the disk drive." << endl;
}
};
// Subsystem 5: Network Interface
class NetworkInterface {
public:
void connectToNetwork() {
cout << "Connected to the network." << endl;
}
};
// Facade: Computer System
class ComputerSystemFacade {
private:
CPU cpu;
Memory memory;
GPU gpu;
DiskDrive diskDrive;
NetworkInterface networkInterface;
public:
void startComputer() {
cout << "Starting the computer..." << endl;
cpu.powerOn();
memory.initialize();
gpu.enableGraphics();
diskDrive.bootFromDisk();
networkInterface.connectToNetwork();
cpu.executeInstructions();
cout << "Computer is ready to use." << endl;
}
};
int main() {
ComputerSystemFacade computer;
// User initiates the computer startup process with a single call
computer.startComputer();
return 0;
}
================================================
FILE: Facade Design Pattern/JAVA/ComputerDemo.java
================================================
// Subsystem 1: CPU
class CPU {
public void powerOn() {
System.out.println("CPU is powered on.");
}
public void executeInstructions() {
System.out.println("CPU is executing instructions.");
}
}
// Subsystem 2: Memory
class Memory {
public void initialize() {
System.out.println("Memory is initialized.");
}
}
// Subsystem 3: GPU
class GPU {
public void enableGraphics() {
System.out.println("GPU graphics are enabled.");
}
}
// Subsystem 4: Disk Drive
class DiskDrive {
public void bootFromDisk() {
System.out.println("Booting from the disk drive.");
}
}
// Subsystem 5: Network Interface
class NetworkInterface {
public void connectToNetwork() {
System.out.println("Connected to the network.");
}
}
// Facade: Computer System
class ComputerSystemFacade {
private CPU cpu;
private Memory memory;
private GPU gpu;
private DiskDrive diskDrive;
private NetworkInterface networkInterface;
public ComputerSystemFacade() {
this.cpu = new CPU();
this.memory = new Memory();
this.gpu = new GPU();
this.diskDrive = new DiskDrive();
this.networkInterface = new NetworkInterface();
}
public void startComputer() {
System.out.println("Starting the computer...");
cpu.powerOn();
memory.initialize();
gpu.enableGraphics();
diskDrive.bootFromDisk();
networkInterface.connectToNetwork();
cpu.executeInstructions();
System.out.println("Computer is ready to use.");
}
}
public class ComputerDemo {
public static void main(String[] args) {
ComputerSystemFacade computer = new ComputerSystemFacade();
// User initiates the computer startup process with a single call
computer.startComputer();
}
}
================================================
FILE: Factory Method Design Pattern/Furniture/C++/furniture.cpp
================================================
//The Factory Method pattern is a creational design pattern that defines an interface for creating objects but lets subclasses alter the type of objects that will be created.
#include <iostream>
#include <string>
// Abstract Product: Furniture Item
class FurnitureItem {
public:
virtual void display() = 0;
};
// Concrete Products: Sofa, Chair, Table
class Sofa : public FurnitureItem {
public:
void display() override {
std::cout << "Sofa" << std::endl;
}
};
class Chair : public FurnitureItem {
public:
void display() override {
std::cout << "Chair" << std::endl;
}
};
class Table : public FurnitureItem {
public:
void display() override {
std::cout << "Table" << std::endl;
}
};
// Abstract Creator: Furniture Factory
class FurnitureFactory {
public:
virtual FurnitureItem* createFurniture() = 0;
};
// Concrete Creators: Sofa Factory, Chair Factory, Table Factory
class SofaFactory : public FurnitureFactory {
public:
FurnitureItem* createFurniture() override {
return new Sofa();
}
};
class ChairFactory : public FurnitureFactory {
public:
FurnitureItem* createFurniture() override {
return new Chair();
}
};
class TableFactory : public FurnitureFactory {
public:
FurnitureItem* createFurniture() override {
return new Table();
}
};
int main() {
// Create factories for different types of furniture
FurnitureFactory* sofaFactory = new SofaFactory();
FurnitureFactory* chairFactory = new ChairFactory();
FurnitureFactory* tableFactory = new TableFactory();
// Create furniture objects using the factory methods
FurnitureItem* sofa = sofaFactory->createFurniture();
FurnitureItem* chair = chairFactory->createFurniture();
FurnitureItem* table = tableFactory->createFurniture();
// Display the created furniture items
sofa->display();
chair->display();
table->display();
// Clean up objects
delete sofaFactory;
delete chairFactory;
delete tableFactory;
delete sofa;
delete chair;
delete table;
return 0;
}
================================================
FILE: Factory Method Design Pattern/Furniture/JAVA/furniture.java
================================================
// Abstract Product: Furniture Item
interface FurnitureItem {
void display();
}
// Concrete Products: Sofa, Chair, Table
class Sofa implements FurnitureItem {
@Override
public void display() {
System.out.println("Sofa");
}
}
class Chair implements FurnitureItem {
@Override
public void display() {
System.out.println("Chair");
}
}
class Table implements FurnitureItem {
@Override
public void display() {
System.out.println("Table");
}
}
// Abstract Creator: Furniture Factory
interface FurnitureFactory {
FurnitureItem createFurniture();
}
// Concrete Creators: Sofa Factory, Chair Factory, Table Factory
class SofaFactory implements FurnitureFactory {
@Override
public FurnitureItem createFurniture() {
return new Sofa();
}
}
class ChairFactory implements FurnitureFactory {
@Override
public FurnitureItem createFurniture() {
return new Chair();
}
}
class TableFactory implements FurnitureFactory {
@Override
public FurnitureItem createFurniture() {
return new Table();
}
}
public class furniture {
public static void main(String[] args) {
// Create factories for different types of furniture
FurnitureFactory sofaFactory = new SofaFactory();
FurnitureFactory chairFactory = new ChairFactory();
FurnitureFactory tableFactory = new TableFactory();
// Create furniture objects using the factory methods
FurnitureItem sofa = sofaFactory.createFurniture();
FurnitureItem chair = chairFactory.createFurniture();
FurnitureItem table = tableFactory.createFurniture();
// Display the created furniture items
sofa.display();
chair.display();
table.display();
}
}
================================================
FILE: Factory Method Design Pattern/Furniture/Javascript/furniture.js
================================================
// Abstract Product: Furniture Item
class FurnitureItem {
display() {}
}
// Concrete Products: Sofa, Chair, Table
class Sofa extends FurnitureItem {
display() {
console.log("Sofa");
}
}
class Chair extends FurnitureItem {
display() {
console.log("Chair");
}
}
class Table extends FurnitureItem {
display() {
console.log("Table");
}
}
// Abstract Creator: Furniture Factory
class FurnitureFactory {
createFurniture() {}
}
// Concrete Creators: Sofa Factory, Chair Factory, Table Factory
class SofaFactory extends FurnitureFactory {
createFurniture() {
return new Sofa();
}
}
class ChairFactory extends FurnitureFactory {
createFurniture() {
return new Chair();
}
}
class TableFactory extends FurnitureFactory {
createFurniture() {
return new Table();
}
}
function main() {
// Create factories for different types of furniture
const sofaFactory = new SofaFactory();
const chairFactory = new ChairFactory();
const tableFactory = new TableFactory();
// Create furniture objects using the factory methods
const sofa = sofaFactory.createFurniture();
const chair = chairFactory.createFurniture();
const table = tableFactory.createFurniture();
// Display the created furniture items
sofa.display();
chair.display();
table.display();
}
main();
================================================
FILE: Factory Method Design Pattern/Furniture/Python/furniture.py
================================================
# Abstract Product: Furniture Item
class FurnitureItem:
def display(self):
pass
# Concrete Products: Sofa, Chair, Table
class Sofa(FurnitureItem):
def display(self):
print("Sofa")
class Chair(FurnitureItem):
def display(self):
print("Chair")
class Table(FurnitureItem):
def display(self):
print("Table")
# Abstract Creator: Furniture Factory
class FurnitureFactory:
def create_furniture(self):
pass
# Concrete Creators: Sofa Factory, Chair Factory, Table Factory
class SofaFactory(FurnitureFactory):
def create_furniture(self):
return Sofa()
class ChairFactory(FurnitureFactory):
def create_furniture(self):
return Chair()
class TableFactory(FurnitureFactory):
def create_furniture(self):
return Table()
def main():
# Create factories for different types of furniture
sofa_factory = SofaFactory()
chair_factory = ChairFactory()
table_factory = TableFactory()
# Create furniture objects using the factory methods
sofa = sofa_factory.create_furniture()
chair = chair_factory.create_furniture()
table = table_factory.create_furniture()
# Display the created furniture items
sofa.display()
chair.display()
table.display()
if __name__ == "__main__":
main()
================================================
FILE: Factory Method Design Pattern/Logger/C++/common.hpp
================================================
#pragma once
#include <iostream>
using namespace std;
enum class LogLevel {
DEBUG,
INFO,
ERROR
};
================================================
FILE: Factory Method Design Pattern/Logger/C++/debug_logger.cpp
================================================
#include "debug_logger.hpp"
void DebugLogger::log(const string &msg)
{
cout << "DEBUG : " << msg << endl;
}
================================================
FILE: Factory Method Design Pattern/Logger/C++/debug_logger.hpp
================================================
#pragma once
#include "ilogger.hpp"
class DebugLogger : public ILogger {
public:
void log(const string& msg);
};
================================================
FILE: Factory Method Design Pattern/Logger/C++/debug_logger_factory.hpp
================================================
#pragma once
#include "logger_factory.hpp"
class DebugLoggerFactory : public ILoggerFactory{
public:
ILogger* createLogger() {
return new DebugLogger();
}
};
================================================
FILE: Factory Method Design Pattern/Logger/C++/error_logger.cpp
================================================
#include "error_logger.hpp"
void ErrorLogger::log(const string& msg) {
cout<<"ERROR : "<<msg<<endl;
}
================================================
FILE: Factory Method Design Pattern/Logger/C++/error_logger.hpp
================================================
#pragma once
#include "ilogger.hpp"
class ErrorLogger : public ILogger{
public:
void log(const string& msg);
};
================================================
FILE: Factory Method Design Pattern/Logger/C++/error_logger_factory.hpp
================================================
#pragma once
#include "logger_factory.hpp"
class ErrorLoggerFactory : public ILoggerFactory{
public:
ILogger* createLogger() {
return new ErrorLogger();
}
};
================================================
FILE: Factory Method Design Pattern/Logger/C++/ilogger.hpp
================================================
#pragma once
#include "common.hpp"
class ILogger {
public:
virtual void log(const string& msg) = 0;
virtual ~ILogger() {}
};
================================================
FILE: Factory Method Design Pattern/Logger/C++/info_logger.cpp
================================================
#include "info_logger.hpp"
void InfoLogger::log(const string& msg) {
cout<<"INFO : "<<msg<<endl;
}
================================================
FILE: Factory Method Design Pattern/Logger/C++/info_logger.hpp
================================================
#pragma once
#include "ilogger.hpp"
class InfoLogger : public ILogger {
public:
void log(const string& msg);
};
================================================
FILE: Factory Method Design Pattern/Logger/C++/info_logger_factory.hpp
================================================
#pragma once
#include "logger_factory.hpp"
class InfoLoggerFactory : public ILoggerFactory{
public:
ILogger* createLogger() {
return new InfoLogger();
}
};
================================================
FILE: Factory Method Design Pattern/Logger/C++/logger_factory.hpp
================================================
#pragma once
#include "ilogger.hpp"
#include "debug_logger.hpp"
#include "info_logger.hpp"
#include "error_logger.hpp"
class ILoggerFactory {
public:
virtual ILogger* createLogger() = 0;
};
================================================
FILE: Factory Method Design Pattern/Logger/C++/main.cpp
================================================
#include "info_logger_factory.hpp"
#include "debug_logger_factory.hpp"
#include "error_logger_factory.hpp"
int main() {
ILoggerFactory* loggerFactory1 = new InfoLoggerFactory;
ILogger* infoLogger = loggerFactory1->createLogger();
ILoggerFactory* loggerFactory2 = new ErrorLoggerFactory;
ILogger* errorLogger = loggerFactory2->createLogger();
ILoggerFactory* loggerFactory3 = new DebugLoggerFactory;
ILogger* debugLogger = loggerFactory3->createLogger();
debugLogger->log("This is a debug log msg");
infoLogger->log("This is an info log msg");
errorLogger->log("This is an error log msg");
delete debugLogger;
delete infoLogger;
delete errorLogger;
return 0;
}
================================================
FILE: Factory Method Design Pattern/Logger/JAVA/LoggerDemo.java
================================================
interface ILogger {
void log(String msg);
}
class DebugLogger implements ILogger {
@Override
public void log(String msg) {
System.out.println("DEBUG : " + msg);
}
}
class ErrorLogger implements ILogger {
@Override
public void log(String msg) {
System.out.println("ERROR : " + msg);
}
}
class InfoLogger implements ILogger {
@Override
public void log(String msg) {
System.out.println("INFO : " + msg);
}
}
interface LoggerFactory {
ILogger createLogger();
}
class DebugLoggerFactory implements LoggerFactory {
@Override
public ILogger createLogger() {
return new DebugLogger();
}
}
class ErrorLoggerFactory implements LoggerFactory {
@Override
public ILogger createLogger() {
return new ErrorLogger();
}
}
class InfoLoggerFactory implements LoggerFactory {
@Override
public ILogger createLogger() {
return new InfoLogger();
}
}
public class LoggerDemo {
public static void main(String[] args) {
LoggerFactory loggerFactory = new InfoLoggerFactory();
ILogger logger = loggerFactory.createLogger();
logger.log("This is an info log message");
}
}
================================================
FILE: Iterator Design Pattern/C++/amazon_inventory.cpp
================================================
#include <iostream>
using namespace std;
// Product class representing individual products
class Product {
private:
string name;
double price;
public:
Product(const string& name, const double& price) : name(name), price(price) {}
const string& getName() const {
return name;
}
double getPrice() const {
return price;
}
};
// Iterator interface
class Iterator {
public:
virtual ~Iterator() {}
virtual Product* first() = 0;
virtual Product* next() = 0;
virtual bool hasNext() = 0;
};
// Concrete iterator for the product collection
class ProductIterator : public Iterator {
private:
vector<Product*>& products;
size_t current;
public:
ProductIterator(vector<Product*>& products) : products(products), current(0) {}
Product* first() {
if (products.empty()) {
return nullptr;
}
current = 0;
return products[current];
}
Product* next() {
if (hasNext()) {
return products[++current];
}
return nullptr;
}
bool hasNext() {
return current < products.size();
}
};
// Aggregate class that stores products and provides an iterator
class Inventory {
private:
vector<Product*> products;
public:
void addProduct(Product* product) {
products.push_back(product);
}
Iterator* createIterator() {
return new ProductIterator(products);
}
};
int main() {
// Create some products
Product product1("Laptop", 99999.99);
Product product2("Smartphone", 49999.99);
Product product3("Headphones", 7999.99);
// Create an inventory and add products
Inventory inventory;
inventory.addProduct(&product1);
inventory.addProduct(&product2);
inventory.addProduct(&product3);
// Create an iterator and iterate over the products
Iterator* iterator = inventory.createIterator();
Product* currentProduct = iterator->first();
while (currentProduct) {
cout << "Product: " << currentProduct->getName() <<
", Price: $" << currentProduct->getPrice() << std::endl;
currentProduct = iterator->next();
}
delete iterator;
return 0;
}
================================================
FILE: Iterator Design Pattern/JAVA/AmazonInventory.java
================================================
import java.util.*;
// Product class representing individual products
class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
// Iterator interface
interface Iterator {
Product first();
Product next();
boolean hasNext();
}
// Concrete iterator for the product collection
class ProductIterator implements Iterator {
private List<Product> products;
private int current;
public ProductIterator(List<Product> products) {
this.products = products;
this.current = 0;
}
public Product first() {
if (products.isEmpty()) {
return null;
}
current = 0;
return products.get(current);
}
public Product next() {
if (hasNext()) {
return products.get(++current);
}
return null;
}
public boolean hasNext() {
return current < products.size() - 1;
}
}
// Aggregate class that stores products and provides an iterator
class Inventory {
private List<Product> products = new ArrayList<>();
public void addProduct(Product product) {
products.add(product);
}
public Iterator createIterator() {
return new ProductIterator(products);
}
}
public class AmazonInventory {
public static void main(String[] args) {
// Create some products
Product product1 = new Product("Laptop", 99999.99);
Product product2 = new Product("Smartphone", 49999.99);
Product product3 = new Product("Headphones", 7999.99);
// Create an inventory and add products
Inventory inventory = new Inventory();
inventory.addProduct(product1);
inventory.addProduct(product2);
inventory.addProduct(product3);
// Create an iterator and iterate over the products
Iterator iterator = inventory.createIterator();
Product currentProduct = iterator.first();
while (currentProduct != null) {
System.out.println("Product: " + currentProduct.getName() + ", Price: $" + currentProduct.getPrice());
currentProduct = iterator.next();
}
}
}
================================================
FILE: Observer Design Pattern/C++/order_status.cpp
================================================
#include <iostream>
using namespace std;
class Order;
// Observer interface
class Observer
{
public:
virtual void update(Order *order) = 0;
};
// Concrete Observer: Customer
class Customer : public Observer
{
private:
string name;
public:
Customer(string name) : name(name) {}
void update(Order *order);
};
// Concrete Observer: Restaurant
class Restaurant : public Observer
{
private:
string restaurantName;
public:
Restaurant(string name) : restaurantName(name) {}
void update(Order *order);
};
// Concrete Observer: DeliveryDriver
class DeliveryDriver : public Observer
{
private:
string driverName;
public:
DeliveryDriver(string name) : driverName(name) {}
void update(Order *order);
};
// Concrete Observer: CallCenter
class CallCenter : public Observer
{
public:
void update(Order *order);
};
// Subject: Order
class Order
{
private:
int id;
string status;
vector<Observer *> observers;
public:
Order(int id) : id(id), status("Order Placed") {}
int getId()
{
return id;
}
string getStatus()
{
return status;
}
void setStatus(string newStatus)
{
status = newStatus;
notifyObservers();
}
void attach(Observer *observer)
{
observers.push_back(observer);
}
void detach(Observer *observer)
{
for (auto it = observers.begin(); it != observers.end(); ++it)
{
if (*it == observer)
{
observers.erase(it);
break; // Assuming each observer can be attached only once
}
}
}
void notifyObservers()
{
for (Observer *observer : observers)
{
observer->update(this);
}
}
};
void Customer::update(Order *order)
{
cout << "Hello, " << name << "! Order #" << order->getId() << " is now " << order->getStatus() << endl;
}
void Restaurant::update(Order *order)
{
cout << "Restaurant " << restaurantName << ": Order #" << order->getId() << " is now " << order->getStatus() << endl;
}
void DeliveryDriver::update(Order *order)
{
cout << "Driver " << driverName << ": Order #" << order->getId() << " is now " << order->getStatus() << endl;
}
void CallCenter::update(Order *order)
{
cout << "Call center: Order #" << order->getId() << " is now " << order->getStatus() << endl;
}
int main()
{
// Create an order
Order order1(123);
// Create customers, restaurants, drivers, and a call center to track the order
Customer customer1("Customer 1");
Restaurant restaurant1("Rest 1");
DeliveryDriver driver1("Driver 1");
CallCenter callCenter;
// Attach observers to the order
order1.attach(&customer1);
order1.attach(&restaurant1);
order1.attach(&driver1);
order1.attach(&callCenter);
// Simulate order status updates
order1.setStatus("Out for Delivery");
// Detach an observer (if needed)
order1.detach(&callCenter);
// Simulate more order status updates
order1.setStatus("Delivered");
return 0;
}
================================================
FILE: Observer Design Pattern/JAVA/OrderStatus.java
================================================
import java.util.*;
interface Observer {
void update(Order order);
}
class Customer implements Observer {
private String name;
public Customer(String name) {
this.name = name;
}
@Override
public void update(Order order) {
System.out.println("Hello, " + name + "! Order #" + order.getId() + " is now " + order.getStatus() + ".");
}
}
class Restaurant implements Observer {
private String restaurantName;
public Restaurant(String name) {
this.restaurantName = name;
}
@Override
public void update(Order order) {
System.out.println("Restaurant " + restaurantName + ": Order #" + order.getId() + " is now " + order.getStatus() + ".");
}
}
class DeliveryDriver implements Observer {
private String driverName;
public DeliveryDriver(String name) {
this.driverName = name;
}
@Override
public void update(Order order) {
System.out.println("Driver " + driverName + ": Order #" + order.getId() + " is now " + order.getStatus() + ".");
}
}
class CallCenter implements Observer {
@Override
public void update(Order order) {
System.out.println("Call center: Order #" + order.getId() + " is now " + order.getStatus() + ".");
}
}
class Order {
private int id;
private String status;
private List<Observer> observers = new ArrayList<>();
public Order(int id) {
this.id = id;
this.status = "Order Placed";
}
public int getId() {
return id;
}
public String getStatus() {
return status;
}
public void setStatus(String newStatus) {
status = newStatus;
notifyObservers();
}
public void attach(Observer observer) {
observers.add(observer);
}
public void detach(Observer observer) {
observers.remove(observer);
}
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(this);
}
}
}
public class OrderStatus {
public static void main(String[] args) {
// Create an order
Order order1 = new Order(123);
// Create customers, restaurants, drivers, and a call center to track the order
Customer customer1 = new Customer("Customer 1");
Restaurant restaurant1 = new Restaurant("Rest 1");
DeliveryDriver driver1 = new DeliveryDriver("Driver 1");
CallCenter callCenter = new CallCenter();
// Attach observers to the order
order1.attach(customer1);
order1.attach(restaurant1);
order1.attach(driver1);
order1.attach(callCenter);
// Simulate order status updates
order1.setStatus("Out for Delivery");
// Detach an observer (if needed)
order1.detach(callCenter);
// Simulate more order status updates
order1.setStatus("Delivered");
}
}
================================================
FILE: Prototype Design Pattern/C++/product.cpp
================================================
#include <iostream>
using namespace std;
// Abstract base class representing a prototype for products
class ProductPrototype {
public:
virtual ProductPrototype* clone() = 0;
virtual void display() = 0;
virtual ~ProductPrototype() {}
};
// Concrete prototype class representing a product
class Product : public ProductPrototype {
private:
string name;
double price;
public:
Product(const string& name, double price)
: name(name), price(price) {}
ProductPrototype* clone() override {
return new Product(*this); // Copy constructor used for cloning
}
void display() override {
cout << "Product: " << name << endl;
cout << "Price: $" << price << endl;
}
};
int main() {
// Create prototype instances of products
ProductPrototype* product1 = new Product("Laptop", 999.99);
ProductPrototype* product2 = new Product("Smartphone", 499.99);
// Clone the prototypes to create new product instances
ProductPrototype* newProduct1 = product1->clone();
ProductPrototype* newProduct2 = product2->clone();
// Display product details
cout << "Original Products:\n";
product1->display();
product2->display();
cout << "\nCloned Products:\n";
newProduct1->display();
newProduct2->display();
// Clean up
delete product1;
delete product2;
delete newProduct1;
delete newProduct2;
return 0;
}
================================================
FILE: Prototype Design Pattern/C++/router.cpp
================================================
#include <iostream>
using namespace std;
class NetworkDevice {
public:
virtual NetworkDevice* clone() const = 0;
virtual void display() const = 0;
virtual void update(string newName) = 0; // Update the device's name
};
class Router : public NetworkDevice {
public:
Router(string name, string ip, string securityPolicy)
: name(move(name)), ip(move(ip)), securityPolicy(move(securityPolicy)) {}
NetworkDevice* clone() const override {
return new Router(*this);
}
void display() const override {
cout << "Router - Name: " << name << ", IP: " << ip << ", Security Policy: " << securityPolicy << endl;
}
void update(string newName) override {
name = move(newName);
}
private:
string name;
string ip;
string securityPolicy;
};
class Switch : public NetworkDevice {
public:
Switch(string name, string protocol)
: name(move(name)), protocol(move(protocol)) {}
NetworkDevice* clone() const override {
return new Switch(*this);
}
void display() const override {
cout << "Switch - Name: " << name << ", Protocol: " << protocol << endl;
}
void update(string newName) override {
name = move(newName);
}
private:
string name;
string protocol;
};
int main() {
// Create prototype instances of a router and a switch
NetworkDevice* routerPrototype = new Router("Router A", "192.168.1.1", "Firewall Enabled");
NetworkDevice* switchPrototype = new Switch("Switch X", "Ethernet");
// Clone and display router and switch devices
NetworkDevice* routerClone = routerPrototype->clone();
NetworkDevice* switchClone = switchPrototype->clone();
cout << "Router Clone:" << endl;
routerClone->display();
cout << "\nSwitch Clone:" << endl;
switchClone->display();
// Update the names of the clones
routerClone->update("Router B");
switchClone->update("Switch Y");
cout << "\nUpdated Router Clone:" << endl;
routerClone->display();
cout << "\nUpdated Switch Clone:" << endl;
switchClone->display();
// Clean up
delete routerPrototype;
delete switchPrototype;
delete routerClone;
delete switchClone;
return 0;
}
================================================
FILE: Prototype Design Pattern/JAVA/ProductDemo.java
================================================
// Abstract base class representing a prototype for products
abstract class ProductPrototype {
public abstract ProductPrototype clone();
public abstract void display();
}
// Concrete prototype class representing a product
class Product extends ProductPrototype {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public ProductPrototype clone() {
return new Product(name, price);
}
@Override
public void display() {
System.out.println("Product: " + name);
System.out.println("Price: $" + price);
}
}
public class ProductDemo {
public static void main(String[] args) {
// Create prototype instances of products
ProductPrototype product1 = new Product("Laptop", 999.99);
ProductPrototype product2 = new Product("Smartphone", 499.99);
// Clone the prototypes to create new product instances
ProductPrototype newProduct1 = product1.clone();
ProductPrototype newProduct2 = product2.clone();
System.out.println("Original Products:");
product1.display();
product2.display();
System.out.println("\nCloned Products:");
newProduct1.display();
newProduct2.display();
}
}
================================================
FILE: Prototype Design Pattern/JAVA/RouterDemo.java
================================================
abstract class NetworkDevice {
public abstract NetworkDevice clone();
public abstract void display();
public abstract void update(String newName);
}
class Router extends NetworkDevice {
private String name;
private String ip;
private String securityPolicy;
public Router(String name, String ip, String securityPolicy) {
this.name = name;
this.ip = ip;
this.securityPolicy = securityPolicy;
}
@Override
public NetworkDevice clone() {
return new Router(name, ip, securityPolicy);
}
@Override
public void display() {
System.out.println("Router - Name: " + name + ", IP: " + ip + ", Security Policy: " + securityPolicy);
}
@Override
public void update(String newName) {
name = newName;
}
}
class Switch extends NetworkDevice {
private String name;
private String protocol;
public Switch(String name, String protocol) {
this.name = name;
this.protocol = protocol;
}
@Override
public NetworkDevice clone() {
return new Switch(name, protocol);
}
@Override
public void display() {
System.out.println("Switch - Name: " + name + ", Protocol: " + protocol);
}
@Override
public void update(String newName) {
name = newName;
}
}
public class RouterDemo {
public static void main(String[] args) {
// Create prototype instances of a router and a switch
NetworkDevice routerPrototype = new Router("Router A", "192.168.1.1", "Firewall Enabled");
NetworkDevice switchPrototype = new Switch("Switch X", "Ethernet");
// Clone and display router and switch devices
NetworkDevice routerClone = routerPrototype.clone();
NetworkDevice switchClone = switchPrototype.clone();
System.out.println("Router Clone:");
routerClone.display();
System.out.println("\nSwitch Clone:");
switchClone.display();
// Update the names of the clones
routerClone.update("Router B");
switchClone.update("Switch Y");
System.out.println("\nUpdated Router Clone:");
routerClone.display();
System.out.println("\nUpdated Switch Clone:");
switchClone.display();
}
}
================================================
FILE: Proxy Design Pattern/C++/image.cpp
================================================
#include <iostream>
using namespace std;
// The Subject interface represents the Image.
class Image {
public:
virtual void display() = 0;
};
// The RealImage is the actual implementation of the Image.
class RealImage : public Image {
private:
string filename;
public:
RealImage(const string& filename) : filename(filename) {
loadFromDisk();
}
void display() {
cout << "Displaying image: " << filename << endl;
}
void loadFromDisk() {
cout << "Loading image from disk: " << filename << endl;
}
};
// The ImageProxy is the proxy class that loads and displays high-resolution images on-demand.
class ImageProxy : public Image {
private:
RealImage* realImage;
string filename;
public:
ImageProxy(const string& filename) : filename(filename), realImage(nullptr) {}
void display() {
if (!realImage) {
realImage = new RealImage(filename);
}
realImage->display();
}
~ImageProxy() {
if (realImage) {
delete realImage;
}
}
};
int main() {
// Create an ImageProxy for a high-resolution image.
ImageProxy proxy("high_res_image.jpg");
// Display the image (loading it on-demand).
proxy.display();
// The image is not loaded again if we display it multiple times.
proxy.display();
return 0;
}
================================================
FILE: Proxy Design Pattern/JAVA/ImageDemo.java
================================================
interface Image {
void display();
}
class RealImage implements Image {
private String filename;
public RealImage(String filename) {
this.filename = filename;
loadFromDisk();
}
@Override
public void display() {
System.out.println("Displaying image: " + filename);
}
private void loadFromDisk() {
System.out.println("Loading image from disk: " + filename);
}
}
class ImageProxy implements Image {
private RealImage realImage;
private String filename;
public ImageProxy(String filename) {
this.filename = filename;
this.realImage = null;
}
@Override
public void display() {
if (realImage == null) {
realImage = new RealImage(filename);
}
realImage.display();
}
}
public class ImageDemo {
public static void main(String[] args) {
// Create an ImageProxy for a high-resolution image.
Image proxy = new ImageProxy("high_res_image.jpg");
// Display the image (loading it on-demand).
proxy.display();
// The image is not loaded again if we display it multiple times.
proxy.display();
}
}
================================================
FILE: Simple Factory Design Pattern/C++/common.hpp
================================================
#pragma once
#include <iostream>
using namespace std;
enum class LogLevel {
DEBUG,
INFO,
ERROR
};
================================================
FILE: Simple Factory Design Pattern/C++/debug_logger.cpp
================================================
#include "debug_logger.hpp"
void DebugLogger::log(const string &msg)
{
cout << "DEBUG : " << msg << endl;
}
================================================
FILE: Simple Factory Design Pattern/C++/debug_logger.hpp
================================================
#pragma once
#include "ilogger.hpp"
class DebugLogger : public ILogger {
public:
void log(const string& msg);
};
================================================
FILE: Simple Factory Design Pattern/C++/error_logger.cpp
================================================
#include "error_logger.hpp"
void ErrorLogger::log(const string& msg) {
cout<<"ERROR : "<<msg<<endl;
}
================================================
FILE: Simple Factory Design Pattern/C++/error_logger.hpp
================================================
#pragma once
#include "ilogger.hpp"
class ErrorLogger : public ILogger{
public:
void log(const string& msg);
};
================================================
FILE: Simple Factory Design Pattern/C++/ilogger.hpp
================================================
#pragma once
#include "common.hpp"
class ILogger {
public:
virtual void log(const string& msg) = 0;
virtual ~ILogger() {}
};
================================================
FILE: Simple Factory Design Pattern/C++/info_logger.cpp
================================================
#include "info_logger.hpp"
void InfoLogger::log(const string& msg) {
cout<<"INFO : "<<msg<<endl;
}
================================================
FILE: Simple Factory Design Pattern/C++/info_logger.hpp
================================================
#pragma once
#include "ilogger.hpp"
class InfoLogger : public ILogger {
public:
void log(const string& msg);
};
================================================
FILE: Simple Factory Design Pattern/C++/logger_factory.cpp
================================================
#include "logger_factory.hpp"
ILogger* LoggerFactory::createLogger(LogLevel pLogLevel) {
if(pLogLevel == LogLevel::DEBUG)
return new DebugLogger();
if(pLogLevel == LogLevel::INFO)
return new InfoLogger();
if(pLogLevel == LogLevel::ERROR)
return new ErrorLogger();
return nullptr;
}
================================================
FILE: Simple Factory Design Pattern/C++/logger_factory.hpp
================================================
#pragma once
#include "ilogger.hpp"
#include "debug_logger.hpp"
#include "info_logger.hpp"
#include "error_logger.hpp"
class LoggerFactory {
public:
static ILogger* createLogger(LogLevel pLogLevel);
};
================================================
FILE: Simple Factory Design Pattern/C++/main.cpp
================================================
#include "logger_factory.hpp"
int main() {
ILogger* debugLogger = LoggerFactory::createLogger(LogLevel::DEBUG);
ILogger* infoLogger = LoggerFactory::createLogger(LogLevel::INFO);
ILogger* errorLogger = LoggerFactory::createLogger(LogLevel::ERROR);
debugLogger->log("This is a debug log msg");
infoLogger->log("This is an info log msg");
errorLogger->log("This is an error log msg");
delete debugLogger;
delete infoLogger;
delete errorLogger;
return 0;
}
================================================
FILE: Simple Factory Design Pattern/JAVA/Main.java
================================================
import logger.*;
public class Main {
public static void main(String[] args) {
ILogger debugLogger = LoggerFactory.createLogger(LogLevel.DEBUG);
ILogger infoLogger = LoggerFactory.createLogger(LogLevel.INFO);
ILogger errorLogger = LoggerFactory.createLogger(LogLevel.ERROR);
debugLogger.log("This is a debug log msg");
infoLogger.log("This is an info log msg");
errorLogger.log("This is an error log msg");
}
}
================================================
FILE: Simple Factory Design Pattern/JAVA/logger/DebugLogger.java
================================================
package logger;
public class DebugLogger implements ILogger {
public void log(String msg) {
System.out.println("DEBUG: " + msg);
}
}
================================================
FILE: Simple Factory Design Pattern/JAVA/logger/ErrorLogger.java
================================================
package logger;
public class ErrorLogger implements ILogger {
public void log(String msg) {
System.out.println("ERROR: " + msg);
}
}
================================================
FILE: Simple Factory Design Pattern/JAVA/logger/ILogger.java
================================================
package logger;
public interface ILogger {
void log (String msg);
}
================================================
FILE: Simple Factory Design Pattern/JAVA/logger/InfoLogger.java
================================================
package logger;
public class InfoLogger implements ILogger {
public void log(String msg) {
System.out.println("INFO: " + msg);
}
}
================================================
FILE: Simple Factory Design Pattern/JAVA/logger/LogLevel.java
================================================
package logger;
public enum LogLevel {
DEBUG, INFO, ERROR
}
================================================
FILE: Simple Factory Design Pattern/JAVA/logger/LoggerFactory.java
================================================
package logger;
public class LoggerFactory {
public static ILogger createLogger(LogLevel logLevel) {
switch(logLevel) {
case DEBUG:
return new DebugLogger();
case INFO:
return new InfoLogger();
case ERROR:
return new ErrorLogger();
default:
return null;
}
}
}
================================================
FILE: Singleton Design Pattern/C++/payment_gateway.cpp
================================================
#include <iostream>
using namespace std;
class PaymentGatewayManager
{
private:
PaymentGatewayManager()
{
cout << "Payment Gateway Manager initialized." << endl;
}
static PaymentGatewayManager *instance;
static mutex mtx;
public:
static PaymentGatewayManager *getInstance()
{
if (instance == nullptr)
{
mtx.lock();
if (instance == nullptr)
{
instance = new PaymentGatewayManager();
}
mtx.unlock();
}
return instance;
}
void processPayment(double amount)
{
cout << "Processing payment of $" << amount << " through the payment gateway." << endl;
}
};
PaymentGatewayManager *PaymentGatewayManager::instance = nullptr;
mutex PaymentGatewayManager::mtx;
int main()
{
PaymentGatewayManager *paymentGateway = PaymentGatewayManager::getInstance();
paymentGateway->processPayment(100.0);
// Attempt to create another instance (should return the existing instance)
PaymentGatewayManager *anotherPaymentGateway = PaymentGatewayManager::getInstance();
// Check if both instances are the same.
if (paymentGateway == anotherPaymentGateway)
{
cout << "Both instances are the same. Singleton pattern is working" << endl;
}
else
{
cout << "Singleton pattern is not working correctly" << endl;
}
return 0;
}
================================================
FILE: Singleton Design Pattern/JAVA/PaymentGateway.java
================================================
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class PaymentGatewayManager {
private PaymentGatewayManager() {
System.out.println("Payment Gateway Manager initialized.");
}
private static PaymentGatewayManager instance;
private static Lock mtx = new ReentrantLock();
public static PaymentGatewayManager getInstance() {
if (instance == null) { // First check without locking
mtx.lock(); // Acquire the lock before creating the instance
try {
if (instance == null) { // Double-checked locking
instance = new PaymentGatewayManager();
}
} finally {
mtx.unlock(); // Always release the lock
}
}
return instance;
}
public void processPayment(double amount) {
System.out.println("Processing payment of $" + amount + " through the payment gateway.");
}
}
public class PaymentGateway {
public static void main(String[] args) {
PaymentGatewayManager paymentGateway = PaymentGatewayManager.getInstance();
paymentGateway.processPayment(100.0);
// Attempt to create another instance (should return the existing instance)
PaymentGatewayManager anotherPaymentGateway = PaymentGatewayManager.getInstance();
// Check if both instances are the same.
if (paymentGateway == anotherPaymentGateway) {
System.out.println("Both instances are the same. Singleton pattern is working.");
} else {
System.out.println("Singleton pattern is not working correctly.");
}
}
}
================================================
FILE: State Design Pattern/C++/state.cpp
================================================
#include <iostream>
using namespace std;
// Define the RideState interface.
class RideState {
public:
virtual void handleRequest() = 0;
virtual void handleCancel() = 0;
};
// Implement concrete states.
class RideRequestedState : public RideState {
public:
void handleRequest() override {
cout << "Ride has been requested." << endl;
}
void handleCancel() override {
cout << "Ride request has been canceled." << endl;
}
};
class DriverAssignedState : public RideState {
public:
void handleRequest() override {
cout << "Ride is already assigned to a driver." << endl;
}
void handleCancel() override {
cout << "Ride request has been canceled. The driver is notified." << endl;
}
};
class EnRouteState : public RideState {
public:
void handleRequest() override {
cout << "Ride is already en route." << endl;
}
void handleCancel() override {
cout << "Ride request cannot be canceled while en route." << endl;
}
};
// Context
class Ride {
private:
RideState* state;
public:
Ride() {
// Initial state is RideRequestedState.
state = new RideRequestedState();
}
void setState(RideState* newState) {
delete state;
state = newState;
}
void requestRide() {
state->handleRequest();
}
void cancelRide() {
state->handleCancel();
}
};
int main() {
Ride ride;
ride.requestRide(); // Output: Ride has been requested.
ride.cancelRide(); // Output: Ride request has been canceled.
cout<<"--------------------------------------------------"<<endl;
cout<<"Setting state to Driver Assigned."<<endl;
ride.setState(new DriverAssignedState());
ride.requestRide(); // Output: Ride is already assigned to a driver.
ride.cancelRide(); // Output: Ride request has been canceled. The driver is notified.
cout<<"--------------------------------------------------"<<endl;
cout<<"Setting state to EnRoute."<<endl;
ride.setState(new EnRouteState());
ride.requestRide(); // Output: Ride is already en route.
ride.cancelRide(); // Output: Ride request cannot be canceled while en route.
return 0;
}
================================================
FILE: State Design Pattern/JAVA/StateDemo.java
================================================
// Define the RideState interface.
interface RideState {
void handleRequest();
void handleCancel();
}
// Implement concrete states.
class RideRequestedState implements RideState {
@Override
public void handleRequest() {
System.out.println("Ride has been requested.");
}
@Override
public void handleCancel() {
System.out.println("Ride request has been canceled.");
}
}
class DriverAssignedState implements RideState {
@Override
public void handleRequest() {
System.out.println("Ride is already assigned to a driver.");
}
@Override
public void handleCancel() {
System.out.println("Ride request has been canceled. The driver is notified.");
}
}
class EnRouteState implements RideState {
@Override
public void handleRequest() {
System.out.println("Ride is already en route.");
}
@Override
public void handleCancel() {
System.out.println("Ride request cannot be canceled while en route.");
}
}
// Context
class Ride {
private RideState state;
public Ride() {
// Initial state is RideRequestedState.
state = new RideRequestedState();
}
public void setState(RideState newState) {
state = newState;
}
public void requestRide() {
state.handleRequest();
}
public void cancelRide() {
state.handleCancel();
}
}
public class StateDemo {
public static void main(String[] args) {
Ride ride = new Ride();
ride.requestRide(); // Output: Ride has been requested.
ride.cancelRide(); // Output: Ride request has been canceled.
System.out.println("--------------------------------------------------");
System.out.println("Setting state to Driver Assigned.");
ride.setState(new DriverAssignedState());
ride.requestRide(); // Output: Ride is already assigned to a driver.
ride.cancelRide(); // Output: Ride request has been canceled. The driver is notified.
System.out.println("--------------------------------------------------");
System.out.println("Setting state to EnRoute.");
ride.setState(new EnRouteState());
ride.requestRide(); // Output: Ride is already en route.
ride.cancelRide(); // Output: Ride request cannot be canceled while en route.
}
}
================================================
FILE: Strategy Design Pattern/C++/payment.cpp
================================================
#include <iostream>
using namespace std;
class PaymentStrategy {
public:
virtual void processPayment(double amount) = 0;
virtual ~PaymentStrategy() {}
};
class CreditCardPayment : public PaymentStrategy {
public:
void processPayment(double amount) override {
cout << "Processing credit card payment of $" << amount << endl;
}
};
class PayPalPayment : public PaymentStrategy {
public:
void processPayment(double amount) override {
cout << "Processing PayPal payment of $" << amount << endl;
}
};
class CryptocurrencyPayment : public PaymentStrategy {
public:
void processPayment(double amount) override {
cout << "Processing cryptocurrency payment of $" << amount << endl;
}
};
class PaymentProcessor {
private:
PaymentStrategy* paymentStrategy;
public:
PaymentProcessor() : paymentStrategy(nullptr) {}
void setPaymentStrategy(PaymentStrategy* strategy) {
paymentStrategy = strategy;
}
void processPayment(double amount) {
if (paymentStrategy) {
paymentStrategy->processPayment(amount);
} else {
cerr << "Payment strategy not set." << endl;
}
}
~PaymentProcessor() {
if (paymentStrategy) {
delete paymentStrategy; // Clean up the strategy instance
}
}
};
int main() {
PaymentProcessor processor;
// Select and set the payment strategy at runtime
PaymentStrategy* strategy = new CreditCardPayment();
processor.setPaymentStrategy(strategy);
// Process the payment
processor.processPayment(100.0);
// Change the payment strategy
delete strategy; // Clean up the previous strategy
strategy = new PayPalPayment();
processor.setPaymentStrategy(strategy);
// Process another payment using the new strategy
processor.processPayment(50.0);
// Clean up
delete strategy;
return 0;
}
================================================
FILE: Strategy Design Pattern/JAVA/PaymentDemo.java
================================================
// PaymentStrategy interface
interface PaymentStrategy {
void processPayment(double amount);
}
// Concrete PaymentStrategy classes
class CreditCardPayment implements PaymentStrategy {
public void processPayment(double amount) {
System.out.println("Processing credit card payment of $" + amount);
}
}
class PayPalPayment implements PaymentStrategy {
public void processPayment(double amount) {
System.out.println("Processing PayPal payment of $" + amount);
}
}
class CryptocurrencyPayment implements PaymentStrategy {
public void processPayment(double amount) {
System.out.println("Processing cryptocurrency payment of $" + amount);
}
}
// PaymentProcessor
class PaymentProcessor {
private PaymentStrategy paymentStrategy;
public PaymentProcessor() {
paymentStrategy = null;
}
public void setPaymentStrategy(PaymentStrategy strategy) {
if (paymentStrategy != null) {
// Clean up the previous strategy
paymentStrategy = null;
}
paymentStrategy = strategy;
}
public void processPayment(double amount) {
if (paymentStrategy != null) {
paymentStrategy.processPayment(amount);
} else {
System.err.println("Payment strategy not set.");
}
}
public void finalize() {
if (paymentStrategy != null) {
// Clean up the strategy instance
paymentStrategy = null;
}
}
}
public class PaymentDemo {
public static void main(String[] args) {
PaymentProcessor processor = new PaymentProcessor();
// Select and set the payment strategy at runtime
PaymentStrategy strategy = new CreditCardPayment();
processor.setPaymentStrategy(strategy);
// Process the payment
processor.processPayment(100.0);
// Change the payment strategy
strategy = new PayPalPayment();
processor.setPaymentStrategy(strategy);
// Process another payment using the new strategy
processor.processPayment(50.0);
}
}
================================================
FILE: Strategy and Factory Design Pattern/C++/payment.cpp
================================================
#include <iostream>
using namespace std;
// PaymentStrategy interface
class PaymentStrategy {
public:
virtual ~PaymentStrategy() {}
virtual void processPayment(double amount) = 0;
};
// Concrete PaymentStrategy classes
class CreditCardPayment : public PaymentStrategy {
public:
void processPayment(double amount) override {
cout << "Processing credit card payment of $" << amount << endl;
}
};
class PayPalPayment : public PaymentStrategy {
public:
void processPayment(double amount) override {
cout << "Processing PayPal payment of $" << amount << endl;
}
};
class CryptocurrencyPayment : public PaymentStrategy {
public:
void processPayment(double amount) override {
cout << "Processing cryptocurrency payment of $" << amount << endl;
}
};
// PaymentStrategyFactory
class PaymentStrategyFactory {
public:
static PaymentStrategy* createPaymentStrategy(const string& paymentMethod) {
if (paymentMethod == "CreditCard") {
return new CreditCardPayment();
} else if (paymentMethod == "PayPal") {
return new PayPalPayment();
} else if (paymentMethod == "Cryptocurrency") {
return new CryptocurrencyPayment();
} else {
//default
return new CreditCardPayment();
}
}
};
// PaymentProcessor
class PaymentProcessor {
private:
PaymentStrategy* paymentStrategy;
public:
PaymentProcessor() : paymentStrategy(nullptr) {}
void setPaymentStrategy(const string& paymentMethod) {
if (paymentStrategy) {
delete paymentStrategy; // Clean up the previous strategy
}
paymentStrategy = PaymentStrategyFactory::createPaymentStrategy(paymentMethod);
}
void processPayment(double amount) {
if (paymentStrategy) {
paymentStrategy->processPayment(amount);
} else {
cerr << "Payment strategy not set." << endl;
}
}
~PaymentProcessor() {
if (paymentStrategy) {
delete paymentStrategy; // Clean up the strategy instance
}
}
};
int main() {
PaymentProcessor processor;
// Use the factory to create payment strategies
processor.setPaymentStrategy("CreditCard");
processor.processPayment(100.0);
processor.setPaymentStrategy("PayPal");
processor.processPayment(50.0);
return 0;
}
================================================
FILE: Strategy and Factory Design Pattern/JAVA/PaymentDemo.java
================================================
// PaymentStrategy interface
interface PaymentStrategy {
void processPayment(double amount);
}
// Concrete PaymentStrategy classes
class CreditCardPayment implements PaymentStrategy {
public void processPayment(double amount) {
System.out.println("Processing credit card payment of $" + amount);
}
}
class PayPalPayment implements PaymentStrategy {
public void processPayment(double amount) {
System.out.println("Processing PayPal payment of $" + amount);
}
}
class CryptocurrencyPayment implements PaymentStrategy {
public void processPayment(double amount) {
System.out.println("Processing cryptocurrency payment of $" + amount);
}
}
// PaymentStrategyFactory
class PaymentStrategyFactory {
public static PaymentStrategy createPaymentStrategy(String paymentMethod) {
if (paymentMethod.equals("CreditCard")) {
return new CreditCardPayment();
} else if (paymentMethod.equals("PayPal")) {
return new PayPalPayment();
} else if (paymentMethod.equals("Cryptocurrency")) {
return new CryptocurrencyPayment();
} else {
// Default to CreditCardPayment
return new CreditCardPayment();
}
}
}
// PaymentProcessor
class PaymentProcessor {
private PaymentStrategy paymentStrategy;
public PaymentProcessor() {
paymentStrategy = null;
}
public void setPaymentStrategy(String paymentMethod) {
if (paymentStrategy != null) {
// Clean up the previous strategy
paymentStrategy = null;
}
paymentStrategy = PaymentStrategyFactory.createPaymentStrategy(paymentMethod);
}
public void processPayment(double amount) {
if (paymentStrategy != null) {
paymentStrategy.processPayment(amount);
} else {
System.err.println("Payment strategy not set.");
}
}
public void finalize() {
if (paymentStrategy != null) {
// Clean up the strategy instance
paymentStrategy = null;
}
}
}
public class PaymentDemo {
public static void main(String[] args) {
PaymentProcessor processor = new PaymentProcessor();
// Use the factory to create payment strategies
processor.setPaymentStrategy("CreditCard");
processor.processPayment(100.0);
processor.setPaymentStrategy("PayPal");
processor.processPayment(50.0);
}
}
================================================
FILE: Template Design Pattern/C++/amazon_order.cpp
================================================
#include <iostream>
using namespace std;
// Abstract class representing the template for order processing
class OrderProcessingTemplate {
public:
void processOrder() {
verifyOrder();
assignDeliveryAgent();
trackDelivery();
}
virtual void verifyOrder() = 0;
virtual void assignDeliveryAgent() = 0;
virtual void trackDelivery() = 0;
};
// Concrete subclass for processing orders from local restaurants
class LocalOrderProcessor : public OrderProcessingTemplate {
public:
void verifyOrder() {
cout << "Verifying local order..." << endl;
// Specific logic for verifying local orders
}
void assignDeliveryAgent() {
cout << "Assigning a local delivery agent..." << endl;
// Specific logic for assigning local delivery agents
}
void trackDelivery() {
cout << "Tracking local delivery..." << endl;
// Specific logic for tracking local deliveries
}
};
// Concrete subclass for processing orders from international restaurants
class InternationalOrderProcessor : public OrderProcessingTemplate {
public:
void verifyOrder() {
cout << "Verifying international order..." << endl;
// Specific logic for verifying international orders
}
void assignDeliveryAgent() {
cout << "Assigning an international delivery agent..." << endl;
// Specific logic for assigning international delivery agents
}
void trackDelivery() {
cout << "Tracking international delivery..." << endl;
// Specific logic for tracking international deliveries
}
};
int main() {
OrderProcessingTemplate* localOrder = new LocalOrderProcessor();
OrderProcessingTemplate* internationalOrder = new InternationalOrderProcessor();
cout << "Processing a local order:" << endl;
localOrder->processOrder();
cout << endl;
cout << "Processing an international order:" << endl;
internationalOrder->processOrder();
delete localOrder;
delete internationalOrder;
return 0;
}
================================================
FILE: Template Design Pattern/JAVA/AmazonOrderProcessor.java
================================================
// Abstract class representing the template for order processing
abstract class OrderProcessingTemplate {
public void processOrder() {
verifyOrder();
assignDeliveryAgent();
trackDelivery();
}
abstract void verifyOrder();
abstract void assignDeliveryAgent();
abstract void trackDelivery();
}
// Concrete subclass for processing orders from local restaurants
class LocalOrderProcessor extends OrderProcessingTemplate {
void verifyOrder() {
System.out.println("Verifying local order...");
// Specific logic for verifying local orders
}
void assignDeliveryAgent() {
System.out.println("Assigning a local delivery agent...");
// Specific logic for assigning local delivery agents
}
void trackDelivery() {
System.out.println("Tracking local delivery...");
// Specific logic for tracking local deliveries
}
}
// Concrete subclass for processing orders from international restaurants
class InternationalOrderProcessor extends OrderProcessingTemplate {
void verifyOrder() {
System.out.println("Verifying international order...");
// Specific logic for verifying international orders
}
void assignDeliveryAgent() {
System.out.println("Assigning an international delivery agent...");
// Specific logic for assigning international delivery agents
}
void trackDelivery() {
System.out.println("Tracking international delivery...");
// Specific logic for tracking international deliveries
}
}
public class AmazonOrderProcessor {
public static void main(String[] args) {
OrderProcessingTemplate localOrder = new LocalOrderProcessor();
OrderProcessingTemplate internationalOrder = new InternationalOrderProcessor();
System.out.println("Processing a local order:");
localOrder.processOrder();
System.out.println();
System.out.println("Processing an international order:");
internationalOrder.processOrder();
}
}
gitextract__e0g9rmv/
├── .gitignore
├── Abstract Factory Design Pattern/
│ ├── Furniture /
│ │ ├── C++/
│ │ │ ├── furniture
│ │ │ └── furniture.cpp
│ │ ├── JAVA/
│ │ │ └── furniture.java
│ │ ├── Javascript/
│ │ │ └── furniture.js
│ │ └── Python/
│ │ └── furniture.py
│ └── UI/
│ ├── C++/
│ │ ├── ui
│ │ └── ui.cpp
│ └── JAVA/
│ └── UI.java
├── Adapter Design Pattern/
│ ├── Class Adapter/
│ │ └── C++/
│ │ └── xml_to_json.cpp
│ └── Object Adapter/
│ ├── C++/
│ │ └── xml_to_json.cpp
│ └── JAVA/
│ └── XmlToJson.java
├── Bridge Design Pattern/
│ ├── C++/
│ │ └── uber.cpp
│ └── JAVA/
│ └── UberDemo.java
├── Builder Design Pattern/
│ ├── Builder with Chaining/
│ │ ├── C++/
│ │ │ ├── desktop
│ │ │ └── desktop.cpp
│ │ └── JAVA/
│ │ └── DesktopBuilderDemo.java
│ ├── C++/
│ │ ├── desktop
│ │ └── desktop.cpp
│ └── JAVA/
│ └── DesktopBuilderDemo.java
├── Chain of Responsibility Design Pattern/
│ ├── C++/
│ │ └── swiggy_order.cpp
│ └── JAVA/
│ └── SwiggyOrder.java
├── Command Design Pattern/
│ ├── C++/
│ │ ├── document.cpp
│ │ └── uber_rides.cpp
│ └── JAVA/
│ ├── DocumentDemo.java
│ └── UberRidesDemo.java
├── Composite Design Pattern/
│ ├── C++/
│ │ ├── directorystructure.cpp
│ │ └── employee.cpp
│ └── JAVA/
│ ├── EmployeesDemo.java
│ └── directorystructure.java
├── Decorator Design Pattern/
│ ├── C++/
│ │ └── swiggy.cpp
│ └── JAVA/
│ └── Swiggy.java
├── Facade Design Pattern/
│ ├── C++/
│ │ └── computer.cpp
│ └── JAVA/
│ └── ComputerDemo.java
├── Factory Method Design Pattern/
│ ├── Furniture/
│ │ ├── C++/
│ │ │ └── furniture.cpp
│ │ ├── JAVA/
│ │ │ └── furniture.java
│ │ ├── Javascript/
│ │ │ └── furniture.js
│ │ └── Python/
│ │ └── furniture.py
│ └── Logger/
│ ├── C++/
│ │ ├── common.hpp
│ │ ├── debug_logger.cpp
│ │ ├── debug_logger.hpp
│ │ ├── debug_logger_factory.hpp
│ │ ├── error_logger.cpp
│ │ ├── error_logger.hpp
│ │ ├── error_logger_factory.hpp
│ │ ├── furniture
│ │ ├── ilogger.hpp
│ │ ├── info_logger.cpp
│ │ ├── info_logger.hpp
│ │ ├── info_logger_factory.hpp
│ │ ├── logger
│ │ ├── logger_factory.hpp
│ │ └── main.cpp
│ └── JAVA/
│ └── LoggerDemo.java
├── Iterator Design Pattern/
│ ├── C++/
│ │ └── amazon_inventory.cpp
│ └── JAVA/
│ └── AmazonInventory.java
├── Observer Design Pattern/
│ ├── C++/
│ │ └── order_status.cpp
│ └── JAVA/
│ └── OrderStatus.java
├── Prototype Design Pattern/
│ ├── C++/
│ │ ├── product
│ │ ├── product.cpp
│ │ ├── router
│ │ └── router.cpp
│ └── JAVA/
│ ├── ProductDemo.java
│ └── RouterDemo.java
├── Proxy Design Pattern/
│ ├── C++/
│ │ └── image.cpp
│ └── JAVA/
│ └── ImageDemo.java
├── Simple Factory Design Pattern/
│ ├── C++/
│ │ ├── common.hpp
│ │ ├── debug_logger.cpp
│ │ ├── debug_logger.hpp
│ │ ├── error_logger.cpp
│ │ ├── error_logger.hpp
│ │ ├── furniture
│ │ ├── ilogger.hpp
│ │ ├── info_logger.cpp
│ │ ├── info_logger.hpp
│ │ ├── logger
│ │ ├── logger_factory.cpp
│ │ ├── logger_factory.hpp
│ │ └── main.cpp
│ └── JAVA/
│ ├── Main.java
│ └── logger/
│ ├── DebugLogger.java
│ ├── ErrorLogger.java
│ ├── ILogger.java
│ ├── InfoLogger.java
│ ├── LogLevel.java
│ └── LoggerFactory.java
├── Singleton Design Pattern/
│ ├── C++/
│ │ ├── payment_gateway.cpp
│ │ └── pg
│ └── JAVA/
│ └── PaymentGateway.java
├── State Design Pattern/
│ ├── C++/
│ │ └── state.cpp
│ └── JAVA/
│ └── StateDemo.java
├── Strategy Design Pattern/
│ ├── C++/
│ │ └── payment.cpp
│ └── JAVA/
│ └── PaymentDemo.java
├── Strategy and Factory Design Pattern/
│ ├── C++/
│ │ └── payment.cpp
│ └── JAVA/
│ └── PaymentDemo.java
└── Template Design Pattern/
├── C++/
│ └── amazon_order.cpp
└── JAVA/
└── AmazonOrderProcessor.java
SYMBOL INDEX (945 symbols across 79 files)
FILE: Abstract Factory Design Pattern/Furniture /C++/furniture.cpp
class Sofa (line 4) | class Sofa {
class Chair (line 10) | class Chair {
class Table (line 16) | class Table {
class ModernSofa (line 22) | class ModernSofa : public Sofa {
method sitOn (line 24) | void sitOn() override {
class ModernChair (line 29) | class ModernChair : public Chair {
method sitOn (line 31) | void sitOn() override {
class ModernTable (line 36) | class ModernTable : public Table {
method place (line 38) | void place() override {
class TraditionalSofa (line 44) | class TraditionalSofa : public Sofa {
method sitOn (line 46) | void sitOn() override {
class TraditionalChair (line 51) | class TraditionalChair : public Chair {
method sitOn (line 53) | void sitOn() override {
class TraditionalTable (line 58) | class TraditionalTable : public Table {
method place (line 60) | void place() override {
class FurnitureFactory (line 66) | class FurnitureFactory {
method FurnitureFactory (line 72) | static FurnitureFactory* CreateFurnitureFactory(std::string type) {
class ModernFurnitureFactory (line 84) | class ModernFurnitureFactory : public FurnitureFactory {
method Sofa (line 86) | Sofa* createSofa() override {
method Chair (line 90) | Chair* createChair() override {
method Table (line 94) | Table* createTable() override {
class TraditionalFurnitureFactory (line 100) | class TraditionalFurnitureFactory : public FurnitureFactory {
method Sofa (line 102) | Sofa* createSofa() override {
method Chair (line 106) | Chair* createChair() override {
method Table (line 110) | Table* createTable() override {
function main (line 115) | int main() {
FILE: Abstract Factory Design Pattern/Furniture /JAVA/furniture.java
type Sofa (line 1) | interface Sofa {
method sitOn (line 2) | void sitOn();
type Chair (line 6) | interface Chair {
method sitOn (line 7) | void sitOn();
type Table (line 11) | interface Table {
method place (line 12) | void place();
class ModernSofa (line 16) | class ModernSofa implements Sofa {
method sitOn (line 17) | public void sitOn() {
class ModernChair (line 22) | class ModernChair implements Chair {
method sitOn (line 23) | public void sitOn() {
class ModernTable (line 28) | class ModernTable implements Table {
method place (line 29) | public void place() {
class TraditionalSofa (line 35) | class TraditionalSofa implements Sofa {
method sitOn (line 36) | public void sitOn() {
class TraditionalChair (line 41) | class TraditionalChair implements Chair {
method sitOn (line 42) | public void sitOn() {
class TraditionalTable (line 47) | class TraditionalTable implements Table {
method place (line 48) | public void place() {
type FurnitureFactory (line 54) | interface FurnitureFactory {
method createSofa (line 55) | Sofa createSofa();
method createChair (line 56) | Chair createChair();
method createTable (line 57) | Table createTable();
method createFurnitureFactory (line 59) | public static FurnitureFactory createFurnitureFactory(String type) {
class ModernFurnitureFactory (line 71) | class ModernFurnitureFactory implements FurnitureFactory {
method createSofa (line 72) | public Sofa createSofa() {
method createChair (line 76) | public Chair createChair() {
method createTable (line 80) | public Table createTable() {
class TraditionalFurnitureFactory (line 86) | class TraditionalFurnitureFactory implements FurnitureFactory {
method createSofa (line 87) | public Sofa createSofa() {
method createChair (line 91) | public Chair createChair() {
method createTable (line 95) | public Table createTable() {
class furniture (line 100) | public class furniture {
method main (line 101) | public static void main(String[] args) {
FILE: Abstract Factory Design Pattern/Furniture /Javascript/furniture.js
class Sofa (line 2) | class Sofa {
method sitOn (line 3) | sitOn() {}
class Chair (line 7) | class Chair {
method sitOn (line 8) | sitOn() {}
class Table (line 12) | class Table {
method place (line 13) | place() {}
class ModernSofa (line 17) | class ModernSofa extends Sofa {
method sitOn (line 18) | sitOn() {
class ModernChair (line 23) | class ModernChair extends Chair {
method sitOn (line 24) | sitOn() {
class ModernTable (line 29) | class ModernTable extends Table {
method place (line 30) | place() {
class TraditionalSofa (line 36) | class TraditionalSofa extends Sofa {
method sitOn (line 37) | sitOn() {
class TraditionalChair (line 42) | class TraditionalChair extends Chair {
method sitOn (line 43) | sitOn() {
class TraditionalTable (line 48) | class TraditionalTable extends Table {
method place (line 49) | place() {
class FurnitureFactory (line 55) | class FurnitureFactory {
method createSofa (line 56) | createSofa() {}
method createChair (line 57) | createChair() {}
method createTable (line 58) | createTable() {}
method createFurnitureFactory (line 60) | static createFurnitureFactory(type) {
class ModernFurnitureFactory (line 72) | class ModernFurnitureFactory extends FurnitureFactory {
method createSofa (line 73) | createSofa() {
method createChair (line 77) | createChair() {
method createTable (line 81) | createTable() {
class TraditionalFurnitureFactory (line 87) | class TraditionalFurnitureFactory extends FurnitureFactory {
method createSofa (line 88) | createSofa() {
method createChair (line 92) | createChair() {
method createTable (line 96) | createTable() {
function main (line 101) | function main() {
FILE: Abstract Factory Design Pattern/Furniture /Python/furniture.py
class Sofa (line 2) | class Sofa:
method sit_on (line 3) | def sit_on(self):
class Chair (line 7) | class Chair:
method sit_on (line 8) | def sit_on(self):
class Table (line 12) | class Table:
method place (line 13) | def place(self):
class ModernSofa (line 17) | class ModernSofa(Sofa):
method sit_on (line 18) | def sit_on(self):
class ModernChair (line 21) | class ModernChair(Chair):
method sit_on (line 22) | def sit_on(self):
class ModernTable (line 25) | class ModernTable(Table):
method place (line 26) | def place(self):
class TraditionalSofa (line 30) | class TraditionalSofa(Sofa):
method sit_on (line 31) | def sit_on(self):
class TraditionalChair (line 34) | class TraditionalChair(Chair):
method sit_on (line 35) | def sit_on(self):
class TraditionalTable (line 38) | class TraditionalTable(Table):
method place (line 39) | def place(self):
class FurnitureFactory (line 43) | class FurnitureFactory:
method create_sofa (line 44) | def create_sofa(self):
method create_chair (line 47) | def create_chair(self):
method create_table (line 50) | def create_table(self):
method create_furniture_factory (line 54) | def create_furniture_factory(type):
class ModernFurnitureFactory (line 63) | class ModernFurnitureFactory(FurnitureFactory):
method create_sofa (line 64) | def create_sofa(self):
method create_chair (line 67) | def create_chair(self):
method create_table (line 70) | def create_table(self):
class TraditionalFurnitureFactory (line 74) | class TraditionalFurnitureFactory(FurnitureFactory):
method create_sofa (line 75) | def create_sofa(self):
method create_chair (line 78) | def create_chair(self):
method create_table (line 81) | def create_table(self):
function main (line 84) | def main():
FILE: Abstract Factory Design Pattern/UI/C++/ui.cpp
class Ibutton (line 5) | class Ibutton{
class ITextbox (line 10) | class ITextbox{
class MacButton (line 16) | class MacButton : public Ibutton{
method press (line 18) | void press(){
class WinButton (line 24) | class WinButton : public Ibutton{
method press (line 26) | void press(){
class MacTextBox (line 32) | class MacTextBox : public ITextbox{
method settext (line 34) | void settext(){
class WinTextBox (line 40) | class WinTextBox : public ITextbox{
method settext (line 42) | void settext(){
class IFactory (line 48) | class IFactory{
class WinFactory (line 55) | class WinFactory : public IFactory{
method Ibutton (line 57) | Ibutton* createbutton(){
method ITextbox (line 60) | ITextbox* createtextbox(){
class MacFactory (line 66) | class MacFactory : public IFactory{
method Ibutton (line 68) | Ibutton* createbutton(){
method ITextbox (line 71) | ITextbox* createtextbox(){
class GUIAbstractfactory (line 77) | class GUIAbstractfactory{
method IFactory (line 79) | static IFactory* createfactory(string ostype){
function main (line 91) | int main(){
FILE: Abstract Factory Design Pattern/UI/JAVA/UI.java
type IButton (line 3) | interface IButton {
method press (line 4) | void press();
type ITextbox (line 7) | interface ITextbox {
method settext (line 8) | void settext();
class MacButton (line 11) | class MacButton implements IButton {
method press (line 12) | @Override
class WinButton (line 18) | class WinButton implements IButton {
method press (line 19) | @Override
class MacTextBox (line 25) | class MacTextBox implements ITextbox {
method settext (line 26) | @Override
class WinTextBox (line 32) | class WinTextBox implements ITextbox {
method settext (line 33) | @Override
type IFactory (line 39) | interface IFactory {
method createButton (line 40) | IButton createButton();
method createTextbox (line 41) | ITextbox createTextbox();
class WinFactory (line 44) | class WinFactory implements IFactory {
method createButton (line 45) | @Override
method createTextbox (line 50) | @Override
class MacFactory (line 56) | class MacFactory implements IFactory {
method createButton (line 57) | @Override
method createTextbox (line 62) | @Override
class GUIAbstractFactory (line 68) | class GUIAbstractFactory {
method createFactory (line 69) | public static IFactory createFactory(String osType) {
class UI (line 80) | public class UI {
method main (line 81) | public static void main(String[] args) {
FILE: Adapter Design Pattern/Class Adapter/C++/xml_to_json.cpp
class JSONAnalyticsTool (line 6) | class JSONAnalyticsTool
method setJsonData (line 11) | void setJsonData(string jsonData) {
method AnalyzeData (line 14) | void AnalyzeData()
class AnalyticsTool (line 26) | class AnalyticsTool {
class XMLToJSONAdapter (line 34) | class XMLToJSONAdapter : public AnalyticsTool, public JSONAnalyticsTool
method XMLToJSONAdapter (line 37) | XMLToJSONAdapter(string xmlData) {
method AnalyzeData (line 43) | void AnalyzeData()
function main (line 50) | int main()
FILE: Adapter Design Pattern/Object Adapter/C++/xml_to_json.cpp
class JSONAnalyticsTool (line 6) | class JSONAnalyticsTool
method setJsonData (line 11) | void setJsonData(string jsonData) {
method AnalyzeData (line 14) | void AnalyzeData()
class AnalyticsTool (line 26) | class AnalyticsTool {
class XMLToJSONAdapter (line 33) | class XMLToJSONAdapter : public AnalyticsTool
method XMLToJSONAdapter (line 39) | XMLToJSONAdapter(string xmlData) {
method AnalyzeData (line 45) | void AnalyzeData()
function main (line 52) | int main()
FILE: Adapter Design Pattern/Object Adapter/JAVA/XmlToJson.java
class JSONAnalyticsTool (line 1) | class JSONAnalyticsTool {
method setJsonData (line 4) | public void setJsonData(String jsonData) {
method AnalyzeData (line 8) | public void AnalyzeData() {
type AnalyticsTool (line 17) | interface AnalyticsTool {
method AnalyzeData (line 18) | void AnalyzeData();
class XMLToJSONAdapter (line 21) | class XMLToJSONAdapter implements AnalyticsTool {
method XMLToJSONAdapter (line 24) | public XMLToJSONAdapter(String xmlData) {
method AnalyzeData (line 31) | public void AnalyzeData() {
class XmlToJson (line 36) | public class XmlToJson {
method main (line 37) | public static void main(String[] args) {
FILE: Bridge Design Pattern/C++/uber.cpp
class NavigationImpl (line 6) | class NavigationImpl
class GoogleMaps (line 13) | class GoogleMaps : public NavigationImpl
method navigateTo (line 16) | void navigateTo(string destination)
class AppleMaps (line 24) | class AppleMaps : public NavigationImpl
method navigateTo (line 27) | void navigateTo(string destination)
class NavigationSystem (line 35) | class NavigationSystem
class UberRide (line 45) | class UberRide : public NavigationSystem
method UberRide (line 52) | UberRide(string driverName) : driverName(driverName) {}
method navigate (line 54) | void navigate(string destination)
method setNavigationImpl (line 60) | void setNavigationImpl(NavigationImpl *impl)
class UberEats (line 67) | class UberEats : public NavigationSystem
method UberEats (line 73) | UberEats(string restaurantName) : restaurantName(restaurantName) {}
method navigate (line 75) | void navigate(string destination)
method setNavigationImpl (line 81) | void setNavigationImpl(NavigationImpl *impl)
function main (line 87) | int main()
FILE: Bridge Design Pattern/JAVA/UberDemo.java
type NavigationImpl (line 2) | interface NavigationImpl {
method navigateTo (line 3) | void navigateTo(String destination);
type NavigationSystem (line 7) | interface NavigationSystem {
method navigate (line 8) | void navigate(String destination);
class UberRide (line 12) | class UberRide implements NavigationSystem {
method UberRide (line 16) | public UberRide(String driverName) {
method setNavigationImpl (line 20) | public void setNavigationImpl(NavigationImpl impl) {
method navigate (line 24) | public void navigate(String destination) {
class UberEats (line 31) | class UberEats implements NavigationSystem {
method UberEats (line 35) | public UberEats(String restaurantName) {
method setNavigationImpl (line 39) | public void setNavigationImpl(NavigationImpl impl) {
method navigate (line 43) | public void navigate(String destination) {
class GoogleMaps (line 50) | class GoogleMaps implements NavigationImpl {
method navigateTo (line 51) | public void navigateTo(String destination) {
class AppleMaps (line 58) | class AppleMaps implements NavigationImpl {
method navigateTo (line 59) | public void navigateTo(String destination) {
class UberDemo (line 65) | public class UberDemo {
method main (line 66) | public static void main(String[] args) {
FILE: Builder Design Pattern/Builder with Chaining/C++/desktop.cpp
class Desktop (line 5) | class Desktop
method display (line 14) | void display()
class DesktopBuilder (line 25) | class DesktopBuilder
method Desktop (line 37) | Desktop build()
class DellDesktopBuilder (line 43) | class DellDesktopBuilder : public DesktopBuilder
method DesktopBuilder (line 46) | DesktopBuilder &buildMotherboard()
method DesktopBuilder (line 52) | DesktopBuilder &buildProcessor()
method DesktopBuilder (line 58) | DesktopBuilder &buildMemory()
method DesktopBuilder (line 64) | DesktopBuilder &buildStorage()
method DesktopBuilder (line 70) | DesktopBuilder &buildGraphicsCard()
class HpDesktopBuilder (line 77) | class HpDesktopBuilder : public DesktopBuilder
method DesktopBuilder (line 80) | DesktopBuilder &buildMotherboard()
method DesktopBuilder (line 86) | DesktopBuilder &buildProcessor()
method DesktopBuilder (line 92) | DesktopBuilder &buildMemory()
method DesktopBuilder (line 98) | DesktopBuilder &buildStorage()
method DesktopBuilder (line 104) | DesktopBuilder &buildGraphicsCard()
class DesktopDirector (line 111) | class DesktopDirector
method Desktop (line 114) | Desktop buildComputer(DesktopBuilder &builder)
function main (line 120) | int main()
FILE: Builder Design Pattern/Builder with Chaining/JAVA/DesktopBuilderDemo.java
class Desktop (line 1) | class Desktop {
method display (line 8) | void display() {
class DesktopBuilder (line 18) | abstract class DesktopBuilder {
method buildMotherboard (line 21) | abstract DesktopBuilder buildMotherboard();
method buildProcessor (line 23) | abstract DesktopBuilder buildProcessor();
method buildMemory (line 25) | abstract DesktopBuilder buildMemory();
method buildStorage (line 27) | abstract DesktopBuilder buildStorage();
method buildGraphicsCard (line 29) | abstract DesktopBuilder buildGraphicsCard();
method build (line 31) | Desktop build() {
class DellDesktopBuilder (line 36) | class DellDesktopBuilder extends DesktopBuilder {
method DellDesktopBuilder (line 37) | DellDesktopBuilder() {
method buildMotherboard (line 41) | @Override
method buildProcessor (line 47) | @Override
method buildMemory (line 53) | @Override
method buildStorage (line 59) | @Override
method buildGraphicsCard (line 65) | @Override
class HpDesktopBuilder (line 72) | class HpDesktopBuilder extends DesktopBuilder {
method HpDesktopBuilder (line 73) | HpDesktopBuilder() {
method buildMotherboard (line 77) | @Override
method buildProcessor (line 83) | @Override
method buildMemory (line 89) | @Override
method buildStorage (line 95) | @Override
method buildGraphicsCard (line 101) | @Override
class DesktopDirector (line 108) | class DesktopDirector {
method buildDesktop (line 109) | Desktop buildDesktop(DesktopBuilder builder) {
class DesktopBuilderDemo (line 114) | public class DesktopBuilderDemo {
method main (line 115) | public static void main(String[] args) {
FILE: Builder Design Pattern/C++/desktop.cpp
class Desktop (line 4) | class Desktop
method display (line 13) | void display()
class DesktopBuilder (line 24) | class DesktopBuilder
method Desktop (line 36) | Desktop getDesktop()
class DellDesktopBuilder (line 42) | class DellDesktopBuilder : public DesktopBuilder
method buildMotherboard (line 45) | void buildMotherboard()
method buildProcessor (line 50) | void buildProcessor()
method buildMemory (line 55) | void buildMemory()
method buildStorage (line 60) | void buildStorage()
method buildGraphicsCard (line 65) | void buildGraphicsCard()
class HpDesktopBuilder (line 71) | class HpDesktopBuilder : public DesktopBuilder
method buildMotherboard (line 74) | void buildMotherboard()
method buildProcessor (line 79) | void buildProcessor()
method buildMemory (line 84) | void buildMemory()
method buildStorage (line 89) | void buildStorage()
method buildGraphicsCard (line 94) | void buildGraphicsCard()
class DesktopDirector (line 100) | class DesktopDirector
method Desktop (line 103) | Desktop buildDesktop(DesktopBuilder &builder)
function main (line 114) | int main()
FILE: Builder Design Pattern/JAVA/DesktopBuilderDemo.java
class Desktop (line 1) | class Desktop {
method display (line 8) | public void display() {
method getMotherboard (line 17) | public String getMotherboard() {
method setMotherboard (line 21) | public void setMotherboard(String motherboard) {
method getProcessor (line 25) | public String getProcessor() {
method setProcessor (line 29) | public void setProcessor(String processor) {
method getMemory (line 33) | public String getMemory() {
method setMemory (line 37) | public void setMemory(String memory) {
method getStorage (line 41) | public String getStorage() {
method setStorage (line 45) | public void setStorage(String storage) {
method getGraphicsCard (line 49) | public String getGraphicsCard() {
method setGraphicsCard (line 53) | public void setGraphicsCard(String graphicsCard) {
class DesktopBuilder (line 58) | abstract class DesktopBuilder {
method buildMotherboard (line 61) | public abstract void buildMotherboard();
method buildProcessor (line 63) | public abstract void buildProcessor();
method buildMemory (line 65) | public abstract void buildMemory();
method buildStorage (line 67) | public abstract void buildStorage();
method buildGraphicsCard (line 69) | public abstract void buildGraphicsCard();
method getDesktop (line 71) | public Desktop getDesktop() {
class DellDesktopBuilder (line 76) | class DellDesktopBuilder extends DesktopBuilder {
method buildMotherboard (line 77) | public void buildMotherboard() {
method buildProcessor (line 81) | public void buildProcessor() {
method buildMemory (line 85) | public void buildMemory() {
method buildStorage (line 89) | public void buildStorage() {
method buildGraphicsCard (line 93) | public void buildGraphicsCard() {
class HpDesktopBuilder (line 98) | class HpDesktopBuilder extends DesktopBuilder {
method buildMotherboard (line 99) | public void buildMotherboard() {
method buildProcessor (line 103) | public void buildProcessor() {
method buildMemory (line 107) | public void buildMemory() {
method buildStorage (line 111) | public void buildStorage() {
method buildGraphicsCard (line 115) | public void buildGraphicsCard() {
class DesktopDirector (line 120) | class DesktopDirector {
method buildDesktop (line 121) | public Desktop buildDesktop(DesktopBuilder builder) {
class DesktopBuilderDemo (line 131) | public class DesktopBuilderDemo {
method main (line 132) | public static void main(String[] args) {
FILE: Chain of Responsibility Design Pattern/C++/swiggy_order.cpp
class OrderHandler (line 6) | class OrderHandler {
method OrderHandler (line 10) | OrderHandler(OrderHandler* nextHandler) : nextHandler(nextHandler) {}
class OrderValidationHandler (line 16) | class OrderValidationHandler : public OrderHandler {
method OrderValidationHandler (line 18) | OrderValidationHandler(OrderHandler* nextHandler) : OrderHandler(nextH...
method processOrder (line 20) | void processOrder(const string& order) {
class PaymentProcessingHanlder (line 33) | class PaymentProcessingHanlder : public OrderHandler {
method PaymentProcessingHanlder (line 35) | PaymentProcessingHanlder(OrderHandler* nextHandler) : OrderHandler(nex...
method processOrder (line 37) | void processOrder(const string& order) {
class OrderPreparationHandler (line 50) | class OrderPreparationHandler : public OrderHandler {
method OrderPreparationHandler (line 52) | OrderPreparationHandler(OrderHandler* nexxtHandler) : OrderHandler(nex...
method processOrder (line 54) | void processOrder(const string& order) {
class DeliveryAssignmentHandler (line 66) | class DeliveryAssignmentHandler : public OrderHandler {
method DeliveryAssignmentHandler (line 68) | DeliveryAssignmentHandler(OrderHandler* nexxtHandler) : OrderHandler(n...
method processOrder (line 70) | void processOrder(const string& order) {
class OrderTrackingHandler (line 83) | class OrderTrackingHandler : public OrderHandler {
method OrderTrackingHandler (line 85) | OrderTrackingHandler(OrderHandler* nexxtHandler) : OrderHandler(nextHa...
method processOrder (line 87) | void processOrder(const string& order) {
function main (line 99) | int main() {
FILE: Chain of Responsibility Design Pattern/JAVA/SwiggyOrder.java
class OrderHandler (line 2) | abstract class OrderHandler {
method OrderHandler (line 5) | public OrderHandler(OrderHandler nextHandler) {
method processOrder (line 9) | public abstract void processOrder(String order);
class OrderValidationHandler (line 13) | class OrderValidationHandler extends OrderHandler {
method OrderValidationHandler (line 14) | public OrderValidationHandler(OrderHandler nextHandler) {
method processOrder (line 18) | @Override
class PaymentProcessingHandler (line 31) | class PaymentProcessingHandler extends OrderHandler {
method PaymentProcessingHandler (line 32) | public PaymentProcessingHandler(OrderHandler nextHandler) {
method processOrder (line 36) | @Override
class OrderPreparationHandler (line 49) | class OrderPreparationHandler extends OrderHandler {
method OrderPreparationHandler (line 50) | public OrderPreparationHandler(OrderHandler nextHandler) {
method processOrder (line 54) | @Override
class DeliveryAssignmentHandler (line 67) | class DeliveryAssignmentHandler extends OrderHandler {
method DeliveryAssignmentHandler (line 68) | public DeliveryAssignmentHandler(OrderHandler nextHandler) {
method processOrder (line 72) | @Override
class OrderTrackingHandler (line 85) | class OrderTrackingHandler extends OrderHandler {
method OrderTrackingHandler (line 86) | public OrderTrackingHandler(OrderHandler nextHandler) {
method processOrder (line 90) | @Override
class SwiggyOrder (line 97) | public class SwiggyOrder {
method main (line 98) | public static void main(String[] args) {
FILE: Command Design Pattern/C++/document.cpp
class ActionListenerCommand (line 6) | class ActionListenerCommand {
class Document (line 13) | class Document {
method open (line 15) | void open() {
method save (line 19) | void save() {
class ActionOpen (line 25) | class ActionOpen : public ActionListenerCommand {
method ActionOpen (line 30) | ActionOpen(Document* document) : doc(document) {}
method execute (line 32) | void execute() {
class ActionSave (line 38) | class ActionSave : public ActionListenerCommand {
method ActionSave (line 43) | ActionSave(Document* document) : doc(document) {}
method execute (line 45) | void execute() {
class MenuOptions (line 51) | class MenuOptions {
method addCommand (line 56) | void addCommand(ActionListenerCommand* command) {
method executeCommands (line 60) | void executeCommands() {
function main (line 67) | int main() {
FILE: Command Design Pattern/C++/uber_rides.cpp
class RideService (line 6) | class RideService {
method requestRide (line 8) | void requestRide(const string& passenger, const string& srcLoc, const ...
method cancelRide (line 14) | void cancelRide(const string& passenger) {
class Command (line 21) | class Command {
class RideRequestCommand (line 28) | class RideRequestCommand : public Command {
method RideRequestCommand (line 36) | RideRequestCommand(RideService* receiver, const string& passenger, con...
method execute (line 39) | void execute() override {
class CancelRideCommand (line 45) | class CancelRideCommand : public Command {
method CancelRideCommand (line 51) | CancelRideCommand(RideService* receiver, const string& passenger)
method execute (line 54) | void execute() override {
class RideRequestInvoker (line 60) | class RideRequestInvoker {
method processRequest (line 62) | void processRequest(Command* command) {
function main (line 67) | int main() {
FILE: Command Design Pattern/JAVA/DocumentDemo.java
type ActionListenerCommand (line 4) | interface ActionListenerCommand {
method execute (line 5) | void execute();
class Document (line 9) | class Document {
method open (line 10) | public void open() {
method save (line 14) | public void save() {
class ActionOpen (line 20) | class ActionOpen implements ActionListenerCommand {
method ActionOpen (line 23) | public ActionOpen(Document doc) {
method execute (line 27) | @Override
class ActionSave (line 34) | class ActionSave implements ActionListenerCommand {
method ActionSave (line 37) | public ActionSave(Document doc) {
method execute (line 41) | @Override
class MenuOptions (line 48) | class MenuOptions {
method addCommand (line 51) | public void addCommand(ActionListenerCommand command) {
method executeCommands (line 55) | public void executeCommands() {
class DocumentDemo (line 62) | public class DocumentDemo {
method main (line 63) | public static void main(String[] args) {
FILE: Command Design Pattern/JAVA/UberRidesDemo.java
class RideService (line 2) | class RideService {
method requestRide (line 3) | public void requestRide(String passenger, String srcLoc, String destLo...
method cancelRide (line 9) | public void cancelRide(String passenger) {
type Command (line 16) | interface Command {
method execute (line 17) | void execute();
class RideRequestCommand (line 21) | class RideRequestCommand implements Command {
method RideRequestCommand (line 27) | public RideRequestCommand(RideService receiver, String passenger, Stri...
method execute (line 34) | public void execute() {
class CancelRideCommand (line 40) | class CancelRideCommand implements Command {
method CancelRideCommand (line 44) | public CancelRideCommand(RideService receiver, String passenger) {
method execute (line 49) | public void execute() {
class RideRequestInvoker (line 55) | class RideRequestInvoker {
method processRequest (line 56) | public void processRequest(Command command) {
class UberRidesDemo (line 61) | public class UberRidesDemo {
method main (line 62) | public static void main(String[] args) {
FILE: Composite Design Pattern/C++/directorystructure.cpp
class FileSystemComponent (line 4) | class FileSystemComponent {
class File (line 10) | class File : public FileSystemComponent {
method File (line 16) | File(const string& fileName, int fileSize) : name(fileName), size(file...
method listContents (line 18) | void listContents() const override {
method getSize (line 22) | int getSize() const override {
class Directory (line 29) | class Directory : public FileSystemComponent {
method Directory (line 35) | Directory(const string& dirName) : name(dirName) {}
method addComponent (line 37) | void addComponent(FileSystemComponent* component) {
method listContents (line 41) | void listContents() const override {
method getSize (line 48) | int getSize() const override {
function main (line 57) | int main() {
FILE: Composite Design Pattern/C++/employee.cpp
class EmployeeComponent (line 5) | class EmployeeComponent {
class Employee (line 12) | class Employee : public EmployeeComponent {
method Employee (line 18) | Employee(string empName, double empSalary) : name(empName), salary(emp...
method displayInfo (line 20) | void displayInfo() override {
method calculateSalary (line 24) | double calculateSalary() override {
class Department (line 29) | class Department : public EmployeeComponent {
method Department (line 35) | Department(string deptName) : name(deptName) {}
method addMember (line 37) | void addMember(EmployeeComponent* member) {
method displayInfo (line 41) | void displayInfo() override {
method calculateSalary (line 48) | double calculateSalary() override {
class Team (line 57) | class Team : public EmployeeComponent {
method Team (line 63) | Team(string teamName) : name(teamName) {}
method addMember (line 65) | void addMember(EmployeeComponent* member) {
method displayInfo (line 69) | void displayInfo() override {
method calculateSalary (line 76) | double calculateSalary() override {
function main (line 86) | int main() {
FILE: Composite Design Pattern/JAVA/EmployeesDemo.java
class EmployeeComponent (line 3) | abstract class EmployeeComponent {
method displayInfo (line 4) | public abstract void displayInfo();
method calculateSalary (line 5) | public abstract double calculateSalary();
class Employee (line 8) | class Employee extends EmployeeComponent {
method Employee (line 12) | public Employee(String empName, double empSalary) {
method displayInfo (line 17) | @Override
method calculateSalary (line 22) | @Override
class Department (line 28) | class Department extends EmployeeComponent {
method Department (line 32) | public Department(String deptName) {
method addMember (line 37) | public void addMember(EmployeeComponent member) {
method displayInfo (line 41) | @Override
method calculateSalary (line 49) | @Override
class Team (line 59) | class Team extends EmployeeComponent {
method Team (line 63) | public Team(String teamName) {
method addMember (line 68) | public void addMember(EmployeeComponent member) {
method displayInfo (line 72) | @Override
method calculateSalary (line 80) | @Override
class EmployeesDemo (line 90) | public class EmployeesDemo {
method main (line 91) | public static void main(String[] args) {
FILE: Composite Design Pattern/JAVA/directorystructure.java
type FileSystemComponent (line 4) | interface FileSystemComponent {
method listContents (line 5) | void listContents();
method getSize (line 6) | int getSize();
class File (line 10) | class File implements FileSystemComponent {
method File (line 14) | public File(String fileName, int fileSize) {
method listContents (line 19) | @Override
method getSize (line 24) | @Override
class Directory (line 31) | class Directory implements FileSystemComponent {
method Directory (line 35) | public Directory(String dirName) {
method addComponent (line 40) | public void addComponent(FileSystemComponent component) {
method listContents (line 44) | @Override
method getSize (line 52) | @Override
class directorystructure (line 62) | public class directorystructure {
method main (line 63) | public static void main(String[] args) {
FILE: Decorator Design Pattern/C++/swiggy.cpp
class FoodItem (line 6) | class FoodItem
class Pizza (line 15) | class Pizza : public FoodItem
method string (line 18) | string getDescription()
method getPrice (line 23) | double getPrice()
class Burger (line 30) | class Burger : public FoodItem
method string (line 33) | string getDescription()
method getPrice (line 38) | double getPrice()
class Decorator (line 44) | class Decorator : public FoodItem
method Decorator (line 50) | Decorator(FoodItem *item) : foodItem(item) {}
class ExtraCheeseDecorator (line 54) | class ExtraCheeseDecorator : public Decorator
method ExtraCheeseDecorator (line 60) | ExtraCheeseDecorator(FoodItem *item, double price)
method string (line 63) | string getDescription()
method getPrice (line 68) | double getPrice()
class ExtraSauceDecorator (line 75) | class ExtraSauceDecorator : public Decorator
method ExtraSauceDecorator (line 81) | ExtraSauceDecorator(FoodItem *item, double price)
method string (line 84) | string getDescription()
method getPrice (line 89) | double getPrice()
class ExtraToppingsDecorator (line 96) | class ExtraToppingsDecorator : public Decorator
method ExtraToppingsDecorator (line 102) | ExtraToppingsDecorator(FoodItem *item, double price)
method string (line 105) | string getDescription()
method getPrice (line 110) | double getPrice()
function main (line 116) | int main()
FILE: Decorator Design Pattern/JAVA/Swiggy.java
type FoodItem (line 3) | interface FoodItem {
method getDescription (line 4) | String getDescription();
method getPrice (line 5) | double getPrice();
class Pizza (line 9) | class Pizza implements FoodItem {
method getDescription (line 10) | public String getDescription() {
method getPrice (line 14) | public double getPrice() {
class Burger (line 20) | class Burger implements FoodItem {
method getDescription (line 21) | public String getDescription() {
method getPrice (line 25) | public double getPrice() {
class Decorator (line 31) | abstract class Decorator implements FoodItem {
method Decorator (line 34) | public Decorator(FoodItem item) {
class ExtraCheeseDecorator (line 40) | class ExtraCheeseDecorator extends Decorator {
method ExtraCheeseDecorator (line 43) | public ExtraCheeseDecorator(FoodItem item, double price) {
method getDescription (line 48) | public String getDescription() {
method getPrice (line 52) | public double getPrice() {
class ExtraSauceDecorator (line 58) | class ExtraSauceDecorator extends Decorator {
method ExtraSauceDecorator (line 61) | public ExtraSauceDecorator(FoodItem item, double price) {
method getDescription (line 66) | public String getDescription() {
method getPrice (line 70) | public double getPrice() {
class ExtraToppingsDecorator (line 76) | class ExtraToppingsDecorator extends Decorator {
method ExtraToppingsDecorator (line 79) | public ExtraToppingsDecorator(FoodItem item, double price) {
method getDescription (line 84) | public String getDescription() {
method getPrice (line 88) | public double getPrice() {
class Swiggy (line 93) | public class Swiggy {
method main (line 94) | public static void main(String[] args) {
FILE: Facade Design Pattern/C++/computer.cpp
class CPU (line 5) | class CPU {
method powerOn (line 7) | void powerOn() {
method executeInstructions (line 11) | void executeInstructions() {
class Memory (line 17) | class Memory {
method initialize (line 19) | void initialize() {
class GPU (line 25) | class GPU {
method enableGraphics (line 27) | void enableGraphics() {
class DiskDrive (line 33) | class DiskDrive {
method bootFromDisk (line 35) | void bootFromDisk() {
class NetworkInterface (line 41) | class NetworkInterface {
method connectToNetwork (line 43) | void connectToNetwork() {
class ComputerSystemFacade (line 49) | class ComputerSystemFacade {
method startComputer (line 58) | void startComputer() {
function main (line 70) | int main() {
FILE: Facade Design Pattern/JAVA/ComputerDemo.java
class CPU (line 2) | class CPU {
method powerOn (line 3) | public void powerOn() {
method executeInstructions (line 7) | public void executeInstructions() {
class Memory (line 13) | class Memory {
method initialize (line 14) | public void initialize() {
class GPU (line 20) | class GPU {
method enableGraphics (line 21) | public void enableGraphics() {
class DiskDrive (line 27) | class DiskDrive {
method bootFromDisk (line 28) | public void bootFromDisk() {
class NetworkInterface (line 34) | class NetworkInterface {
method connectToNetwork (line 35) | public void connectToNetwork() {
class ComputerSystemFacade (line 41) | class ComputerSystemFacade {
method ComputerSystemFacade (line 48) | public ComputerSystemFacade() {
method startComputer (line 56) | public void startComputer() {
class ComputerDemo (line 68) | public class ComputerDemo {
method main (line 69) | public static void main(String[] args) {
FILE: Factory Method Design Pattern/Furniture/C++/furniture.cpp
class FurnitureItem (line 7) | class FurnitureItem {
class Sofa (line 13) | class Sofa : public FurnitureItem {
method display (line 15) | void display() override {
class Chair (line 20) | class Chair : public FurnitureItem {
method display (line 22) | void display() override {
class Table (line 27) | class Table : public FurnitureItem {
method display (line 29) | void display() override {
class FurnitureFactory (line 35) | class FurnitureFactory {
class SofaFactory (line 41) | class SofaFactory : public FurnitureFactory {
method FurnitureItem (line 43) | FurnitureItem* createFurniture() override {
class ChairFactory (line 48) | class ChairFactory : public FurnitureFactory {
method FurnitureItem (line 50) | FurnitureItem* createFurniture() override {
class TableFactory (line 55) | class TableFactory : public FurnitureFactory {
method FurnitureItem (line 57) | FurnitureItem* createFurniture() override {
function main (line 62) | int main() {
FILE: Factory Method Design Pattern/Furniture/JAVA/furniture.java
type FurnitureItem (line 2) | interface FurnitureItem {
method display (line 3) | void display();
class Sofa (line 7) | class Sofa implements FurnitureItem {
method display (line 8) | @Override
class Chair (line 14) | class Chair implements FurnitureItem {
method display (line 15) | @Override
class Table (line 21) | class Table implements FurnitureItem {
method display (line 22) | @Override
type FurnitureFactory (line 29) | interface FurnitureFactory {
method createFurniture (line 30) | FurnitureItem createFurniture();
class SofaFactory (line 34) | class SofaFactory implements FurnitureFactory {
method createFurniture (line 35) | @Override
class ChairFactory (line 41) | class ChairFactory implements FurnitureFactory {
method createFurniture (line 42) | @Override
class TableFactory (line 48) | class TableFactory implements FurnitureFactory {
method createFurniture (line 49) | @Override
class furniture (line 55) | public class furniture {
method main (line 56) | public static void main(String[] args) {
FILE: Factory Method Design Pattern/Furniture/Javascript/furniture.js
class FurnitureItem (line 2) | class FurnitureItem {
method display (line 3) | display() {}
class Sofa (line 7) | class Sofa extends FurnitureItem {
method display (line 8) | display() {
class Chair (line 13) | class Chair extends FurnitureItem {
method display (line 14) | display() {
class Table (line 19) | class Table extends FurnitureItem {
method display (line 20) | display() {
class FurnitureFactory (line 26) | class FurnitureFactory {
method createFurniture (line 27) | createFurniture() {}
class SofaFactory (line 31) | class SofaFactory extends FurnitureFactory {
method createFurniture (line 32) | createFurniture() {
class ChairFactory (line 37) | class ChairFactory extends FurnitureFactory {
method createFurniture (line 38) | createFurniture() {
class TableFactory (line 43) | class TableFactory extends FurnitureFactory {
method createFurniture (line 44) | createFurniture() {
function main (line 49) | function main() {
FILE: Factory Method Design Pattern/Furniture/Python/furniture.py
class FurnitureItem (line 2) | class FurnitureItem:
method display (line 3) | def display(self):
class Sofa (line 7) | class Sofa(FurnitureItem):
method display (line 8) | def display(self):
class Chair (line 11) | class Chair(FurnitureItem):
method display (line 12) | def display(self):
class Table (line 15) | class Table(FurnitureItem):
method display (line 16) | def display(self):
class FurnitureFactory (line 20) | class FurnitureFactory:
method create_furniture (line 21) | def create_furniture(self):
class SofaFactory (line 25) | class SofaFactory(FurnitureFactory):
method create_furniture (line 26) | def create_furniture(self):
class ChairFactory (line 29) | class ChairFactory(FurnitureFactory):
method create_furniture (line 30) | def create_furniture(self):
class TableFactory (line 33) | class TableFactory(FurnitureFactory):
method create_furniture (line 34) | def create_furniture(self):
function main (line 37) | def main():
FILE: Factory Method Design Pattern/Logger/C++/common.hpp
type LogLevel (line 7) | enum class LogLevel {
FILE: Factory Method Design Pattern/Logger/C++/debug_logger.hpp
class DebugLogger (line 4) | class DebugLogger : public ILogger {
FILE: Factory Method Design Pattern/Logger/C++/debug_logger_factory.hpp
class DebugLoggerFactory (line 5) | class DebugLoggerFactory : public ILoggerFactory{
method ILogger (line 7) | ILogger* createLogger() {
FILE: Factory Method Design Pattern/Logger/C++/error_logger.hpp
class ErrorLogger (line 4) | class ErrorLogger : public ILogger{
FILE: Factory Method Design Pattern/Logger/C++/error_logger_factory.hpp
class ErrorLoggerFactory (line 5) | class ErrorLoggerFactory : public ILoggerFactory{
method ILogger (line 7) | ILogger* createLogger() {
FILE: Factory Method Design Pattern/Logger/C++/ilogger.hpp
class ILogger (line 4) | class ILogger {
FILE: Factory Method Design Pattern/Logger/C++/info_logger.hpp
class InfoLogger (line 4) | class InfoLogger : public ILogger {
FILE: Factory Method Design Pattern/Logger/C++/info_logger_factory.hpp
class InfoLoggerFactory (line 5) | class InfoLoggerFactory : public ILoggerFactory{
method ILogger (line 7) | ILogger* createLogger() {
FILE: Factory Method Design Pattern/Logger/C++/logger_factory.hpp
class ILoggerFactory (line 7) | class ILoggerFactory {
FILE: Factory Method Design Pattern/Logger/C++/main.cpp
function main (line 5) | int main() {
FILE: Factory Method Design Pattern/Logger/JAVA/LoggerDemo.java
type ILogger (line 1) | interface ILogger {
method log (line 2) | void log(String msg);
class DebugLogger (line 5) | class DebugLogger implements ILogger {
method log (line 6) | @Override
class ErrorLogger (line 12) | class ErrorLogger implements ILogger {
method log (line 13) | @Override
class InfoLogger (line 19) | class InfoLogger implements ILogger {
method log (line 20) | @Override
type LoggerFactory (line 26) | interface LoggerFactory {
method createLogger (line 27) | ILogger createLogger();
class DebugLoggerFactory (line 30) | class DebugLoggerFactory implements LoggerFactory {
method createLogger (line 31) | @Override
class ErrorLoggerFactory (line 37) | class ErrorLoggerFactory implements LoggerFactory {
method createLogger (line 38) | @Override
class InfoLoggerFactory (line 44) | class InfoLoggerFactory implements LoggerFactory {
method createLogger (line 45) | @Override
class LoggerDemo (line 51) | public class LoggerDemo {
method main (line 52) | public static void main(String[] args) {
FILE: Iterator Design Pattern/C++/amazon_inventory.cpp
class Product (line 6) | class Product {
method Product (line 12) | Product(const string& name, const double& price) : name(name), price(p...
method string (line 14) | const string& getName() const {
method getPrice (line 18) | double getPrice() const {
class Iterator (line 24) | class Iterator {
class ProductIterator (line 33) | class ProductIterator : public Iterator {
method ProductIterator (line 41) | ProductIterator(vector<Product*>& products) : products(products), curr...
method Product (line 43) | Product* first() {
method Product (line 51) | Product* next() {
method hasNext (line 58) | bool hasNext() {
class Inventory (line 64) | class Inventory {
method addProduct (line 68) | void addProduct(Product* product) {
method Iterator (line 72) | Iterator* createIterator() {
function main (line 78) | int main() {
FILE: Iterator Design Pattern/JAVA/AmazonInventory.java
class Product (line 4) | class Product {
method Product (line 8) | public Product(String name, double price) {
method getName (line 13) | public String getName() {
method getPrice (line 17) | public double getPrice() {
type Iterator (line 23) | interface Iterator {
method first (line 24) | Product first();
method next (line 25) | Product next();
method hasNext (line 26) | boolean hasNext();
class ProductIterator (line 30) | class ProductIterator implements Iterator {
method ProductIterator (line 34) | public ProductIterator(List<Product> products) {
method first (line 39) | public Product first() {
method next (line 47) | public Product next() {
method hasNext (line 54) | public boolean hasNext() {
class Inventory (line 60) | class Inventory {
method addProduct (line 63) | public void addProduct(Product product) {
method createIterator (line 67) | public Iterator createIterator() {
class AmazonInventory (line 72) | public class AmazonInventory {
method main (line 73) | public static void main(String[] args) {
FILE: Observer Design Pattern/C++/order_status.cpp
class Order (line 4) | class Order
method Order (line 65) | Order(int id) : id(id), status("Order Placed") {}
method getId (line 67) | int getId()
method string (line 72) | string getStatus()
method setStatus (line 77) | void setStatus(string newStatus)
method attach (line 83) | void attach(Observer *observer)
method detach (line 88) | void detach(Observer *observer)
method notifyObservers (line 100) | void notifyObservers()
class Observer (line 7) | class Observer
class Customer (line 14) | class Customer : public Observer
method Customer (line 20) | Customer(string name) : name(name) {}
class Restaurant (line 26) | class Restaurant : public Observer
method Restaurant (line 32) | Restaurant(string name) : restaurantName(name) {}
class DeliveryDriver (line 38) | class DeliveryDriver : public Observer
method DeliveryDriver (line 44) | DeliveryDriver(string name) : driverName(name) {}
class CallCenter (line 50) | class CallCenter : public Observer
class Order (line 57) | class Order
method Order (line 65) | Order(int id) : id(id), status("Order Placed") {}
method getId (line 67) | int getId()
method string (line 72) | string getStatus()
method setStatus (line 77) | void setStatus(string newStatus)
method attach (line 83) | void attach(Observer *observer)
method detach (line 88) | void detach(Observer *observer)
method notifyObservers (line 100) | void notifyObservers()
function main (line 128) | int main()
FILE: Observer Design Pattern/JAVA/OrderStatus.java
type Observer (line 3) | interface Observer {
method update (line 4) | void update(Order order);
class Customer (line 7) | class Customer implements Observer {
method Customer (line 10) | public Customer(String name) {
method update (line 14) | @Override
class Restaurant (line 20) | class Restaurant implements Observer {
method Restaurant (line 23) | public Restaurant(String name) {
method update (line 27) | @Override
class DeliveryDriver (line 33) | class DeliveryDriver implements Observer {
method DeliveryDriver (line 36) | public DeliveryDriver(String name) {
method update (line 40) | @Override
class CallCenter (line 46) | class CallCenter implements Observer {
method update (line 47) | @Override
class Order (line 53) | class Order {
method Order (line 58) | public Order(int id) {
method getId (line 63) | public int getId() {
method getStatus (line 67) | public String getStatus() {
method setStatus (line 71) | public void setStatus(String newStatus) {
method attach (line 76) | public void attach(Observer observer) {
method detach (line 80) | public void detach(Observer observer) {
method notifyObservers (line 84) | public void notifyObservers() {
class OrderStatus (line 91) | public class OrderStatus {
method main (line 92) | public static void main(String[] args) {
FILE: Prototype Design Pattern/C++/product.cpp
class ProductPrototype (line 5) | class ProductPrototype {
class Product (line 13) | class Product : public ProductPrototype {
method Product (line 19) | Product(const string& name, double price)
method ProductPrototype (line 22) | ProductPrototype* clone() override {
method display (line 26) | void display() override {
function main (line 32) | int main() {
FILE: Prototype Design Pattern/C++/router.cpp
class NetworkDevice (line 5) | class NetworkDevice {
class Router (line 12) | class Router : public NetworkDevice {
method Router (line 14) | Router(string name, string ip, string securityPolicy)
method NetworkDevice (line 17) | NetworkDevice* clone() const override {
method display (line 21) | void display() const override {
method update (line 25) | void update(string newName) override {
class Switch (line 35) | class Switch : public NetworkDevice {
method Switch (line 37) | Switch(string name, string protocol)
method NetworkDevice (line 40) | NetworkDevice* clone() const override {
method display (line 44) | void display() const override {
method update (line 48) | void update(string newName) override {
function main (line 57) | int main() {
FILE: Prototype Design Pattern/JAVA/ProductDemo.java
class ProductPrototype (line 2) | abstract class ProductPrototype {
method clone (line 3) | public abstract ProductPrototype clone();
method display (line 4) | public abstract void display();
class Product (line 8) | class Product extends ProductPrototype {
method Product (line 12) | public Product(String name, double price) {
method clone (line 17) | @Override
method display (line 22) | @Override
class ProductDemo (line 29) | public class ProductDemo {
method main (line 30) | public static void main(String[] args) {
FILE: Prototype Design Pattern/JAVA/RouterDemo.java
class NetworkDevice (line 1) | abstract class NetworkDevice {
method clone (line 2) | public abstract NetworkDevice clone();
method display (line 4) | public abstract void display();
method update (line 6) | public abstract void update(String newName);
class Router (line 9) | class Router extends NetworkDevice {
method Router (line 14) | public Router(String name, String ip, String securityPolicy) {
method clone (line 20) | @Override
method display (line 25) | @Override
method update (line 30) | @Override
class Switch (line 36) | class Switch extends NetworkDevice {
method Switch (line 40) | public Switch(String name, String protocol) {
method clone (line 45) | @Override
method display (line 50) | @Override
method update (line 55) | @Override
class RouterDemo (line 61) | public class RouterDemo {
method main (line 62) | public static void main(String[] args) {
FILE: Proxy Design Pattern/C++/image.cpp
class Image (line 5) | class Image {
class RealImage (line 11) | class RealImage : public Image {
method RealImage (line 16) | RealImage(const string& filename) : filename(filename) {
method display (line 20) | void display() {
method loadFromDisk (line 24) | void loadFromDisk() {
class ImageProxy (line 30) | class ImageProxy : public Image {
method ImageProxy (line 36) | ImageProxy(const string& filename) : filename(filename), realImage(nul...
method display (line 38) | void display() {
function main (line 52) | int main() {
FILE: Proxy Design Pattern/JAVA/ImageDemo.java
type Image (line 1) | interface Image {
method display (line 2) | void display();
class RealImage (line 5) | class RealImage implements Image {
method RealImage (line 8) | public RealImage(String filename) {
method display (line 13) | @Override
method loadFromDisk (line 18) | private void loadFromDisk() {
class ImageProxy (line 23) | class ImageProxy implements Image {
method ImageProxy (line 27) | public ImageProxy(String filename) {
method display (line 32) | @Override
class ImageDemo (line 41) | public class ImageDemo {
method main (line 42) | public static void main(String[] args) {
FILE: Simple Factory Design Pattern/C++/common.hpp
type LogLevel (line 7) | enum class LogLevel {
FILE: Simple Factory Design Pattern/C++/debug_logger.hpp
class DebugLogger (line 4) | class DebugLogger : public ILogger {
FILE: Simple Factory Design Pattern/C++/error_logger.hpp
class ErrorLogger (line 4) | class ErrorLogger : public ILogger{
FILE: Simple Factory Design Pattern/C++/ilogger.hpp
class ILogger (line 4) | class ILogger {
FILE: Simple Factory Design Pattern/C++/info_logger.hpp
class InfoLogger (line 4) | class InfoLogger : public ILogger {
FILE: Simple Factory Design Pattern/C++/logger_factory.cpp
function ILogger (line 3) | ILogger* LoggerFactory::createLogger(LogLevel pLogLevel) {
FILE: Simple Factory Design Pattern/C++/logger_factory.hpp
class LoggerFactory (line 7) | class LoggerFactory {
FILE: Simple Factory Design Pattern/C++/main.cpp
function main (line 3) | int main() {
FILE: Simple Factory Design Pattern/JAVA/Main.java
class Main (line 4) | public class Main {
method main (line 5) | public static void main(String[] args) {
FILE: Simple Factory Design Pattern/JAVA/logger/DebugLogger.java
class DebugLogger (line 3) | public class DebugLogger implements ILogger {
method log (line 4) | public void log(String msg) {
FILE: Simple Factory Design Pattern/JAVA/logger/ErrorLogger.java
class ErrorLogger (line 3) | public class ErrorLogger implements ILogger {
method log (line 4) | public void log(String msg) {
FILE: Simple Factory Design Pattern/JAVA/logger/ILogger.java
type ILogger (line 3) | public interface ILogger {
method log (line 4) | void log (String msg);
FILE: Simple Factory Design Pattern/JAVA/logger/InfoLogger.java
class InfoLogger (line 3) | public class InfoLogger implements ILogger {
method log (line 4) | public void log(String msg) {
FILE: Simple Factory Design Pattern/JAVA/logger/LogLevel.java
type LogLevel (line 3) | public enum LogLevel {
FILE: Simple Factory Design Pattern/JAVA/logger/LoggerFactory.java
class LoggerFactory (line 3) | public class LoggerFactory {
method createLogger (line 4) | public static ILogger createLogger(LogLevel logLevel) {
FILE: Singleton Design Pattern/C++/payment_gateway.cpp
class PaymentGatewayManager (line 5) | class PaymentGatewayManager
method PaymentGatewayManager (line 9) | PaymentGatewayManager()
method PaymentGatewayManager (line 19) | static PaymentGatewayManager *getInstance()
method processPayment (line 33) | void processPayment(double amount)
function main (line 43) | int main()
FILE: Singleton Design Pattern/JAVA/PaymentGateway.java
class PaymentGatewayManager (line 4) | class PaymentGatewayManager {
method PaymentGatewayManager (line 6) | private PaymentGatewayManager() {
method getInstance (line 14) | public static PaymentGatewayManager getInstance() {
method processPayment (line 28) | public void processPayment(double amount) {
class PaymentGateway (line 34) | public class PaymentGateway {
method main (line 35) | public static void main(String[] args) {
FILE: State Design Pattern/C++/state.cpp
class RideState (line 5) | class RideState {
class RideRequestedState (line 13) | class RideRequestedState : public RideState {
method handleRequest (line 15) | void handleRequest() override {
method handleCancel (line 19) | void handleCancel() override {
class DriverAssignedState (line 24) | class DriverAssignedState : public RideState {
method handleRequest (line 26) | void handleRequest() override {
method handleCancel (line 30) | void handleCancel() override {
class EnRouteState (line 35) | class EnRouteState : public RideState {
method handleRequest (line 37) | void handleRequest() override {
method handleCancel (line 41) | void handleCancel() override {
class Ride (line 48) | class Ride {
method Ride (line 53) | Ride() {
method setState (line 58) | void setState(RideState* newState) {
method requestRide (line 63) | void requestRide() {
method cancelRide (line 67) | void cancelRide() {
function main (line 72) | int main() {
FILE: State Design Pattern/JAVA/StateDemo.java
type RideState (line 2) | interface RideState {
method handleRequest (line 3) | void handleRequest();
method handleCancel (line 4) | void handleCancel();
class RideRequestedState (line 9) | class RideRequestedState implements RideState {
method handleRequest (line 10) | @Override
method handleCancel (line 15) | @Override
class DriverAssignedState (line 21) | class DriverAssignedState implements RideState {
method handleRequest (line 22) | @Override
method handleCancel (line 27) | @Override
class EnRouteState (line 33) | class EnRouteState implements RideState {
method handleRequest (line 34) | @Override
method handleCancel (line 39) | @Override
class Ride (line 47) | class Ride {
method Ride (line 50) | public Ride() {
method setState (line 55) | public void setState(RideState newState) {
method requestRide (line 59) | public void requestRide() {
method cancelRide (line 63) | public void cancelRide() {
class StateDemo (line 68) | public class StateDemo {
method main (line 69) | public static void main(String[] args) {
FILE: Strategy Design Pattern/C++/payment.cpp
class PaymentStrategy (line 4) | class PaymentStrategy {
class CreditCardPayment (line 10) | class CreditCardPayment : public PaymentStrategy {
method processPayment (line 12) | void processPayment(double amount) override {
class PayPalPayment (line 17) | class PayPalPayment : public PaymentStrategy {
method processPayment (line 19) | void processPayment(double amount) override {
class CryptocurrencyPayment (line 24) | class CryptocurrencyPayment : public PaymentStrategy {
method processPayment (line 26) | void processPayment(double amount) override {
class PaymentProcessor (line 31) | class PaymentProcessor {
method PaymentProcessor (line 36) | PaymentProcessor() : paymentStrategy(nullptr) {}
method setPaymentStrategy (line 38) | void setPaymentStrategy(PaymentStrategy* strategy) {
method processPayment (line 42) | void processPayment(double amount) {
function main (line 57) | int main() {
FILE: Strategy Design Pattern/JAVA/PaymentDemo.java
type PaymentStrategy (line 2) | interface PaymentStrategy {
method processPayment (line 3) | void processPayment(double amount);
class CreditCardPayment (line 7) | class CreditCardPayment implements PaymentStrategy {
method processPayment (line 8) | public void processPayment(double amount) {
class PayPalPayment (line 13) | class PayPalPayment implements PaymentStrategy {
method processPayment (line 14) | public void processPayment(double amount) {
class CryptocurrencyPayment (line 19) | class CryptocurrencyPayment implements PaymentStrategy {
method processPayment (line 20) | public void processPayment(double amount) {
class PaymentProcessor (line 26) | class PaymentProcessor {
method PaymentProcessor (line 29) | public PaymentProcessor() {
method setPaymentStrategy (line 33) | public void setPaymentStrategy(PaymentStrategy strategy) {
method processPayment (line 41) | public void processPayment(double amount) {
method finalize (line 49) | public void finalize() {
class PaymentDemo (line 57) | public class PaymentDemo {
method main (line 58) | public static void main(String[] args) {
FILE: Strategy and Factory Design Pattern/C++/payment.cpp
class PaymentStrategy (line 5) | class PaymentStrategy {
class CreditCardPayment (line 12) | class CreditCardPayment : public PaymentStrategy {
method processPayment (line 14) | void processPayment(double amount) override {
class PayPalPayment (line 19) | class PayPalPayment : public PaymentStrategy {
method processPayment (line 21) | void processPayment(double amount) override {
class CryptocurrencyPayment (line 26) | class CryptocurrencyPayment : public PaymentStrategy {
method processPayment (line 28) | void processPayment(double amount) override {
class PaymentStrategyFactory (line 34) | class PaymentStrategyFactory {
method PaymentStrategy (line 36) | static PaymentStrategy* createPaymentStrategy(const string& paymentMet...
class PaymentProcessor (line 51) | class PaymentProcessor {
method PaymentProcessor (line 56) | PaymentProcessor() : paymentStrategy(nullptr) {}
method setPaymentStrategy (line 58) | void setPaymentStrategy(const string& paymentMethod) {
method processPayment (line 65) | void processPayment(double amount) {
function main (line 80) | int main() {
FILE: Strategy and Factory Design Pattern/JAVA/PaymentDemo.java
type PaymentStrategy (line 2) | interface PaymentStrategy {
method processPayment (line 3) | void processPayment(double amount);
class CreditCardPayment (line 7) | class CreditCardPayment implements PaymentStrategy {
method processPayment (line 8) | public void processPayment(double amount) {
class PayPalPayment (line 13) | class PayPalPayment implements PaymentStrategy {
method processPayment (line 14) | public void processPayment(double amount) {
class CryptocurrencyPayment (line 19) | class CryptocurrencyPayment implements PaymentStrategy {
method processPayment (line 20) | public void processPayment(double amount) {
class PaymentStrategyFactory (line 26) | class PaymentStrategyFactory {
method createPaymentStrategy (line 27) | public static PaymentStrategy createPaymentStrategy(String paymentMeth...
class PaymentProcessor (line 42) | class PaymentProcessor {
method PaymentProcessor (line 45) | public PaymentProcessor() {
method setPaymentStrategy (line 49) | public void setPaymentStrategy(String paymentMethod) {
method processPayment (line 57) | public void processPayment(double amount) {
method finalize (line 65) | public void finalize() {
class PaymentDemo (line 73) | public class PaymentDemo {
method main (line 74) | public static void main(String[] args) {
FILE: Template Design Pattern/C++/amazon_order.cpp
class OrderProcessingTemplate (line 5) | class OrderProcessingTemplate {
method processOrder (line 7) | void processOrder() {
class LocalOrderProcessor (line 19) | class LocalOrderProcessor : public OrderProcessingTemplate {
method verifyOrder (line 21) | void verifyOrder() {
method assignDeliveryAgent (line 26) | void assignDeliveryAgent() {
method trackDelivery (line 31) | void trackDelivery() {
class InternationalOrderProcessor (line 38) | class InternationalOrderProcessor : public OrderProcessingTemplate {
method verifyOrder (line 40) | void verifyOrder() {
method assignDeliveryAgent (line 45) | void assignDeliveryAgent() {
method trackDelivery (line 50) | void trackDelivery() {
function main (line 56) | int main() {
FILE: Template Design Pattern/JAVA/AmazonOrderProcessor.java
class OrderProcessingTemplate (line 2) | abstract class OrderProcessingTemplate {
method processOrder (line 3) | public void processOrder() {
method verifyOrder (line 9) | abstract void verifyOrder();
method assignDeliveryAgent (line 10) | abstract void assignDeliveryAgent();
method trackDelivery (line 11) | abstract void trackDelivery();
class LocalOrderProcessor (line 15) | class LocalOrderProcessor extends OrderProcessingTemplate {
method verifyOrder (line 16) | void verifyOrder() {
method assignDeliveryAgent (line 21) | void assignDeliveryAgent() {
method trackDelivery (line 26) | void trackDelivery() {
class InternationalOrderProcessor (line 33) | class InternationalOrderProcessor extends OrderProcessingTemplate {
method verifyOrder (line 34) | void verifyOrder() {
method assignDeliveryAgent (line 39) | void assignDeliveryAgent() {
method trackDelivery (line 44) | void trackDelivery() {
class AmazonOrderProcessor (line 50) | public class AmazonOrderProcessor {
method main (line 51) | public static void main(String[] args) {
Condensed preview — 97 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (142K chars).
[
{
"path": ".gitignore",
"chars": 445,
"preview": "# Compiled source #\n###################\n*.com\n*.class\n*.dll\n*.exe\n*.o\n*.so\n\n# Packages #\n############\n# it's better to u"
},
{
"path": "Abstract Factory Design Pattern/Furniture /C++/furniture.cpp",
"chars": 3841,
"preview": "#include <iostream>\n\n// Abstract Product: Sofa\nclass Sofa {\npublic:\n virtual void sitOn() = 0;\n};\n\n// Abstract Produc"
},
{
"path": "Abstract Factory Design Pattern/Furniture /JAVA/furniture.java",
"chars": 3320,
"preview": "interface Sofa {\n void sitOn();\n}\n\n// Abstract Product: Chair\ninterface Chair {\n void sitOn();\n}\n\n// Abstract Prod"
},
{
"path": "Abstract Factory Design Pattern/Furniture /Javascript/furniture.js",
"chars": 2857,
"preview": "// Abstract Product: Sofa\nclass Sofa {\n sitOn() {}\n}\n\n// Abstract Product: Chair\nclass Chair {\n sitOn() {}\n}\n\n// A"
},
{
"path": "Abstract Factory Design Pattern/Furniture /Python/furniture.py",
"chars": 2745,
"preview": "# Abstract Product: Sofa\nclass Sofa:\n def sit_on(self):\n pass\n\n# Abstract Product: Chair\nclass Chair:\n def "
},
{
"path": "Abstract Factory Design Pattern/UI/C++/ui.cpp",
"chars": 1839,
"preview": "#include <string>\n#include <iostream>\nusing namespace std;\n\nclass Ibutton{\n public :\n virtual void press() = 0;\n "
},
{
"path": "Abstract Factory Design Pattern/UI/JAVA/UI.java",
"chars": 2086,
"preview": "import java.util.Scanner;\n\ninterface IButton {\n void press();\n}\n\ninterface ITextbox {\n void settext();\n}\n\nclass Ma"
},
{
"path": "Adapter Design Pattern/Class Adapter/C++/xml_to_json.cpp",
"chars": 1427,
"preview": "#include <iostream>\nusing namespace std;\n\n// Data analytics tool that expects JSON data\n// Adaptee\nclass JSONAnalyticsTo"
},
{
"path": "Adapter Design Pattern/Object Adapter/C++/xml_to_json.cpp",
"chars": 1432,
"preview": "#include <iostream>\nusing namespace std;\n\n// Data analytics tool that expects JSON data\n// Adaptee\nclass JSONAnalyticsTo"
},
{
"path": "Adapter Design Pattern/Object Adapter/JAVA/XmlToJson.java",
"chars": 1334,
"preview": "class JSONAnalyticsTool {\n private String jsonData;\n\n public void setJsonData(String jsonData) {\n this.json"
},
{
"path": "Bridge Design Pattern/C++/uber.cpp",
"chars": 2410,
"preview": "#include <iostream>\n\nusing namespace std;\n\n// Implementation Layer\nclass NavigationImpl\n{\npublic:\n virtual void navig"
},
{
"path": "Bridge Design Pattern/JAVA/UberDemo.java",
"chars": 2606,
"preview": "// Implementation Layer\ninterface NavigationImpl {\n void navigateTo(String destination);\n}\n\n// Abstraction Layer\ninte"
},
{
"path": "Builder Design Pattern/Builder with Chaining/C++/desktop.cpp",
"chars": 2756,
"preview": "#include <iostream>\n\nusing namespace std;\n\nclass Desktop\n{\npublic:\n string motherboard;\n string processor;\n str"
},
{
"path": "Builder Design Pattern/Builder with Chaining/JAVA/DesktopBuilderDemo.java",
"chars": 3123,
"preview": "class Desktop {\n String motherboard;\n String processor;\n String memory;\n String storage;\n String graphics"
},
{
"path": "Builder Design Pattern/C++/desktop.cpp",
"chars": 2451,
"preview": "#include <iostream>\nusing namespace std;\n\nclass Desktop\n{\npublic:\n string motherboard;\n string processor;\n stri"
},
{
"path": "Builder Design Pattern/JAVA/DesktopBuilderDemo.java",
"chars": 3488,
"preview": "class Desktop {\n private String motherboard;\n private String processor;\n private String memory;\n private Str"
},
{
"path": "Chain of Responsibility Design Pattern/C++/swiggy_order.cpp",
"chars": 4556,
"preview": "#include <iostream>\n\nusing namespace std;\n\n// Define the abstract base class for order handlers.\nclass OrderHandler {\n "
},
{
"path": "Chain of Responsibility Design Pattern/JAVA/SwiggyOrder.java",
"chars": 3364,
"preview": "// Define the abstract base class for order handlers.\nabstract class OrderHandler {\n protected OrderHandler nextHandl"
},
{
"path": "Command Design Pattern/C++/document.cpp",
"chars": 1602,
"preview": "#include <iostream>\n\nusing namespace std;\n\n// Command Interface\nclass ActionListenerCommand {\npublic:\n virtual void e"
},
{
"path": "Command Design Pattern/C++/uber_rides.cpp",
"chars": 2437,
"preview": "#include <iostream>\n\nusing namespace std;\n\n// Receiver: RideService\nclass RideService {\npublic:\n void requestRide(con"
},
{
"path": "Command Design Pattern/JAVA/DocumentDemo.java",
"chars": 1707,
"preview": "import java.util.*;\n\n//Command Interface\ninterface ActionListenerCommand {\n void execute();\n}\n\n//Receiver - performin"
},
{
"path": "Command Design Pattern/JAVA/UberRidesDemo.java",
"chars": 2503,
"preview": "// Receiver: RideService\nclass RideService {\n public void requestRide(String passenger, String srcLoc, String destLoc"
},
{
"path": "Composite Design Pattern/C++/directorystructure.cpp",
"chars": 2002,
"preview": "#include <iostream>\nusing namespace std;\n\nclass FileSystemComponent {\npublic:\n virtual void listContents() const = 0;"
},
{
"path": "Composite Design Pattern/C++/employee.cpp",
"chars": 2798,
"preview": "#include <iostream>\n\nusing namespace std;\n\nclass EmployeeComponent {\npublic:\n virtual void displayInfo() = 0;\n vir"
},
{
"path": "Composite Design Pattern/JAVA/EmployeesDemo.java",
"chars": 2909,
"preview": "import java.util.*;\n\nabstract class EmployeeComponent {\n public abstract void displayInfo();\n public abstract doub"
},
{
"path": "Composite Design Pattern/JAVA/directorystructure.java",
"chars": 2231,
"preview": "import java.util.*;\n\n// Abstraction Layer\ninterface FileSystemComponent {\n void listContents();\n int getSize();\n}\n"
},
{
"path": "Decorator Design Pattern/C++/swiggy.cpp",
"chars": 2915,
"preview": "#include <iostream>\nusing namespace std;\n\n// Base interface representing a food item.\n// Component\nclass FoodItem\n{\npubl"
},
{
"path": "Decorator Design Pattern/JAVA/Swiggy.java",
"chars": 2913,
"preview": "// Base interface representing a food item.\n// Component\ninterface FoodItem {\n String getDescription();\n double ge"
},
{
"path": "Facade Design Pattern/C++/computer.cpp",
"chars": 1510,
"preview": "#include <iostream>\nusing namespace std;\n\n// Subsystem 1: CPU\nclass CPU {\npublic:\n void powerOn() {\n cout << \""
},
{
"path": "Facade Design Pattern/JAVA/ComputerDemo.java",
"chars": 1855,
"preview": "// Subsystem 1: CPU\nclass CPU {\n public void powerOn() {\n System.out.println(\"CPU is powered on.\");\n }\n\n "
},
{
"path": "Factory Method Design Pattern/Furniture/C++/furniture.cpp",
"chars": 2105,
"preview": "//The Factory Method pattern is a creational design pattern that defines an interface for creating objects but lets subc"
},
{
"path": "Factory Method Design Pattern/Furniture/JAVA/furniture.java",
"chars": 1796,
"preview": "// Abstract Product: Furniture Item\ninterface FurnitureItem {\n void display();\n}\n\n// Concrete Products: Sofa, Chair, "
},
{
"path": "Factory Method Design Pattern/Furniture/Javascript/furniture.js",
"chars": 1398,
"preview": "// Abstract Product: Furniture Item\nclass FurnitureItem {\n display() {}\n}\n\n// Concrete Products: Sofa, Chair, Table\nc"
},
{
"path": "Factory Method Design Pattern/Furniture/Python/furniture.py",
"chars": 1311,
"preview": "# Abstract Product: Furniture Item\nclass FurnitureItem:\n def display(self):\n pass\n\n# Concrete Products: Sofa, "
},
{
"path": "Factory Method Design Pattern/Logger/C++/common.hpp",
"chars": 112,
"preview": "#pragma once\n\n#include <iostream>\n\nusing namespace std;\n\nenum class LogLevel {\n DEBUG,\n INFO,\n ERROR\n};"
},
{
"path": "Factory Method Design Pattern/Logger/C++/debug_logger.cpp",
"chars": 112,
"preview": "#include \"debug_logger.hpp\"\n\nvoid DebugLogger::log(const string &msg)\n{\n cout << \"DEBUG : \" << msg << endl;\n}"
},
{
"path": "Factory Method Design Pattern/Logger/C++/debug_logger.hpp",
"chars": 125,
"preview": "#pragma once\n#include \"ilogger.hpp\"\n\nclass DebugLogger : public ILogger {\n public:\n void log(const string& msg"
},
{
"path": "Factory Method Design Pattern/Logger/C++/debug_logger_factory.hpp",
"chars": 191,
"preview": "#pragma once\n\n#include \"logger_factory.hpp\"\n\nclass DebugLoggerFactory : public ILoggerFactory{\n public:\n ILogg"
},
{
"path": "Factory Method Design Pattern/Logger/C++/error_logger.cpp",
"chars": 106,
"preview": "#include \"error_logger.hpp\"\n\nvoid ErrorLogger::log(const string& msg) {\n cout<<\"ERROR : \"<<msg<<endl;\n}"
},
{
"path": "Factory Method Design Pattern/Logger/C++/error_logger.hpp",
"chars": 124,
"preview": "#pragma once\n#include \"ilogger.hpp\"\n\nclass ErrorLogger : public ILogger{\n public:\n void log(const string& msg)"
},
{
"path": "Factory Method Design Pattern/Logger/C++/error_logger_factory.hpp",
"chars": 191,
"preview": "#pragma once\n\n#include \"logger_factory.hpp\"\n\nclass ErrorLoggerFactory : public ILoggerFactory{\n public:\n ILogg"
},
{
"path": "Factory Method Design Pattern/Logger/C++/ilogger.hpp",
"chars": 145,
"preview": "#pragma once\n#include \"common.hpp\"\n\nclass ILogger {\n public:\n virtual void log(const string& msg) = 0;\n "
},
{
"path": "Factory Method Design Pattern/Logger/C++/info_logger.cpp",
"chars": 103,
"preview": "#include \"info_logger.hpp\"\n\nvoid InfoLogger::log(const string& msg) {\n cout<<\"INFO : \"<<msg<<endl;\n}"
},
{
"path": "Factory Method Design Pattern/Logger/C++/info_logger.hpp",
"chars": 124,
"preview": "#pragma once\n#include \"ilogger.hpp\"\n\nclass InfoLogger : public ILogger {\n public:\n void log(const string& msg)"
},
{
"path": "Factory Method Design Pattern/Logger/C++/info_logger_factory.hpp",
"chars": 189,
"preview": "#pragma once\n\n#include \"logger_factory.hpp\"\n\nclass InfoLoggerFactory : public ILoggerFactory{\n public:\n ILogge"
},
{
"path": "Factory Method Design Pattern/Logger/C++/logger_factory.hpp",
"chars": 202,
"preview": "#pragma once\n#include \"ilogger.hpp\"\n#include \"debug_logger.hpp\"\n#include \"info_logger.hpp\"\n#include \"error_logger.hpp\"\n\n"
},
{
"path": "Factory Method Design Pattern/Logger/C++/main.cpp",
"chars": 717,
"preview": "#include \"info_logger_factory.hpp\"\n#include \"debug_logger_factory.hpp\"\n#include \"error_logger_factory.hpp\"\n\nint main() {"
},
{
"path": "Factory Method Design Pattern/Logger/JAVA/LoggerDemo.java",
"chars": 1212,
"preview": "interface ILogger {\n void log(String msg);\n}\n\nclass DebugLogger implements ILogger {\n @Override\n public void lo"
},
{
"path": "Iterator Design Pattern/C++/amazon_inventory.cpp",
"chars": 2415,
"preview": "#include <iostream>\n\nusing namespace std;\n\n// Product class representing individual products\nclass Product {\n private"
},
{
"path": "Iterator Design Pattern/JAVA/AmazonInventory.java",
"chars": 2355,
"preview": "import java.util.*;\n\n// Product class representing individual products\nclass Product {\n private String name;\n priv"
},
{
"path": "Observer Design Pattern/C++/order_status.cpp",
"chars": 3094,
"preview": "#include <iostream>\nusing namespace std;\n\nclass Order;\n\n// Observer interface\nclass Observer\n{\npublic:\n virtual void "
},
{
"path": "Observer Design Pattern/JAVA/OrderStatus.java",
"chars": 2910,
"preview": "import java.util.*;\n\ninterface Observer {\n void update(Order order);\n}\n\nclass Customer implements Observer {\n priv"
},
{
"path": "Prototype Design Pattern/C++/product.cpp",
"chars": 1428,
"preview": "#include <iostream>\nusing namespace std;\n\n// Abstract base class representing a prototype for products\nclass ProductProt"
},
{
"path": "Prototype Design Pattern/C++/router.cpp",
"chars": 2244,
"preview": "#include <iostream>\n\nusing namespace std;\n\nclass NetworkDevice {\npublic:\n virtual NetworkDevice* clone() const = 0;\n "
},
{
"path": "Prototype Design Pattern/JAVA/ProductDemo.java",
"chars": 1347,
"preview": "// Abstract base class representing a prototype for products\nabstract class ProductPrototype {\n public abstract Produ"
},
{
"path": "Prototype Design Pattern/JAVA/RouterDemo.java",
"chars": 2284,
"preview": "abstract class NetworkDevice {\n public abstract NetworkDevice clone();\n\n public abstract void display();\n\n publ"
},
{
"path": "Proxy Design Pattern/C++/image.cpp",
"chars": 1368,
"preview": "#include <iostream>\nusing namespace std;\n\n// The Subject interface represents the Image.\nclass Image {\npublic:\n virtu"
},
{
"path": "Proxy Design Pattern/JAVA/ImageDemo.java",
"chars": 1194,
"preview": "interface Image {\n void display();\n}\n\nclass RealImage implements Image {\n private String filename;\n\n public Rea"
},
{
"path": "Simple Factory Design Pattern/C++/common.hpp",
"chars": 112,
"preview": "#pragma once\n\n#include <iostream>\n\nusing namespace std;\n\nenum class LogLevel {\n DEBUG,\n INFO,\n ERROR\n};"
},
{
"path": "Simple Factory Design Pattern/C++/debug_logger.cpp",
"chars": 112,
"preview": "#include \"debug_logger.hpp\"\n\nvoid DebugLogger::log(const string &msg)\n{\n cout << \"DEBUG : \" << msg << endl;\n}"
},
{
"path": "Simple Factory Design Pattern/C++/debug_logger.hpp",
"chars": 125,
"preview": "#pragma once\n#include \"ilogger.hpp\"\n\nclass DebugLogger : public ILogger {\n public:\n void log(const string& msg"
},
{
"path": "Simple Factory Design Pattern/C++/error_logger.cpp",
"chars": 106,
"preview": "#include \"error_logger.hpp\"\n\nvoid ErrorLogger::log(const string& msg) {\n cout<<\"ERROR : \"<<msg<<endl;\n}"
},
{
"path": "Simple Factory Design Pattern/C++/error_logger.hpp",
"chars": 124,
"preview": "#pragma once\n#include \"ilogger.hpp\"\n\nclass ErrorLogger : public ILogger{\n public:\n void log(const string& msg)"
},
{
"path": "Simple Factory Design Pattern/C++/ilogger.hpp",
"chars": 145,
"preview": "#pragma once\n#include \"common.hpp\"\n\nclass ILogger {\n public:\n virtual void log(const string& msg) = 0;\n "
},
{
"path": "Simple Factory Design Pattern/C++/info_logger.cpp",
"chars": 103,
"preview": "#include \"info_logger.hpp\"\n\nvoid InfoLogger::log(const string& msg) {\n cout<<\"INFO : \"<<msg<<endl;\n}"
},
{
"path": "Simple Factory Design Pattern/C++/info_logger.hpp",
"chars": 124,
"preview": "#pragma once\n#include \"ilogger.hpp\"\n\nclass InfoLogger : public ILogger {\n public:\n void log(const string& msg)"
},
{
"path": "Simple Factory Design Pattern/C++/logger_factory.cpp",
"chars": 322,
"preview": "#include \"logger_factory.hpp\"\n\nILogger* LoggerFactory::createLogger(LogLevel pLogLevel) {\n if(pLogLevel == LogLevel::"
},
{
"path": "Simple Factory Design Pattern/C++/logger_factory.hpp",
"chars": 214,
"preview": "#pragma once\n#include \"ilogger.hpp\"\n#include \"debug_logger.hpp\"\n#include \"info_logger.hpp\"\n#include \"error_logger.hpp\"\n\n"
},
{
"path": "Simple Factory Design Pattern/C++/main.cpp",
"chars": 497,
"preview": "#include \"logger_factory.hpp\"\n\nint main() {\n ILogger* debugLogger = LoggerFactory::createLogger(LogLevel::DEBUG);\n "
},
{
"path": "Simple Factory Design Pattern/JAVA/Main.java",
"chars": 469,
"preview": "import logger.*;\n\n\npublic class Main {\n public static void main(String[] args) {\n ILogger debugLogger = Logger"
},
{
"path": "Simple Factory Design Pattern/JAVA/logger/DebugLogger.java",
"chars": 150,
"preview": "package logger;\n\npublic class DebugLogger implements ILogger {\n public void log(String msg) {\n System.out.prin"
},
{
"path": "Simple Factory Design Pattern/JAVA/logger/ErrorLogger.java",
"chars": 150,
"preview": "package logger;\n\npublic class ErrorLogger implements ILogger {\n public void log(String msg) {\n System.out.prin"
},
{
"path": "Simple Factory Design Pattern/JAVA/logger/ILogger.java",
"chars": 73,
"preview": "package logger;\n\npublic interface ILogger {\n void log (String msg);\n}\n"
},
{
"path": "Simple Factory Design Pattern/JAVA/logger/InfoLogger.java",
"chars": 148,
"preview": "package logger;\n\npublic class InfoLogger implements ILogger {\n public void log(String msg) {\n System.out.print"
},
{
"path": "Simple Factory Design Pattern/JAVA/logger/LogLevel.java",
"chars": 66,
"preview": "package logger;\n\npublic enum LogLevel {\n DEBUG, INFO, ERROR\n}\n\n"
},
{
"path": "Simple Factory Design Pattern/JAVA/logger/LoggerFactory.java",
"chars": 397,
"preview": "package logger;\n\npublic class LoggerFactory {\n public static ILogger createLogger(LogLevel logLevel) {\n switch"
},
{
"path": "Singleton Design Pattern/C++/payment_gateway.cpp",
"chars": 1435,
"preview": "#include <iostream>\n\nusing namespace std;\n\nclass PaymentGatewayManager\n{\n\nprivate:\n PaymentGatewayManager()\n {\n "
},
{
"path": "Singleton Design Pattern/JAVA/PaymentGateway.java",
"chars": 1681,
"preview": "import java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReentrantLock;\n\nclass PaymentGatewayManager {\n"
},
{
"path": "State Design Pattern/C++/state.cpp",
"chars": 2263,
"preview": "#include <iostream>\nusing namespace std;\n\n// Define the RideState interface.\nclass RideState {\npublic:\n virtual void "
},
{
"path": "State Design Pattern/JAVA/StateDemo.java",
"chars": 2388,
"preview": "// Define the RideState interface.\ninterface RideState {\n void handleRequest();\n void handleCancel();\n}\n\n// Implem"
},
{
"path": "Strategy Design Pattern/C++/payment.cpp",
"chars": 1919,
"preview": "#include <iostream>\nusing namespace std;\n\nclass PaymentStrategy {\npublic:\n virtual void processPayment(double amount)"
},
{
"path": "Strategy Design Pattern/JAVA/PaymentDemo.java",
"chars": 2102,
"preview": "// PaymentStrategy interface\ninterface PaymentStrategy {\n void processPayment(double amount);\n}\n\n// Concrete PaymentS"
},
{
"path": "Strategy and Factory Design Pattern/C++/payment.cpp",
"chars": 2397,
"preview": "#include <iostream>\nusing namespace std;\n\n// PaymentStrategy interface\nclass PaymentStrategy {\npublic:\n virtual ~Paym"
},
{
"path": "Strategy and Factory Design Pattern/JAVA/PaymentDemo.java",
"chars": 2478,
"preview": "// PaymentStrategy interface\ninterface PaymentStrategy {\n void processPayment(double amount);\n}\n\n// Concrete PaymentS"
},
{
"path": "Template Design Pattern/C++/amazon_order.cpp",
"chars": 2052,
"preview": "#include <iostream>\nusing namespace std;\n\n// Abstract class representing the template for order processing\nclass OrderPr"
},
{
"path": "Template Design Pattern/JAVA/AmazonOrderProcessor.java",
"chars": 2056,
"preview": "// Abstract class representing the template for order processing\nabstract class OrderProcessingTemplate {\n public voi"
}
]
// ... and 11 more files (download for full content)
About this extraction
This page contains the full source code of the keertipurswani/LLD-Design-Patterns GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 97 files (125.6 KB), approximately 29.8k tokens, and a symbol index with 945 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.