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 // 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 #include 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"<>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 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!"<AnalyzeData(); delete tool2; return 0; } ================================================ FILE: Adapter Design Pattern/Object Adapter/C++/xml_to_json.cpp ================================================ #include 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!"<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 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 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 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 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: "<processOrder(order); } ~OrderValidationHandler() { cout<<"validation handler dtor called"<processOrder(order); } ~PaymentProcessingHanlder() { cout<<"PaymentProcessingHanlder dtor called"<processOrder(order); } ~OrderPreparationHandler() { cout<<"OrderPreparationHandler dtor called"<processOrder(order); } ~DeliveryAssignmentHandler() { cout<<"DeliveryAssignmentHandler dtor called"<processOrder(order); } ~OrderTrackingHandler() { cout<<"OrderTrackingHandler dtor called"<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 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 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 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 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 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 class Directory : public FileSystemComponent { private: string name; vector 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 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 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 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 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 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 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 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 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 #include // 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 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 : "<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 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& products; size_t current; public: ProductIterator(vector& 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 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 products; private int current; public ProductIterator(List 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 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 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 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 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 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 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 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 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 : "<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 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 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<<"--------------------------------------------------"< 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 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 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(); } }