├── README.md ├── cpp ├── Basics │ ├── OOPS │ │ ├── Card.cpp │ │ ├── Client.cpp │ │ ├── CreditCard.cpp │ │ ├── DebitCard.cpp │ │ ├── PaymentMethod.cpp │ │ ├── PaymentService.cpp │ │ ├── UPI.cpp │ │ └── Wallet.cpp │ └── UML │ │ ├── AggregationExample.cpp │ │ ├── AssociationExample.cpp │ │ ├── CompositionExample.cpp │ │ ├── DependencyExample.cpp │ │ ├── InheritanceExample.cpp │ │ └── RealizationExample.cpp ├── BehaviouralPatterns │ ├── CommandPattern │ │ ├── WithCommandPattern.cpp │ │ └── WithoutCommandPattern.cpp │ ├── IteratorPattern │ │ ├── Book.cpp │ │ ├── BookCollectionV1.cpp │ │ ├── BookCollectionV2.cpp │ │ ├── BookCollectionV3.cpp │ │ ├── ClientV1.cpp │ │ ├── ClientV2.cpp │ │ └── ClientV3.cpp │ ├── MediatorPattern │ │ ├── WithMediatorPattern.cpp │ │ └── WithoutMediatorPattern.cpp │ ├── MementoPattern │ │ ├── Caretaker.cpp │ │ ├── EditorMemento.cpp │ │ ├── TextEditor.cpp │ │ └── TextEditorMain.cpp │ ├── ObserverPattern │ │ ├── ObserverPatternExample.cpp │ │ └── WithoutObserverPattern.cpp │ ├── StatePattern │ │ ├── Problem │ │ │ ├── DirectionService.cpp │ │ │ └── WithoutStatePattern.cpp │ │ └── Solution │ │ │ ├── Car.cpp │ │ │ ├── Cycling.cpp │ │ │ ├── DirectionService.cpp │ │ │ ├── Train.cpp │ │ │ ├── TransportationMode.cpp │ │ │ ├── Walking.cpp │ │ │ └── WithStatePattern.cpp │ ├── StrategyPattern │ │ ├── StrategyPattern.cpp │ │ └── WithoutStrategyPattern.cpp │ └── TemplateMethodPattern │ │ ├── WithTemplatePattern.cpp │ │ └── WithoutTemplateMethod.cpp ├── CreationalPatterns │ ├── AbstractFactoryPattern │ │ ├── Problem │ │ │ └── Application.cpp │ │ └── Solution │ │ │ └── Application.cpp │ ├── BuilderPattern │ │ ├── Problem │ │ │ ├── House.cpp │ │ │ └── WithoutBuilderPattern.cpp │ │ └── Solution │ │ │ ├── House.cpp │ │ │ └── WithBuilderPattern.cpp │ ├── FactoryPattern │ │ ├── Problem │ │ │ ├── Bike.cpp │ │ │ ├── Bus.cpp │ │ │ ├── Car.cpp │ │ │ ├── Transport.cpp │ │ │ └── TransportService.cpp │ │ └── Solution │ │ │ ├── Bike.cpp │ │ │ ├── Bus.cpp │ │ │ ├── Car.cpp │ │ │ ├── Transport.cpp │ │ │ ├── TransportFactory.cpp │ │ │ └── TransportService.cpp │ ├── PrototypePattern │ │ ├── Problem │ │ │ ├── GameBoard.cpp │ │ │ ├── GameClientWithoutPrototype.cpp │ │ │ └── GamePiece.cpp │ │ └── Solution │ │ │ ├── GameBoard.cpp │ │ │ ├── GameClientWithPrototype.cpp │ │ │ ├── GamePiece.cpp │ │ │ └── Prototype.cpp │ └── SingletonPattern │ │ ├── Problem │ │ ├── AppSettings.cpp │ │ └── WithoutSingletonPattern.cpp │ │ └── Solution │ │ ├── AppSettings.cpp │ │ └── SingletonPattern.cpp ├── LLDProject │ └── RideSharingApp │ │ ├── V1 │ │ ├── Client.cpp │ │ ├── Driver.cpp │ │ ├── Location.cpp │ │ ├── Passenger.cpp │ │ ├── RideSharingAppService.cpp │ │ └── Vehicle.cpp │ │ └── V2 │ │ ├── Bike.cpp │ │ ├── Car.cpp │ │ ├── Client.cpp │ │ ├── Driver.cpp │ │ ├── FareStrategy.cpp │ │ ├── Location.cpp │ │ ├── Passenger.cpp │ │ ├── Ride.cpp │ │ ├── RideMatchingSystem.cpp │ │ ├── User.cpp │ │ └── Vehicle.cpp ├── SOLIDPrinciples │ ├── DIP │ │ ├── BadCode │ │ │ ├── EmailService.cpp │ │ │ ├── NotificationService.cpp │ │ │ └── SMSService.cpp │ │ └── GoodCode │ │ │ ├── EmailService.cpp │ │ │ ├── Main.cpp │ │ │ ├── NotificationChannel.cpp │ │ │ ├── NotificationService.cpp │ │ │ └── SMSService.cpp │ ├── ISP │ │ ├── BadCode │ │ │ ├── Document.cpp │ │ │ ├── Machine.cpp │ │ │ ├── MultiPurposeMachine.cpp │ │ │ └── SimplePrinter.cpp │ │ └── GoodCode │ │ │ ├── Copier.cpp │ │ │ ├── MultiPurposeMachine.cpp │ │ │ ├── Printer.cpp │ │ │ ├── Scanner.cpp │ │ │ └── SimplePrinter.cpp │ ├── LSP │ │ ├── BadCode │ │ │ ├── File.cpp │ │ │ ├── Main.cpp │ │ │ └── ReadOnlyFile.cpp │ │ └── GoodCode │ │ │ ├── Main.cpp │ │ │ ├── ReadOnlyFile.cpp │ │ │ ├── Readable.cpp │ │ │ ├── ReadableFile.cpp │ │ │ ├── Writable.cpp │ │ │ └── WritableFile.cpp │ ├── OCP │ │ ├── BadCode │ │ │ └── PaymentProcessor.cpp │ │ └── GoodCode │ │ │ ├── CreditCard.cpp │ │ │ ├── DebitCard.cpp │ │ │ ├── Main.cpp │ │ │ ├── PayPal.cpp │ │ │ ├── PaymentMethod.cpp │ │ │ ├── PaymentProcessor.cpp │ │ │ └── UPI.cpp │ └── SRP │ │ ├── BadCode │ │ ├── Invoice.cpp │ │ └── Invoice.java │ │ └── GoodCode │ │ ├── EmailService.cpp │ │ ├── EmailService.java │ │ ├── Invoice.cpp │ │ ├── Invoice.java │ │ ├── InvoiceRepository.cpp │ │ ├── InvoiceRepository.java │ │ └── Main.cpp └── StructuralPatterns │ ├── AdapterPattern │ ├── Client.cpp │ ├── Client.java │ ├── EmailNotificationService.cpp │ ├── EmailNotificationService.java │ ├── NotificationService.cpp │ ├── NotificationService.java │ ├── SendGridAdapter.cpp │ ├── SendGridAdapter.java │ ├── SendGridService.cpp │ └── SendGridService.java │ ├── CompositePattern │ ├── Problem │ │ ├── File.cpp │ │ ├── File.java │ │ ├── FileSystemApp.cpp │ │ ├── FileSystemApp.java │ │ ├── Folder.cpp │ │ └── Folder.java │ └── Solution │ │ ├── File.cpp │ │ ├── File.java │ │ ├── FileSystemApp.cpp │ │ ├── FileSystemApp.java │ │ ├── FileSystemComponent.cpp │ │ ├── FileSystemComponent.java │ │ ├── Folder.cpp │ │ └── Folder.java │ ├── DecoratorPattern │ ├── Problem │ │ ├── BasicPizza.cpp │ │ ├── BasicPizza.java │ │ ├── CheeseOlivePizza.cpp │ │ ├── CheeseOlivePizza.java │ │ ├── CheesePizza.cpp │ │ ├── CheesePizza.java │ │ ├── Pizza.cpp │ │ ├── Pizza.java │ │ ├── PizzaApp.cpp │ │ └── PizzaApp.java │ └── Solution │ │ ├── BasicPizza.cpp │ │ ├── BasicPizza.java │ │ ├── CheeseDecorator.cpp │ │ ├── CheeseDecorator.java │ │ ├── MushroomDecorator.cpp │ │ ├── MushroomDecorator.java │ │ ├── OliveDecorator.cpp │ │ ├── OliveDecorator.java │ │ ├── Pizza.cpp │ │ ├── Pizza.java │ │ ├── PizzaApp.cpp │ │ ├── PizzaApp.java │ │ ├── PizzaDecorator.cpp │ │ └── PizzaDecorator.java │ ├── FacadePattern │ ├── Problem │ │ ├── Client.cpp │ │ ├── OrderService.cpp │ │ ├── PaymentService.cpp │ │ └── UserService.cpp │ └── Solution │ │ ├── APIGateway.cpp │ │ ├── Client.cpp │ │ ├── OrderService.cpp │ │ ├── PaymentService.cpp │ │ └── UserService.cpp │ ├── FlyWeightPattern │ ├── Problem │ │ ├── Bullet.cpp │ │ └── Game.cpp │ └── Solution │ │ ├── Bullet.cpp │ │ ├── BulletType.cpp │ │ ├── BulletTypeFactory.cpp │ │ └── Game.cpp │ └── ProxyPattern │ ├── Problem │ ├── Client.cpp │ ├── Image.cpp │ └── RealImage.cpp │ └── Solution │ ├── Client.cpp │ ├── Image.cpp │ ├── ProxyImage.cpp │ └── RealImage.cpp ├── design-patterns ├── .gitignore ├── .idea │ ├── .gitignore │ ├── encodings.xml │ ├── misc.xml │ ├── uiDesigner.xml │ └── vcs.xml ├── pom.xml └── src │ └── main │ └── java │ └── org │ └── prateek │ ├── Basics │ ├── OOPS │ │ ├── Card.java │ │ ├── Client.java │ │ ├── CreditCard.java │ │ ├── DebitCard.java │ │ ├── PaymentMethod.java │ │ ├── PaymentService.java │ │ ├── UPI.java │ │ └── Wallet.java │ └── UML │ │ ├── AggregationExample.java │ │ ├── AssociationExample.java │ │ ├── CompositionExample.java │ │ ├── DependencyExample.java │ │ ├── InheritanceExample.java │ │ └── RealizationExample.java │ ├── BehaviouralPatterns │ ├── CommandPattern │ │ ├── WithCommandPattern.java │ │ └── WithoutCommandPattern.java │ ├── IteratorPattern │ │ ├── Book.java │ │ ├── BookCollectionV1.java │ │ ├── BookCollectionV2.java │ │ ├── BookCollectionV3.java │ │ ├── ClientV1.java │ │ ├── ClientV2.java │ │ └── ClientV3.java │ ├── MediatorPattern │ │ ├── WithMediatorPattern.java │ │ └── WithoutMediatorPattern.java │ ├── MementoPattern │ │ ├── Caretaker.java │ │ ├── EditorMemento.java │ │ ├── TextEditor.java │ │ └── TextEditorMain.java │ ├── ObserverPattern │ │ ├── ObserverPatternExample.java │ │ └── WithoutObserverPattern.java │ ├── StatePattern │ │ ├── Problem │ │ │ ├── DirectionService.java │ │ │ └── WithoutStatePattern.java │ │ └── Solution │ │ │ ├── Car.java │ │ │ ├── Cycling.java │ │ │ ├── DirectionService.java │ │ │ ├── Train.java │ │ │ ├── TransportationMode.java │ │ │ ├── Walking.java │ │ │ └── WithStatePattern.java │ ├── StrategyPattern │ │ ├── StrategyPattern.java │ │ └── WithoutStrategyPattern.java │ └── TemplateMethodPattern │ │ ├── WithTemplatePattern.java │ │ └── WithoutTemplateMethod.java │ ├── CreationalPatterns │ ├── AbstractFactoryPattern │ │ ├── Problem │ │ │ └── Application.java │ │ └── Solution │ │ │ └── Application.java │ ├── BuilderPattern │ │ ├── Problem │ │ │ ├── House.java │ │ │ └── WithoutBuilderPattern.java │ │ └── Solution │ │ │ ├── House.java │ │ │ └── WithBuilderPattern.java │ ├── FactoryPattern │ │ ├── Problem │ │ │ ├── Bike.java │ │ │ ├── Bus.java │ │ │ ├── Car.java │ │ │ ├── Transport.java │ │ │ └── TransportService.java │ │ └── Solution │ │ │ ├── Bike.java │ │ │ ├── Bus.java │ │ │ ├── Car.java │ │ │ ├── Transport.java │ │ │ ├── TransportFactory.java │ │ │ └── TransportService.java │ ├── PrototypePattern │ │ ├── Problem │ │ │ ├── GameBoard.java │ │ │ ├── GameClientWithoutPrototype.java │ │ │ └── GamePiece.java │ │ └── Solution │ │ │ ├── GameBoard.java │ │ │ ├── GameClientWithPrototype.java │ │ │ ├── GamePiece.java │ │ │ └── Prototype.java │ └── SingletonPattern │ │ ├── Problem │ │ ├── AppSettings.java │ │ └── WithoutSingletonPattern.java │ │ └── Solution │ │ ├── AppSettings.java │ │ └── SingletonPattern.java │ ├── LLDProject │ └── RideSharingApp │ │ ├── V1 │ │ ├── Client.java │ │ ├── Driver.java │ │ ├── Location.java │ │ ├── Passenger.java │ │ ├── RideSharingAppService.java │ │ └── Vehicle.java │ │ └── V2 │ │ ├── Bike.java │ │ ├── Car.java │ │ ├── Client.java │ │ ├── Driver.java │ │ ├── FareStrategy.java │ │ ├── Location.java │ │ ├── Passenger.java │ │ ├── Ride.java │ │ ├── RideMatchingSystem.java │ │ ├── User.java │ │ └── Vehicle.java │ ├── SOLIDPrinciples │ ├── DIP │ │ ├── BadCode │ │ │ ├── EmailService.java │ │ │ ├── NotificationService.java │ │ │ └── SMSService.java │ │ └── GoodCode │ │ │ ├── EmailService.java │ │ │ ├── Main.java │ │ │ ├── NotificationChannel.java │ │ │ ├── NotificationService.java │ │ │ └── SMSService.java │ ├── ISP │ │ ├── BadCode │ │ │ ├── Document.java │ │ │ ├── Machine.java │ │ │ ├── MultiPurposeMachine.java │ │ │ └── SimplePrinter.java │ │ └── GoodCode │ │ │ ├── Copier.java │ │ │ ├── MultiPurposeMachine.java │ │ │ ├── Printer.java │ │ │ ├── Scanner.java │ │ │ └── SimplerPrinter.java │ ├── LSP │ │ ├── BadCode │ │ │ ├── File.java │ │ │ ├── Main.java │ │ │ └── ReadOnlyFile.java │ │ └── GoodCode │ │ │ ├── Main.java │ │ │ ├── ReadOnlyFile.java │ │ │ ├── Readable.java │ │ │ ├── ReadableFile.java │ │ │ ├── Writable.java │ │ │ └── WritableFile.java │ ├── OCP │ │ ├── BadCode │ │ │ └── PaymentProcessor.java │ │ └── GoodCode │ │ │ ├── CreditCard.java │ │ │ ├── DebitCard.java │ │ │ ├── Main.java │ │ │ ├── PayPal.java │ │ │ ├── PaymentMethod.java │ │ │ ├── PaymentProcessor.java │ │ │ └── UPI.java │ └── SRP │ │ ├── BadCode │ │ └── Invoice.java │ │ └── GoodCode │ │ ├── EmailService.java │ │ ├── Invoice.java │ │ └── InvoiceRepository.java │ └── StructuralPatterns │ ├── AdapterPattern │ ├── Client.java │ ├── EmailNotificationService.java │ ├── NotificationService.java │ ├── SendGridAdapter.java │ └── SendGridService.java │ ├── CompositePattern │ ├── Problem │ │ ├── File.java │ │ ├── FileSystemApp.java │ │ └── Folder.java │ └── Solution │ │ ├── File.java │ │ ├── FileSystemApp.java │ │ ├── FileSystemComponent.java │ │ └── Folder.java │ ├── DecoratorPattern │ ├── Problem │ │ ├── BasicPizza.java │ │ ├── CheeseOlivePizza.java │ │ ├── CheesePizza.java │ │ ├── Pizza.java │ │ └── PizzaApp.java │ └── Solution │ │ ├── BasicPizza.java │ │ ├── CheeseDecorator.java │ │ ├── MushroomDecorator.java │ │ ├── OliveDecorator.java │ │ ├── Pizza.java │ │ ├── PizzaApp.java │ │ └── PizzaDecorator.java │ ├── FacadePattern │ ├── Problem │ │ ├── Client.java │ │ ├── OrderService.java │ │ ├── PaymentService.java │ │ └── UserService.java │ └── Solution │ │ ├── APIGateway.java │ │ ├── Client.java │ │ ├── OrderService.java │ │ ├── PaymentService.java │ │ └── UserService.java │ ├── FlyWeightPattern │ ├── Problem │ │ ├── Bullet.java │ │ └── Game.java │ └── Solution │ │ ├── Bullet.java │ │ ├── BulletType.java │ │ ├── BulletTypeFactory.java │ │ └── Game.java │ └── ProxyPattern │ ├── Problem │ ├── Client.java │ ├── Image.java │ └── RealImage.java │ └── Solution │ ├── Client.java │ ├── Image.java │ ├── ProxyImage.java │ └── RealImage.java └── solutions ├── Adapter ├── Exercise.java ├── LegacyWeatherService.java ├── NewWeatherService.java ├── NewWeatherServiceAdapter.java └── WeatherService.java ├── Builder ├── Exercise.java ├── Meal.java └── MealBuilder.java ├── Command ├── Command.java ├── Exercise.java ├── Fan.java ├── FanCommands.java ├── Light.java ├── LightCommands.java └── RemoteControl.java ├── Composite ├── Exercise.java ├── MenuComponent.java ├── MenuItem.java └── MenuSection.java ├── Decorator ├── BasicCoffee.java ├── Coffee.java ├── CoffeeDecorator.java ├── Exercise.java ├── Milk.java ├── Sugar.java └── WhippedCream.java ├── Facade ├── DVDPlayer.java ├── Exercise.java ├── HomeTheaterFacade.java ├── LightingControl.java ├── Projector.java └── SoundSystem.java ├── Factory ├── Document.java ├── DocumentFactory.java ├── Exercise.java ├── HTMLDocument.java ├── PDFDocument.java └── WordDocument.java ├── Flyweight ├── CharacterFactory.java ├── CharacterFlyweight.java ├── ConcreteCharacter.java ├── Document.java └── Exercise.java ├── Iterator ├── EmailNotification.java ├── Exercise.java ├── Notification.java ├── NotificationCollection.java ├── NotificationManager.java ├── PushNotification.java └── SMSNotification.java ├── Mediator ├── Airplane.java ├── ControlTower.java ├── Exercise.java └── Mediator.java ├── Memento ├── Caretaker.java ├── EditorMemento.java ├── Exercise.java └── GraphicEditor.java ├── Observer ├── Exercise.java ├── InvestorA.java ├── InvestorB.java ├── Observer.java ├── StockMarket.java └── Subject.java ├── Prototype ├── Archer.java ├── Character.java ├── Exercise.java ├── Mage.java └── Warrior.java ├── Proxy ├── Exercise.java ├── NetworkService.java ├── NetworkServiceProxy.java └── RealNetworkService.java ├── Singleton ├── Exercise.java └── Logger.java ├── State ├── Exercise.java ├── MediaPlayer.java ├── PausedState.java ├── PlayingState.java ├── State.java └── StoppedState.java ├── Strategy ├── Document.java ├── Exercise.java ├── HTMLFormatter.java ├── MarkdownFormatter.java ├── PlainTextFormatter.java └── TextFormatter.java └── Template ├── EmployeeReport.java ├── Exercise.java ├── InventoryReport.java ├── ReportTemplate.java └── SalesReport.java /cpp/Basics/OOPS/Card.cpp: -------------------------------------------------------------------------------- 1 | #ifndef CARD_CPP 2 | #define CARD_CPP 3 | 4 | #include 5 | 6 | class PaymentMethod; 7 | 8 | class Card : public PaymentMethod { 9 | protected: 10 | std::string cardNo; 11 | std::string userName; 12 | 13 | public: 14 | Card(const std::string& cardNo, const std::string& name) 15 | : cardNo(cardNo), userName(name) {} 16 | 17 | std::string getCardNo() { return cardNo; } 18 | std::string getUserName() { return userName; } 19 | }; 20 | 21 | #endif -------------------------------------------------------------------------------- /cpp/Basics/OOPS/Client.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "paymentservice.cpp" 3 | #include "creditcard.cpp" 4 | #include "debitcard.cpp" 5 | #include "upi.cpp" 6 | #include "wallet.cpp" 7 | 8 | int main() { 9 | PaymentService ps; 10 | ps.addPaymentMethod("PrateekDebitCard", new DebitCard("1234", "Prateek Narang")); 11 | ps.addPaymentMethod("PrateekCreditCard", new CreditCard("5678", "Prateek Narang")); 12 | ps.addPaymentMethod("PrateekUPI", new UPI("prateek27")); 13 | ps.addPaymentMethod("PrateekWallet", new Wallet()); 14 | 15 | ps.makePayment("PrateekUPI"); 16 | ps.makePayment("PrateekDebitCard"); 17 | ps.makePayment("PrateekWallet"); 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /cpp/Basics/OOPS/CreditCard.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "card.cpp" 4 | 5 | class CreditCard : public Card { 6 | public: 7 | CreditCard(const std::string& cardNo, const std::string& name) 8 | : Card(cardNo, name) {} 9 | 10 | void pay() { 11 | std::cout << "Making payment via Credit Card" << std::endl; 12 | } 13 | }; -------------------------------------------------------------------------------- /cpp/Basics/OOPS/DebitCard.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "card.cpp" 4 | 5 | class DebitCard : public Card { 6 | public: 7 | DebitCard(const std::string& cardNo, const std::string& name) 8 | : Card(cardNo, name) {} 9 | 10 | void pay() { 11 | std::cout << "Making payment via Debit Card " << cardNo << std::endl; 12 | } 13 | }; -------------------------------------------------------------------------------- /cpp/Basics/OOPS/PaymentMethod.cpp: -------------------------------------------------------------------------------- 1 | #ifndef PAYMENTMETHOD_CPP 2 | #define PAYMENTMETHOD_CPP 3 | 4 | class PaymentMethod { 5 | public: 6 | virtual void pay() = 0; 7 | virtual ~PaymentMethod() {} 8 | }; 9 | 10 | #endif -------------------------------------------------------------------------------- /cpp/Basics/OOPS/PaymentService.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "paymentmethod.cpp" 4 | 5 | class PaymentService { 6 | private: 7 | std::map paymentMethods; 8 | 9 | public: 10 | PaymentService() {} 11 | 12 | void addPaymentMethod(const std::string& name, PaymentMethod* pm) { 13 | paymentMethods[name] = pm; 14 | } 15 | 16 | void makePayment(const std::string& name) { 17 | std::map::iterator it = paymentMethods.find(name); 18 | if (it != paymentMethods.end()) { 19 | it->second->pay(); 20 | } 21 | } 22 | 23 | ~PaymentService() { 24 | for (std::map::iterator it = paymentMethods.begin(); 25 | it != paymentMethods.end(); ++it) { 26 | delete it->second; 27 | } 28 | } 29 | }; -------------------------------------------------------------------------------- /cpp/Basics/OOPS/UPI.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "paymentmethod.cpp" 4 | 5 | class UPI : public PaymentMethod { 6 | private: 7 | std::string upiId; 8 | 9 | public: 10 | UPI(const std::string& id) : upiId(id) {} 11 | 12 | void pay() { 13 | std::cout << "Making payment via UPI " << upiId << std::endl; 14 | } 15 | }; -------------------------------------------------------------------------------- /cpp/Basics/OOPS/Wallet.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "paymentmethod.cpp" 3 | 4 | class Wallet : public PaymentMethod { 5 | public: 6 | void pay() { 7 | std::cout << "Making payment via wallet" << std::endl; 8 | } 9 | }; -------------------------------------------------------------------------------- /cpp/BehaviouralPatterns/IteratorPattern/BookCollectionV1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "Book.cpp" 5 | 6 | class BookCollectionV1 { 7 | private: 8 | std::vector books; 9 | 10 | public: 11 | void addBook(const Book& book) { 12 | books.push_back(book); 13 | } 14 | 15 | std::vector getBooks() const { 16 | return books; 17 | } 18 | }; -------------------------------------------------------------------------------- /cpp/BehaviouralPatterns/IteratorPattern/ClientV1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "Book.cpp" 5 | #include "BookCollectionV1.cpp" 6 | 7 | int main() { 8 | BookCollectionV1 bookCollection; 9 | bookCollection.addBook(Book("C++ Book")); 10 | bookCollection.addBook(Book("Java Book")); 11 | bookCollection.addBook(Book("Python Book")); 12 | 13 | for (size_t i = 0; i < bookCollection.getBooks().size(); ++i) { 14 | std::cout << bookCollection.getBooks()[i].toString() << std::endl; 15 | } 16 | 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /cpp/BehaviouralPatterns/IteratorPattern/ClientV2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include "Book.cpp" 6 | #include "BookCollectionV2.cpp" 7 | 8 | int main() { 9 | BookCollectionV2 bookCollection; 10 | bookCollection.addBook(Book("C++ Book")); 11 | bookCollection.addBook(Book("Java Book")); 12 | bookCollection.addBook(Book("Python Book")); 13 | 14 | // Use the iterator directly 15 | for (auto it = bookCollection.begin(); it != bookCollection.end(); ++it) { 16 | std::cout << (*it).toString() << std::endl; 17 | } 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /cpp/BehaviouralPatterns/IteratorPattern/ClientV3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "BookCollectionV3.cpp" 3 | 4 | int main() { 5 | BookCollectionV3 bookCollection; 6 | bookCollection.addBook(Book("C++ Book")); 7 | bookCollection.addBook(Book("Java Book")); 8 | bookCollection.addBook(Book("Python Book")); 9 | 10 | // Use the custom iterator to iterate over the collection 11 | for (auto it = bookCollection.begin(); it != bookCollection.end(); ++it) { 12 | std::cout << (*it).toString() << std::endl; 13 | } 14 | 15 | return 0; 16 | } -------------------------------------------------------------------------------- /cpp/BehaviouralPatterns/MediatorPattern/WithoutMediatorPattern.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // User class 7 | class User { 8 | private: 9 | string name; 10 | 11 | public: 12 | User(const string& name) : name(name) {} 13 | 14 | void sendMessage(const string& msg, User& recipient) { 15 | cout << name << " sending " << msg << " to " << recipient.getName() << endl; 16 | } 17 | 18 | string getName() const { 19 | return name; 20 | } 21 | }; 22 | 23 | // Main function 24 | int main() { 25 | User rahul("Rahul"); 26 | User amit("Amit"); 27 | User neha("Neha"); 28 | 29 | rahul.sendMessage("Hello", amit); 30 | rahul.sendMessage("Hello", neha); 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /cpp/BehaviouralPatterns/MementoPattern/Caretaker.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "EditorMemento.cpp" 3 | #include "TextEditor.cpp" 4 | 5 | class Caretaker { 6 | private: 7 | std::stack history; 8 | 9 | public: 10 | void saveState(TextEditor& editor) { 11 | history.push(editor.save()); 12 | } 13 | 14 | void undo(TextEditor& editor) { 15 | if (history.size() > 1) { 16 | history.pop(); 17 | EditorMemento memento = history.top(); 18 | editor.restore(memento); 19 | } 20 | } 21 | }; -------------------------------------------------------------------------------- /cpp/BehaviouralPatterns/MementoPattern/EditorMemento.cpp: -------------------------------------------------------------------------------- 1 | #ifndef EDITORMEMENTO_CPP 2 | #define EDITORMEMENTO_CPP 3 | 4 | #include 5 | 6 | class EditorMemento { 7 | private: 8 | std::string content; 9 | 10 | public: 11 | EditorMemento(const std::string& text) : content(text) {} 12 | 13 | std::string getContent() const { 14 | return content; 15 | } 16 | }; 17 | 18 | #endif -------------------------------------------------------------------------------- /cpp/BehaviouralPatterns/MementoPattern/TextEditor.cpp: -------------------------------------------------------------------------------- 1 | #ifndef TEXTEDITOR_CPP 2 | #define TEXTEDITOR_CPP 3 | 4 | #include 5 | #include "EditorMemento.cpp" 6 | 7 | class TextEditor { 8 | private: 9 | std::string content; 10 | 11 | public: 12 | void write(const std::string& text) { 13 | content = text; 14 | } 15 | 16 | EditorMemento save() const; 17 | void restore(const EditorMemento& memento); 18 | 19 | std::string getContent() const { 20 | return content; 21 | } 22 | }; 23 | 24 | EditorMemento TextEditor::save() const { 25 | return EditorMemento(content); 26 | } 27 | 28 | void TextEditor::restore(const EditorMemento& memento) { 29 | content = memento.getContent(); 30 | } 31 | 32 | #endif -------------------------------------------------------------------------------- /cpp/BehaviouralPatterns/MementoPattern/TextEditorMain.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "TextEditor.cpp" 3 | #include "Caretaker.cpp" 4 | 5 | int main() { 6 | TextEditor editor; 7 | Caretaker caretaker; 8 | 9 | editor.write("A"); 10 | caretaker.saveState(editor); 11 | 12 | editor.write("B"); 13 | caretaker.saveState(editor); 14 | 15 | editor.write("C"); 16 | caretaker.saveState(editor); 17 | 18 | caretaker.undo(editor); 19 | 20 | std::cout << editor.getContent() << std::endl; 21 | 22 | return 0; 23 | } -------------------------------------------------------------------------------- /cpp/BehaviouralPatterns/StatePattern/Problem/WithoutStatePattern.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "DirectionService.cpp" 3 | 4 | int main() { 5 | DirectionService directionService(TRAIN); 6 | directionService.setMode(CAR); 7 | 8 | std::cout << directionService.getDirection() << std::endl; 9 | directionService.getETA(); 10 | 11 | return 0; 12 | } -------------------------------------------------------------------------------- /cpp/BehaviouralPatterns/StatePattern/Solution/Car.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "TransportationMode.cpp" 4 | 5 | class Car : public TransportationMode { 6 | public: 7 | int calcETA() override { 8 | std::cout << "Calculating ETA (Car)" << std::endl; 9 | return 3; 10 | } 11 | 12 | std::string getDirection() override { 13 | return "Directions for driving"; 14 | } 15 | }; -------------------------------------------------------------------------------- /cpp/BehaviouralPatterns/StatePattern/Solution/Cycling.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "TransportationMode.cpp" 4 | 5 | class Cycling : public TransportationMode { 6 | public: 7 | int calcETA() override { 8 | std::cout << "Calculating ETA (Cycling)" << std::endl; 9 | return 5; 10 | } 11 | 12 | std::string getDirection() override { 13 | return "Directions for cycling"; 14 | } 15 | }; -------------------------------------------------------------------------------- /cpp/BehaviouralPatterns/StatePattern/Solution/DirectionService.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "TransportationMode.cpp" 4 | 5 | class DirectionService { 6 | private: 7 | TransportationMode* transportationMode; 8 | 9 | public: 10 | DirectionService(TransportationMode* transportationMode) { 11 | this->transportationMode = transportationMode; 12 | } 13 | 14 | void setTransportationMode(TransportationMode* mode) { 15 | this->transportationMode = mode; 16 | } 17 | 18 | int getETA() { 19 | return transportationMode->calcETA(); 20 | } 21 | 22 | std::string getDirection() { 23 | return transportationMode->getDirection(); 24 | } 25 | }; -------------------------------------------------------------------------------- /cpp/BehaviouralPatterns/StatePattern/Solution/Train.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "TransportationMode.cpp" 4 | 5 | class Train : public TransportationMode { 6 | public: 7 | int calcETA() override { 8 | std::cout << "Calculating ETA (Train)" << std::endl; 9 | return 7; 10 | } 11 | 12 | std::string getDirection() override { 13 | return "Directions for train route"; 14 | } 15 | }; -------------------------------------------------------------------------------- /cpp/BehaviouralPatterns/StatePattern/Solution/TransportationMode.cpp: -------------------------------------------------------------------------------- 1 | #ifndef TransportationMode_CPP 2 | #define TransportationMode_CPP 3 | 4 | #include 5 | 6 | class TransportationMode { 7 | public: 8 | virtual int calcETA() = 0; 9 | virtual std::string getDirection() = 0; 10 | virtual ~TransportationMode() = default; 11 | }; 12 | 13 | #endif -------------------------------------------------------------------------------- /cpp/BehaviouralPatterns/StatePattern/Solution/Walking.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "TransportationMode.cpp" 4 | 5 | class Walking : public TransportationMode { 6 | public: 7 | int calcETA() override { 8 | std::cout << "Calculating ETA (Walking)" << std::endl; 9 | return 10; 10 | } 11 | 12 | std::string getDirection() override { 13 | return "Directions for walking"; 14 | } 15 | }; -------------------------------------------------------------------------------- /cpp/BehaviouralPatterns/StatePattern/Solution/WithStatePattern.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "Car.cpp" 4 | #include "Cycling.cpp" 5 | #include "DirectionService.cpp" 6 | 7 | int main() { 8 | // Creating a DirectionService object with the initial transportation mode as Car 9 | DirectionService service(new Car()); 10 | 11 | // service.setTransportationMode(new Cycling()); 12 | 13 | // Display ETA and Direction based on the current mode 14 | std::cout << "ETA: " << service.getETA() << std::endl; 15 | std::cout << "Direction: " << service.getDirection() << std::endl; 16 | 17 | return 0; 18 | } -------------------------------------------------------------------------------- /cpp/BehaviouralPatterns/StrategyPattern/WithoutStrategyPattern.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class PaymentService { 5 | public: 6 | void processPayment(const std::string& paymentMethod) { 7 | if (paymentMethod == "Credit Card") { 8 | std::cout << "Making payment via credit card" << std::endl; 9 | } 10 | else if (paymentMethod == "Debit Card") { 11 | std::cout << "Making payment via debit card" << std::endl; 12 | } 13 | else if (paymentMethod == "UPI") { 14 | std::cout << "Making payment via UPI" << std::endl; 15 | } 16 | else { 17 | std::cout << "Unsupported Payment method" << std::endl; 18 | } 19 | } 20 | }; 21 | 22 | int main() { 23 | PaymentService paymentService; 24 | paymentService.processPayment("UPI"); 25 | 26 | return 0; 27 | } -------------------------------------------------------------------------------- /cpp/CreationalPatterns/BuilderPattern/Problem/WithoutBuilderPattern.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "House.cpp" 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | House house("Concrete", "Wood", "Shingles", true, true, false); 9 | 10 | // House house2("Concrete", "Wood", "Shingles"); // Constructor Explosion Issue (Cannot be done in C++ without overloading) 11 | 12 | cout << "Without Builder Pattern:" << endl; 13 | house.display(); 14 | 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /cpp/CreationalPatterns/BuilderPattern/Solution/WithBuilderPattern.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "House.cpp" 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | // Using Builder Pattern to construct House object 9 | House house = House::HouseBuilder("Concrete", "Wooden", "Tile") 10 | .setGarden(true) 11 | .setSwimmingPool(true) 12 | .setGarage(false) 13 | .build(); 14 | 15 | cout << "With Builder Pattern:" << endl; 16 | house.display(); 17 | 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /cpp/CreationalPatterns/FactoryPattern/Problem/Bike.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Transport.cpp" 3 | 4 | using namespace std; 5 | 6 | class Bike : public Transport { 7 | public: 8 | void deliver() override { 9 | cout << "Deliver by bike" << endl; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /cpp/CreationalPatterns/FactoryPattern/Problem/Bus.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Transport.cpp" 3 | 4 | using namespace std; 5 | 6 | class Bus : public Transport { 7 | public: 8 | void deliver() override { 9 | cout << "Deliver by bus" << endl; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /cpp/CreationalPatterns/FactoryPattern/Problem/Car.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Transport.cpp" 3 | 4 | using namespace std; 5 | 6 | class Car : public Transport { 7 | public: 8 | void deliver() override { 9 | cout << "Deliver by car" << endl; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /cpp/CreationalPatterns/FactoryPattern/Problem/Transport.cpp: -------------------------------------------------------------------------------- 1 | #ifndef TRANSPORT_CPP 2 | #define TRANSPORT_CPP 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Transport { 8 | public: 9 | virtual void deliver() = 0; 10 | virtual ~Transport() = default; 11 | }; 12 | 13 | #endif -------------------------------------------------------------------------------- /cpp/CreationalPatterns/FactoryPattern/Problem/TransportService.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Car.cpp" 3 | #include "Bike.cpp" 4 | #include "Bus.cpp" 5 | #include "Transport.cpp" 6 | 7 | using namespace std; 8 | 9 | int main() { 10 | // Direct create objects 11 | Transport* car = new Car(); 12 | Transport* bike = new Bike(); 13 | // add a bus object 14 | Transport* bus = new Bus(); 15 | 16 | // Cleanup (if dynamic allocation is used) 17 | delete car; 18 | delete bike; 19 | delete bus; 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /cpp/CreationalPatterns/FactoryPattern/Solution/Bike.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Transport.cpp" 3 | 4 | using namespace std; 5 | 6 | class Bike : public Transport { 7 | public: 8 | void deliver() override { 9 | cout << "Deliver by bike" << endl; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /cpp/CreationalPatterns/FactoryPattern/Solution/Bus.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Transport.cpp" 3 | 4 | using namespace std; 5 | 6 | class Bus : public Transport { 7 | public: 8 | void deliver() override { 9 | cout << "Deliver by bus" << endl; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /cpp/CreationalPatterns/FactoryPattern/Solution/Car.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Transport.cpp" 3 | 4 | using namespace std; 5 | 6 | class Car : public Transport { 7 | public: 8 | void deliver() override { 9 | cout << "Deliver by car" << endl; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /cpp/CreationalPatterns/FactoryPattern/Solution/Transport.cpp: -------------------------------------------------------------------------------- 1 | #ifndef TRANSPORT_CPP 2 | #define TRANSPORT_CPP 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Transport { 8 | public: 9 | virtual void deliver() = 0; 10 | virtual ~Transport() = default; 11 | }; 12 | 13 | #endif -------------------------------------------------------------------------------- /cpp/CreationalPatterns/FactoryPattern/Solution/TransportService.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "TransportFactory.cpp" 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | // Direct create objects using TransportFactory 8 | Transport* vehicle = TransportFactory::createTransport("car"); 9 | vehicle->deliver(); 10 | 11 | // Cleanup (if dynamic allocation is used) 12 | delete vehicle; 13 | 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /cpp/CreationalPatterns/PrototypePattern/Problem/GameBoard.cpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include "GamePiece.cpp" 5 | 6 | class GameBoard { 7 | private: 8 | std::vector pieces; 9 | 10 | public: 11 | void addPiece(const GamePiece& piece) { 12 | pieces.push_back(piece); 13 | } 14 | 15 | const std::vector& getPieces() const { 16 | return pieces; 17 | } 18 | 19 | void showBoardState() const { 20 | for (const auto& piece : pieces) { 21 | std::cout << piece.toString() << std::endl; 22 | } 23 | } 24 | }; -------------------------------------------------------------------------------- /cpp/CreationalPatterns/PrototypePattern/Problem/GameClientWithoutPrototype.cpp: -------------------------------------------------------------------------------- 1 | #include "GameBoard.cpp" 2 | 3 | int main() { 4 | GameBoard gameBoard; 5 | gameBoard.addPiece(GamePiece("Red", 1)); 6 | gameBoard.addPiece(GamePiece("Blue", 5)); 7 | gameBoard.showBoardState(); 8 | 9 | // Checkpoint this state 10 | GameBoard copiedBoard; 11 | for (const auto& piece : gameBoard.getPieces()) { 12 | copiedBoard.addPiece(GamePiece(piece.getColor(), piece.getPosition())); 13 | } 14 | 15 | std::cout << "Copied Board" << std::endl; 16 | copiedBoard.showBoardState(); 17 | 18 | return 0; 19 | } -------------------------------------------------------------------------------- /cpp/CreationalPatterns/PrototypePattern/Problem/GamePiece.cpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class GamePiece { 5 | private: 6 | std::string color; 7 | int position; 8 | 9 | public: 10 | GamePiece(std::string color, int position) 11 | : color(color), position(position) {} 12 | 13 | std::string getColor() const { return color; } 14 | int getPosition() const { return position; } 15 | 16 | void setColor(const std::string& color) { this->color = color; } 17 | void setPosition(int position) { this->position = position; } 18 | 19 | std::string toString() const { 20 | return "GamePiece{color='" + color + "', position=" + std::to_string(position) + "}"; 21 | } 22 | }; -------------------------------------------------------------------------------- /cpp/CreationalPatterns/PrototypePattern/Solution/GameClientWithPrototype.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "GameBoard.cpp" 3 | #include "GamePiece.cpp" 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | GameBoard gameBoard; 9 | 10 | // Add some pieces to the board 11 | gameBoard.addPiece(new GamePiece("Red", 1)); 12 | gameBoard.addPiece(new GamePiece("Blue", 5)); 13 | 14 | cout << "Original Board:" << endl; 15 | gameBoard.showBoardState(); 16 | 17 | // Create a checkpoint by cloning the board 18 | GameBoard* copiedBoard = gameBoard.clone(); 19 | 20 | cout << "Copied Board:" << endl; 21 | copiedBoard->showBoardState(); 22 | 23 | // Clean up 24 | delete copiedBoard; 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /cpp/CreationalPatterns/PrototypePattern/Solution/Prototype.cpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | template 3 | class Prototype { 4 | public: 5 | virtual T* clone() const = 0; 6 | }; 7 | -------------------------------------------------------------------------------- /cpp/CreationalPatterns/SingletonPattern/Problem/AppSettings.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class AppSettings { 7 | private: 8 | string databaseUrl; 9 | string apiKey; 10 | 11 | public: 12 | // Constructor 13 | AppSettings() { 14 | // Simulating reading settings from a config file 15 | databaseUrl = "jdbc:mysql://localhost:3306/mydatabase"; 16 | apiKey = "12345-ABCDE"; 17 | } 18 | 19 | string getDatabaseUrl() const { 20 | return databaseUrl; 21 | } 22 | 23 | string getApiKey() const { 24 | return apiKey; 25 | } 26 | }; -------------------------------------------------------------------------------- /cpp/CreationalPatterns/SingletonPattern/Problem/WithoutSingletonPattern.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "AppSettings.cpp" 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | AppSettings appSettings; 9 | AppSettings appSettingsCopy; 10 | 11 | cout << appSettingsCopy.getApiKey() << endl; 12 | cout << appSettings.getApiKey() << endl; 13 | 14 | // More memory usage (Different objects) 15 | cout << boolalpha << (&appSettings == &appSettingsCopy) << endl; 16 | 17 | return 0; 18 | } -------------------------------------------------------------------------------- /cpp/CreationalPatterns/SingletonPattern/Solution/SingletonPattern.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "AppSettings.cpp" 3 | 4 | using namespace std; 5 | 6 | // Initialize static instance 7 | AppSettings* AppSettings::instance = nullptr; 8 | 9 | int main() { 10 | AppSettings* appSettings = AppSettings::getInstance(); 11 | AppSettings* appSettingsCopy = AppSettings::getInstance(); 12 | 13 | cout << appSettingsCopy->getApiKey() << endl; 14 | cout << appSettings->getApiKey() << endl; 15 | 16 | // Check if both instances are the same 17 | cout << boolalpha << (appSettings == appSettingsCopy) << endl; // Should print true 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /cpp/LLDProject/RideSharingApp/V1/Driver.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Location.cpp" 3 | #include "Vehicle.cpp" 4 | 5 | class Driver { 6 | private: 7 | std::string name; 8 | Vehicle vehicle; 9 | Location location; 10 | 11 | public: 12 | Driver(const std::string& driverName, const Location& loc, const Vehicle& v) 13 | : name(driverName), location(loc), vehicle(v) {} 14 | 15 | Location getLocation() const { 16 | return location; 17 | } 18 | 19 | void setLocation(const Location& loc) { 20 | location = loc; 21 | } 22 | 23 | std::string getName() const { 24 | return name; 25 | } 26 | 27 | Vehicle getVehicle() const { 28 | return vehicle; 29 | } 30 | }; -------------------------------------------------------------------------------- /cpp/LLDProject/RideSharingApp/V1/Location.cpp: -------------------------------------------------------------------------------- 1 | #ifndef LOCATION_CPP 2 | #define LOCATION_CPP 3 | 4 | #include 5 | 6 | class Location { 7 | private: 8 | double latitude; 9 | double longitude; 10 | 11 | public: 12 | Location(double lat, double lon) : latitude(lat), longitude(lon) {} 13 | 14 | double getLatitude() const { 15 | return latitude; 16 | } 17 | 18 | double getLongitude() const { 19 | return longitude; 20 | } 21 | }; 22 | 23 | #endif -------------------------------------------------------------------------------- /cpp/LLDProject/RideSharingApp/V1/Passenger.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Location.cpp" 3 | 4 | class Passenger { 5 | public: 6 | std::string name; 7 | Location location; 8 | 9 | Passenger(const std::string& passengerName, const Location& loc) 10 | : name(passengerName), location(loc) {} 11 | }; -------------------------------------------------------------------------------- /cpp/LLDProject/RideSharingApp/V1/Vehicle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class Vehicle { 4 | public: 5 | std::string numberPlate; 6 | std::string type; 7 | 8 | Vehicle(const std::string& plate, const std::string& vehicleType) 9 | : numberPlate(plate), type(vehicleType) {} 10 | }; -------------------------------------------------------------------------------- /cpp/LLDProject/RideSharingApp/V2/Bike.cpp: -------------------------------------------------------------------------------- 1 | #ifndef BIKE_CPP 2 | #define BIKE_CPP 3 | 4 | #include "Vehicle.cpp" 5 | 6 | class Bike : public Vehicle { 7 | public: 8 | Bike(const std::string& numberPlate) : Vehicle(numberPlate) {} 9 | 10 | double getFarePerKm() { 11 | return 10.0; 12 | } 13 | }; 14 | 15 | #endif -------------------------------------------------------------------------------- /cpp/LLDProject/RideSharingApp/V2/Car.cpp: -------------------------------------------------------------------------------- 1 | #ifndef CAR_CPP 2 | #define CAR_CPP 3 | 4 | #include "Vehicle.cpp" 5 | 6 | class Car : public Vehicle { 7 | public: 8 | Car(const std::string& numberPlate) : Vehicle(numberPlate) {} 9 | 10 | double getFarePerKm() { 11 | return 20.0; 12 | } 13 | }; 14 | 15 | #endif -------------------------------------------------------------------------------- /cpp/LLDProject/RideSharingApp/V2/Driver.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "User.cpp" 3 | #include "Vehicle.cpp" 4 | 5 | class Driver : public User { 6 | private: 7 | Vehicle* vehicle; 8 | 9 | public: 10 | Driver(const std::string& name, const std::string& email, 11 | const Location& location, Vehicle* v) 12 | : User(name, email, location), vehicle(v) {} 13 | 14 | Vehicle* getVehicle() const { 15 | return vehicle; 16 | } 17 | 18 | std::string getName() const { 19 | return name; 20 | } 21 | 22 | void notify(const std::string& msg) override { 23 | std::cout << "Driver " << msg << std::endl; 24 | } 25 | }; -------------------------------------------------------------------------------- /cpp/LLDProject/RideSharingApp/V2/Location.cpp: -------------------------------------------------------------------------------- 1 | #ifndef LOCATION_CPP 2 | #define LOCATION_CPP 3 | 4 | #include 5 | 6 | class Location { 7 | private: 8 | double latitude; 9 | double longitude; 10 | 11 | public: 12 | Location(double lat, double lon) : latitude(lat), longitude(lon) {} 13 | 14 | double getLatitude() const { 15 | return latitude; 16 | } 17 | 18 | double getLongitude() const { 19 | return longitude; 20 | } 21 | 22 | double calcDistance(const Location& two) const { 23 | double dx = this->getLatitude() - two.getLatitude(); 24 | double dy = this->getLongitude() - two.getLongitude(); 25 | return std::sqrt(dx * dx + dy * dy); 26 | } 27 | }; 28 | 29 | #endif -------------------------------------------------------------------------------- /cpp/LLDProject/RideSharingApp/V2/Passenger.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "User.cpp" 3 | 4 | class Passenger : public User { 5 | public: 6 | Passenger(const std::string& name, const std::string& email, const Location& location) 7 | : User(name, email, location) {} 8 | 9 | void notify(const std::string& msg) override { 10 | std::cout << "passenger : " << msg << std::endl; 11 | } 12 | }; -------------------------------------------------------------------------------- /cpp/LLDProject/RideSharingApp/V2/User.cpp: -------------------------------------------------------------------------------- 1 | #ifndef USER_CPP 2 | #define USER_CPP 3 | 4 | #include 5 | #include "Location.cpp" 6 | 7 | class User { 8 | protected: 9 | std::string name; 10 | std::string email; 11 | Location location; 12 | 13 | public: 14 | User(const std::string& userName, const std::string& userEmail, const Location& loc) 15 | : name(userName), email(userEmail), location(loc) {} 16 | 17 | virtual ~User() {} 18 | 19 | Location getLocation() const { 20 | return location; 21 | } 22 | 23 | void setLocation(const Location& loc) { 24 | location = loc; 25 | } 26 | 27 | virtual void notify(const std::string& msg) = 0; 28 | }; 29 | 30 | #endif -------------------------------------------------------------------------------- /cpp/LLDProject/RideSharingApp/V2/Vehicle.cpp: -------------------------------------------------------------------------------- 1 | #ifndef VEHICLE_CPP 2 | #define VEHICLE_CPP 3 | 4 | #include 5 | 6 | class Vehicle { 7 | protected: 8 | std::string numberPlate; 9 | 10 | public: 11 | Vehicle(const std::string& plate) : numberPlate(plate) {} 12 | virtual ~Vehicle() {} 13 | virtual double getFarePerKm() = 0; 14 | }; 15 | 16 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/DIP/BadCode/EmailService.cpp: -------------------------------------------------------------------------------- 1 | #ifndef EMAIL_SERVICE_CPP 2 | #define EMAIL_SERVICE_CPP 3 | 4 | #include 5 | #include 6 | 7 | class EmailService { 8 | public: 9 | void sendEmail(const std::string& message) { 10 | std::cout << "Sending email: " << message << std::endl; 11 | } 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/DIP/BadCode/NotificationService.cpp: -------------------------------------------------------------------------------- 1 | #ifndef NOTIFICATION_SERVICE_CPP 2 | #define NOTIFICATION_SERVICE_CPP 3 | 4 | #include "EmailService.cpp" 5 | #include "SMSService.cpp" 6 | 7 | class NotificationService { 8 | private: 9 | EmailService emailService; 10 | SMSService smsService; 11 | 12 | public: 13 | void notifyByEmail(const std::string& msg) { 14 | emailService.sendEmail(msg); 15 | } 16 | 17 | void notifyBySMS(const std::string& msg) { 18 | smsService.sendSMS(msg); 19 | } 20 | }; 21 | 22 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/DIP/BadCode/SMSService.cpp: -------------------------------------------------------------------------------- 1 | #ifndef SMS_SERVICE_CPP 2 | #define SMS_SERVICE_CPP 3 | 4 | #include 5 | #include 6 | 7 | class SMSService { 8 | public: 9 | void sendSMS(const std::string& message) { 10 | std::cout << "Sending SMS: " << message << std::endl; 11 | } 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/DIP/GoodCode/EmailService.cpp: -------------------------------------------------------------------------------- 1 | #ifndef EMAIL_SERVICE_CPP 2 | #define EMAIL_SERVICE_CPP 3 | 4 | #include 5 | #include "NotificationChannel.cpp" 6 | 7 | class EmailService : public NotificationChannel { 8 | public: 9 | void send(const std::string& msg) override { 10 | std::cout << "Sending Email " << msg << std::endl; 11 | } 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/DIP/GoodCode/Main.cpp: -------------------------------------------------------------------------------- 1 | #include "NotificationService.cpp" 2 | #include "EmailService.cpp" 3 | #include "SMSService.cpp" 4 | 5 | int main() { 6 | NotificationChannel* emailChannel = new EmailService(); 7 | NotificationService emailNotification(emailChannel); 8 | emailNotification.notify("Your order has been shipped"); 9 | 10 | NotificationChannel* smsChannel = new SMSService(); 11 | NotificationService smsNotification(smsChannel); 12 | smsNotification.notify("OTP 1234"); 13 | 14 | delete emailChannel; 15 | delete smsChannel; 16 | 17 | return 0; 18 | } -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/DIP/GoodCode/NotificationChannel.cpp: -------------------------------------------------------------------------------- 1 | #ifndef NOTIFICATION_CHANNEL_CPP 2 | #define NOTIFICATION_CHANNEL_CPP 3 | 4 | #include 5 | 6 | class NotificationChannel { 7 | public: 8 | virtual ~NotificationChannel() {} 9 | virtual void send(const std::string& msg) = 0; 10 | }; 11 | 12 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/DIP/GoodCode/NotificationService.cpp: -------------------------------------------------------------------------------- 1 | #ifndef NOTIFICATION_SERVICE_CPP 2 | #define NOTIFICATION_SERVICE_CPP 3 | 4 | #include "NotificationChannel.cpp" 5 | 6 | class NotificationService { 7 | private: 8 | NotificationChannel* notificationChannel; 9 | 10 | public: 11 | NotificationService(NotificationChannel* channel) : notificationChannel(channel) {} 12 | 13 | void notify(const std::string& msg) { 14 | notificationChannel->send(msg); 15 | } 16 | }; 17 | 18 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/DIP/GoodCode/SMSService.cpp: -------------------------------------------------------------------------------- 1 | #ifndef SMS_SERVICE_CPP 2 | #define SMS_SERVICE_CPP 3 | 4 | #include 5 | #include "NotificationChannel.cpp" 6 | 7 | class SMSService : public NotificationChannel { 8 | public: 9 | void send(const std::string& msg) override { 10 | std::cout << "Sending SMS " << msg << std::endl; 11 | } 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/ISP/BadCode/Document.cpp: -------------------------------------------------------------------------------- 1 | #ifndef DOCUMENT_CPP 2 | #define DOCUMENT_CPP 3 | 4 | class Document { 5 | // Empty class for demonstration 6 | }; 7 | 8 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/ISP/BadCode/Machine.cpp: -------------------------------------------------------------------------------- 1 | #ifndef MACHINE_CPP 2 | #define MACHINE_CPP 3 | 4 | #include "Document.cpp" 5 | 6 | class Machine { 7 | public: 8 | virtual ~Machine() {} 9 | virtual void print(Document* doc) = 0; 10 | virtual void scan(Document* doc) = 0; 11 | virtual void copy(Document* doc) = 0; 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/ISP/BadCode/MultiPurposeMachine.cpp: -------------------------------------------------------------------------------- 1 | #ifndef MULTIPURPOSE_MACHINE_CPP 2 | #define MULTIPURPOSE_MACHINE_CPP 3 | 4 | #include 5 | #include "Machine.cpp" 6 | 7 | class MultiPurposeMachine : public Machine { 8 | public: 9 | void print(Document* doc) override { 10 | std::cout << "Printing document..." << std::endl; 11 | } 12 | 13 | void scan(Document* doc) override { 14 | std::cout << "Scan document..." << std::endl; 15 | } 16 | 17 | void copy(Document* doc) override { 18 | std::cout << "Copy document..." << std::endl; 19 | } 20 | }; 21 | 22 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/ISP/BadCode/SimplePrinter.cpp: -------------------------------------------------------------------------------- 1 | #ifndef SIMPLE_PRINTER_CPP 2 | #define SIMPLE_PRINTER_CPP 3 | 4 | #include 5 | #include 6 | #include "Machine.cpp" 7 | 8 | class SimplePrinter : public Machine { 9 | public: 10 | void print(Document* doc) override { 11 | std::cout << "Printing document..." << std::endl; 12 | } 13 | 14 | void scan(Document* doc) override { 15 | throw std::runtime_error("Scan not supported."); 16 | } 17 | 18 | void copy(Document* doc) override { 19 | throw std::runtime_error("Copy not supported."); 20 | } 21 | }; 22 | 23 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/ISP/GoodCode/Copier.cpp: -------------------------------------------------------------------------------- 1 | #ifndef COPIER_CPP 2 | #define COPIER_CPP 3 | 4 | #include "../BadCode/Document.cpp" 5 | 6 | class Copier { 7 | public: 8 | virtual ~Copier() {} 9 | virtual void copy(Document* doc) = 0; 10 | }; 11 | 12 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/ISP/GoodCode/MultiPurposeMachine.cpp: -------------------------------------------------------------------------------- 1 | #ifndef MULTIPURPOSE_MACHINE_CPP 2 | #define MULTIPURPOSE_MACHINE_CPP 3 | 4 | #include 5 | #include "Printer.cpp" 6 | #include "Scanner.cpp" 7 | #include "Copier.cpp" 8 | 9 | class MultiPurposeMachine : public Printer, public Scanner, public Copier { 10 | public: 11 | void print(Document* doc) override { 12 | std::cout << "Printing document..." << std::endl; 13 | } 14 | 15 | void scan(Document* doc) override { 16 | std::cout << "Scan document..." << std::endl; 17 | } 18 | 19 | void copy(Document* doc) override { 20 | std::cout << "Copy document..." << std::endl; 21 | } 22 | }; 23 | 24 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/ISP/GoodCode/Printer.cpp: -------------------------------------------------------------------------------- 1 | #ifndef PRINTER_CPP 2 | #define PRINTER_CPP 3 | 4 | #include "../BadCode/Document.cpp" 5 | 6 | class Printer { 7 | public: 8 | virtual ~Printer() {} 9 | virtual void print(Document* doc) = 0; 10 | }; 11 | 12 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/ISP/GoodCode/Scanner.cpp: -------------------------------------------------------------------------------- 1 | #ifndef SCANNER_CPP 2 | #define SCANNER_CPP 3 | 4 | #include "../BadCode/Document.cpp" 5 | 6 | class Scanner { 7 | public: 8 | virtual ~Scanner() {} 9 | virtual void scan(Document* doc) = 0; 10 | }; 11 | 12 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/ISP/GoodCode/SimplePrinter.cpp: -------------------------------------------------------------------------------- 1 | #ifndef SIMPLE_PRINTER_CPP 2 | #define SIMPLE_PRINTER_CPP 3 | 4 | #include 5 | #include "Printer.cpp" 6 | 7 | class SimplePrinter : public Printer { 8 | public: 9 | void print(Document* doc) override { 10 | std::cout << "Printing the document" << std::endl; 11 | } 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/LSP/BadCode/File.cpp: -------------------------------------------------------------------------------- 1 | #ifndef FILE_CPP 2 | #define FILE_CPP 3 | 4 | #include 5 | 6 | class File { 7 | public: 8 | virtual ~File() {} 9 | 10 | virtual void read() { 11 | std::cout << "reading from file..." << std::endl; 12 | } 13 | 14 | virtual void write() { 15 | std::cout << "Writing to file..." << std::endl; 16 | } 17 | }; 18 | 19 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/LSP/BadCode/Main.cpp: -------------------------------------------------------------------------------- 1 | #include "ReadOnlyFile.cpp" 2 | 3 | int main() { 4 | File* file = new ReadOnlyFile(); 5 | file->read(); // works fine 6 | try { 7 | file->write(); // throwing an exception, violation of LSP 8 | } catch(const std::runtime_error& e) { 9 | std::cout << "Error: " << e.what() << std::endl; 10 | } 11 | 12 | delete file; 13 | return 0; 14 | } -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/LSP/BadCode/ReadOnlyFile.cpp: -------------------------------------------------------------------------------- 1 | #ifndef READONLY_FILE_CPP 2 | #define READONLY_FILE_CPP 3 | 4 | #include 5 | #include "File.cpp" 6 | 7 | class ReadOnlyFile : public File { 8 | public: 9 | void write() override { 10 | throw std::runtime_error("Can't write to a read only file"); 11 | } 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/LSP/GoodCode/Main.cpp: -------------------------------------------------------------------------------- 1 | #include "ReadOnlyFile.cpp" 2 | #include "WritableFile.cpp" 3 | 4 | void readAnyFile(Readable* file) { 5 | file->read(); 6 | } 7 | 8 | int main() { 9 | Readable* readableFile = new ReadOnlyFile(); 10 | readableFile->read(); 11 | 12 | WritableFile* writableFile = new WritableFile(); 13 | writableFile->read(); 14 | writableFile->write(); 15 | 16 | readAnyFile(readableFile); 17 | readAnyFile(writableFile); 18 | 19 | delete readableFile; 20 | delete writableFile; 21 | 22 | return 0; 23 | } -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/LSP/GoodCode/ReadOnlyFile.cpp: -------------------------------------------------------------------------------- 1 | #ifndef READONLY_FILE_CPP 2 | #define READONLY_FILE_CPP 3 | 4 | #include "ReadableFile.cpp" 5 | 6 | class ReadOnlyFile : public ReadableFile { 7 | // Inherits read-only capability 8 | }; 9 | 10 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/LSP/GoodCode/Readable.cpp: -------------------------------------------------------------------------------- 1 | #ifndef READABLE_CPP 2 | #define READABLE_CPP 3 | 4 | class Readable { 5 | public: 6 | virtual ~Readable() {} 7 | virtual void read() = 0; 8 | }; 9 | 10 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/LSP/GoodCode/ReadableFile.cpp: -------------------------------------------------------------------------------- 1 | #ifndef READABLE_FILE_CPP 2 | #define READABLE_FILE_CPP 3 | 4 | #include 5 | #include "Readable.cpp" 6 | 7 | class ReadableFile : public Readable { 8 | public: 9 | void read() override { 10 | std::cout << "Reading from a file" << std::endl; 11 | } 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/LSP/GoodCode/Writable.cpp: -------------------------------------------------------------------------------- 1 | #ifndef WRITABLE_CPP 2 | #define WRITABLE_CPP 3 | 4 | class Writable { 5 | public: 6 | virtual ~Writable() {} 7 | virtual void write() = 0; 8 | }; 9 | 10 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/LSP/GoodCode/WritableFile.cpp: -------------------------------------------------------------------------------- 1 | #ifndef WRITABLE_FILE_CPP 2 | #define WRITABLE_FILE_CPP 3 | 4 | #include 5 | #include "ReadableFile.cpp" 6 | #include "Writable.cpp" 7 | 8 | class WritableFile : public ReadableFile, public Writable { 9 | public: 10 | void write() override { 11 | std::cout << "Writing to file" << std::endl; 12 | } 13 | }; 14 | 15 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/OCP/GoodCode/CreditCard.cpp: -------------------------------------------------------------------------------- 1 | #ifndef CREDIT_CARD_CPP 2 | #define CREDIT_CARD_CPP 3 | 4 | #include 5 | #include "PaymentMethod.cpp" 6 | 7 | class CreditCard : public PaymentMethod { 8 | public: 9 | void pay(double amount) override { 10 | std::cout << "Making Payment via Credit Card: " << amount << std::endl; 11 | } 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/OCP/GoodCode/DebitCard.cpp: -------------------------------------------------------------------------------- 1 | #ifndef DEBIT_CARD_CPP 2 | #define DEBIT_CARD_CPP 3 | 4 | #include 5 | #include "PaymentMethod.cpp" 6 | 7 | class DebitCard : public PaymentMethod { 8 | public: 9 | void pay(double amount) override { 10 | std::cout << "Making Payment via Debit Card: " << amount << std::endl; 11 | } 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/OCP/GoodCode/Main.cpp: -------------------------------------------------------------------------------- 1 | #include "PaymentProcessor.cpp" 2 | #include "CreditCard.cpp" 3 | #include "UPI.cpp" 4 | 5 | int main() { 6 | PaymentProcessor processor; 7 | 8 | PaymentMethod* creditCard = new CreditCard(); 9 | PaymentMethod* upi = new UPI(); 10 | 11 | processor.processPayment(creditCard, 100); 12 | processor.processPayment(upi, 120); 13 | 14 | // Cleanup 15 | delete creditCard; 16 | delete upi; 17 | 18 | return 0; 19 | } -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/OCP/GoodCode/PayPal.cpp: -------------------------------------------------------------------------------- 1 | #ifndef PAYPAL_CPP 2 | #define PAYPAL_CPP 3 | 4 | #include 5 | #include "PaymentMethod.cpp" 6 | 7 | class PayPal : public PaymentMethod { 8 | public: 9 | void pay(double amount) override { 10 | std::cout << "Making Payment via PayPal: " << amount << std::endl; 11 | } 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/OCP/GoodCode/PaymentMethod.cpp: -------------------------------------------------------------------------------- 1 | #ifndef PAYMENT_METHOD_CPP 2 | #define PAYMENT_METHOD_CPP 3 | 4 | class PaymentMethod { 5 | public: 6 | virtual ~PaymentMethod() {} 7 | virtual void pay(double amount) = 0; 8 | }; 9 | 10 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/OCP/GoodCode/PaymentProcessor.cpp: -------------------------------------------------------------------------------- 1 | #ifndef PAYMENT_PROCESSOR_CPP 2 | #define PAYMENT_PROCESSOR_CPP 3 | 4 | #include "PaymentMethod.cpp" 5 | 6 | class PaymentProcessor { 7 | public: 8 | void processPayment(PaymentMethod* paymentMethod, double amount) { 9 | paymentMethod->pay(amount); 10 | } 11 | }; 12 | 13 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/OCP/GoodCode/UPI.cpp: -------------------------------------------------------------------------------- 1 | #ifndef UPI_CPP 2 | #define UPI_CPP 3 | 4 | #include 5 | #include "PaymentMethod.cpp" 6 | 7 | class UPI : public PaymentMethod { 8 | public: 9 | void pay(double amount) override { 10 | std::cout << "Making payment via UPI: " << amount << std::endl; 11 | } 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/SRP/BadCode/Invoice.cpp: -------------------------------------------------------------------------------- 1 | #ifndef INVOICE_CPP 2 | #define INVOICE_CPP 3 | 4 | #include 5 | 6 | class Invoice { 7 | private: 8 | double amount; 9 | 10 | public: 11 | Invoice(double amount) : amount(amount) {} 12 | 13 | // Additional Functionality 14 | void generateInvoice() { 15 | std::cout << "Invoice generated & printed for amount " << amount << std::endl; 16 | } 17 | 18 | void saveToDatabase() { 19 | std::cout << "Saving invoice to Database" << std::endl; 20 | } 21 | 22 | void sendEmailNotification() { 23 | std::cout << "Sending email notification for invoice" << std::endl; 24 | } 25 | }; 26 | 27 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/SRP/BadCode/Invoice.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.SRP.BadCode; 2 | 3 | public class Invoice { 4 | private double amount; 5 | 6 | public Invoice(double amount){ 7 | this.amount = amount; 8 | } 9 | 10 | //Additional Functionality 11 | public void generateInvoice(){ 12 | System.out.println("Invoice generated & printed for amount " +amount); 13 | } 14 | 15 | public void saveToDatabase(){ 16 | System.out.println("Saving invoice to Database "); 17 | } 18 | 19 | public void sendEmailNotification(){ 20 | System.out.println("Sending email notification for invoice "); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/SRP/GoodCode/EmailService.cpp: -------------------------------------------------------------------------------- 1 | #ifndef EMAIL_SERVICE_CPP 2 | #define EMAIL_SERVICE_CPP 3 | 4 | #include 5 | 6 | class EmailService { 7 | public: 8 | void sendEmailNotification() { 9 | std::cout << "Sending email notification for invoice" << std::endl; 10 | } 11 | }; 12 | 13 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/SRP/GoodCode/EmailService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.SRP.GoodCode; 2 | 3 | public class EmailService { 4 | public void sendEmailNotification(){ 5 | System.out.println("Sending email notification for invoice "); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/SRP/GoodCode/Invoice.cpp: -------------------------------------------------------------------------------- 1 | #ifndef INVOICE_CPP 2 | #define INVOICE_CPP 3 | 4 | #include 5 | 6 | class Invoice { 7 | private: 8 | double amount; 9 | 10 | public: 11 | Invoice(double amount) : amount(amount) {} 12 | 13 | void generateInvoice() { 14 | std::cout << "Invoice generated & printed for amount " << amount << std::endl; 15 | } 16 | 17 | double getAmount() const { 18 | return amount; 19 | } 20 | }; 21 | 22 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/SRP/GoodCode/Invoice.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.SRP.GoodCode; 2 | 3 | public class Invoice { 4 | private double amount; 5 | 6 | public Invoice(double amount){ 7 | this.amount = amount; 8 | } 9 | 10 | //Additional Functionality 11 | public void generateInvoice(){ 12 | System.out.println("Invoice generated & printed for amount " +amount); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/SRP/GoodCode/InvoiceRepository.cpp: -------------------------------------------------------------------------------- 1 | #ifndef INVOICE_REPOSITORY_CPP 2 | #define INVOICE_REPOSITORY_CPP 3 | 4 | #include 5 | 6 | class InvoiceRepository { 7 | public: 8 | void saveToDatabase() { 9 | std::cout << "Saving invoice to Database" << std::endl; 10 | } 11 | }; 12 | 13 | #endif -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/SRP/GoodCode/InvoiceRepository.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.SRP.GoodCode; 2 | 3 | public class InvoiceRepository { 4 | public void saveToDatabase(){ 5 | System.out.println("Saving invoice to Database "); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /cpp/SOLIDPrinciples/SRP/GoodCode/Main.cpp: -------------------------------------------------------------------------------- 1 | #include "Invoice.cpp" 2 | #include "EmailService.cpp" 3 | #include "InvoiceRepository.cpp" 4 | 5 | int main() { 6 | // Create an invoice 7 | Invoice invoice(100.0); 8 | 9 | // Generate the invoice 10 | invoice.generateInvoice(); 11 | 12 | // Save to database using repository 13 | InvoiceRepository repository; 14 | repository.saveToDatabase(); 15 | 16 | // Send email notification 17 | EmailService emailService; 18 | emailService.sendEmailNotification(); 19 | 20 | return 0; 21 | } -------------------------------------------------------------------------------- /cpp/StructuralPatterns/AdapterPattern/Client.cpp: -------------------------------------------------------------------------------- 1 | #include "EmailNotificationService.cpp" 2 | #include "SendGridAdapter.cpp" 3 | 4 | int main() { 5 | // Using legacy email service 6 | NotificationService* emailService = new EmailNotificationService(); 7 | emailService->send("customer@codingminutes.com", "order confirmation", "your order has been received!"); 8 | 9 | // Using SendGrid through adapter 10 | SendGridService* sendGridService = new SendGridService(); 11 | NotificationService* emailServiceUsingSendGrid = new SendGridAdapter(sendGridService); 12 | emailServiceUsingSendGrid->send("customer@codingminutes.com", "order confirmation", "your order has been received!"); 13 | 14 | // Cleanup 15 | delete emailService; 16 | delete sendGridService; 17 | delete emailServiceUsingSendGrid; 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /cpp/StructuralPatterns/AdapterPattern/Client.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.AdapterPattern; 2 | 3 | public class Client { 4 | public static void main(String[] args) { 5 | NotificationService emailService = new EmailNotificationService(); 6 | emailService.send("customer@codingminutes.com","order confirmation","your order has been recieved!"); 7 | 8 | //NotificationService sendGridEmailService = new SendGridService(); 9 | NotificationService emailServiceUsingSendGrid = new SendGridAdapter(new SendGridService()); 10 | emailServiceUsingSendGrid.send("customer@codingminutes.com","order confirmation","your order has been recieved!"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/AdapterPattern/EmailNotificationService.cpp: -------------------------------------------------------------------------------- 1 | #ifndef EMAIL_NOTIFICATION_SERVICE_CPP 2 | #define EMAIL_NOTIFICATION_SERVICE_CPP 3 | 4 | #include 5 | #include "NotificationService.cpp" 6 | 7 | class EmailNotificationService : public NotificationService { 8 | public: 9 | void send(const std::string& to, const std::string& subject, const std::string& body) override { 10 | std::cout << "Sending Email to " << to << std::endl; 11 | std::cout << "Subject: " << subject << std::endl; 12 | std::cout << "Body: " << body << std::endl; 13 | } 14 | }; 15 | 16 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/AdapterPattern/EmailNotificationService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.AdapterPattern; 2 | 3 | //Legacy Code: Email Notification Service 4 | public class EmailNotificationService implements NotificationService { 5 | public void send(String to,String subject,String body){ 6 | System.out.println("Sending Email to " + to); 7 | System.out.println("Subject: " + subject); 8 | System.out.println("Body: "+body); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/AdapterPattern/NotificationService.cpp: -------------------------------------------------------------------------------- 1 | #ifndef NOTIFICATION_SERVICE_CPP 2 | #define NOTIFICATION_SERVICE_CPP 3 | 4 | #include 5 | 6 | class NotificationService { 7 | public: 8 | virtual ~NotificationService() {} 9 | virtual void send(const std::string& to, const std::string& subject, const std::string& body) = 0; 10 | }; 11 | 12 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/AdapterPattern/NotificationService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.AdapterPattern; 2 | 3 | interface NotificationService { 4 | void send(String to,String subject,String body); 5 | } 6 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/AdapterPattern/SendGridAdapter.cpp: -------------------------------------------------------------------------------- 1 | #ifndef SENDGRID_ADAPTER_CPP 2 | #define SENDGRID_ADAPTER_CPP 3 | 4 | #include "NotificationService.cpp" 5 | #include "SendGridService.cpp" 6 | 7 | class SendGridAdapter : public NotificationService { 8 | private: 9 | SendGridService* sendGridService; 10 | 11 | public: 12 | SendGridAdapter(SendGridService* service) : sendGridService(service) {} 13 | 14 | void send(const std::string& to, const std::string& subject, const std::string& body) override { 15 | // Adapter Method -> convert parameters and calls to SendGrid Method 16 | sendGridService->sendEmail(to, subject, body); 17 | } 18 | }; 19 | 20 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/AdapterPattern/SendGridAdapter.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.AdapterPattern; 2 | 3 | public class SendGridAdapter implements NotificationService{ 4 | private SendGridService sendGridService; 5 | 6 | public SendGridAdapter(SendGridService sendGridService){ 7 | this.sendGridService = sendGridService; 8 | } 9 | 10 | @Override 11 | public void send(String to, String subject, String body) { 12 | //Adapter Method -> convert parameters and calls to SendGrid Method 13 | sendGridService.sendEmail(to,subject,body); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/AdapterPattern/SendGridService.cpp: -------------------------------------------------------------------------------- 1 | #ifndef SENDGRID_SERVICE_CPP 2 | #define SENDGRID_SERVICE_CPP 3 | 4 | #include 5 | #include 6 | 7 | class SendGridService { 8 | public: 9 | void sendEmail(const std::string& recipient, const std::string& title, const std::string& content) { 10 | std::cout << "Sending email via SendGrid to " << recipient << std::endl; 11 | std::cout << "Title: " << title << std::endl; 12 | std::cout << "Content: " << content << std::endl; 13 | } 14 | }; 15 | 16 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/AdapterPattern/SendGridService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.AdapterPattern; 2 | 3 | public class SendGridService { 4 | public void sendEmail(String recipient, String title, String content){ 5 | System.out.println("Sending email via SendGrid to" + recipient); 6 | System.out.println("Title : " + title); 7 | System.out.println("Content : " + content); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/CompositePattern/Problem/File.cpp: -------------------------------------------------------------------------------- 1 | #ifndef FILE_CPP 2 | #define FILE_CPP 3 | 4 | #include 5 | #include 6 | 7 | class File { 8 | private: 9 | std::string name; 10 | 11 | public: 12 | File(const std::string& name) : name(name) {} 13 | 14 | void showDetails() { 15 | std::cout << "File: " << name << std::endl; 16 | } 17 | }; 18 | 19 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/CompositePattern/Problem/File.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.CompositePattern.Problem; 2 | 3 | public class File { 4 | private String name; 5 | 6 | public File(String name){ 7 | this.name = name; 8 | } 9 | 10 | public void showDetails(){ 11 | System.out.println("File : " +name); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/CompositePattern/Problem/FileSystemApp.cpp: -------------------------------------------------------------------------------- 1 | #include "Folder.cpp" 2 | 3 | int main() { 4 | File* file1 = new File("File1.txt"); 5 | File* file2 = new File("File2.txt"); 6 | 7 | Folder folder("Documents"); 8 | folder.addFile(file1); 9 | folder.addFile(file2); 10 | 11 | folder.showDetails(); 12 | 13 | return 0; 14 | } -------------------------------------------------------------------------------- /cpp/StructuralPatterns/CompositePattern/Problem/FileSystemApp.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.CompositePattern.Problem; 2 | 3 | public class FileSystemApp { 4 | public static void main(String[] args) { 5 | File file1 = new File("File1.txt"); 6 | File file2 = new File("File2.txt"); 7 | Folder folder = new Folder("Documents"); 8 | folder.addFile(file1); 9 | folder.addFile(file2); 10 | 11 | folder.showDetails(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/CompositePattern/Problem/Folder.cpp: -------------------------------------------------------------------------------- 1 | #ifndef FOLDER_CPP 2 | #define FOLDER_CPP 3 | 4 | #include 5 | #include 6 | #include 7 | #include "File.cpp" 8 | 9 | class Folder { 10 | private: 11 | std::string name; 12 | std::vector files; 13 | 14 | public: 15 | Folder(const std::string& name) : name(name) {} 16 | 17 | void addFile(File* file) { 18 | files.push_back(file); 19 | } 20 | 21 | void showDetails() { 22 | std::cout << "Folder: " << name << std::endl; 23 | for(File* file : files) { 24 | file->showDetails(); 25 | } 26 | } 27 | 28 | ~Folder() { 29 | for(File* file : files) { 30 | delete file; 31 | } 32 | } 33 | }; 34 | 35 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/CompositePattern/Problem/Folder.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.CompositePattern.Problem; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Folder { 7 | private String name; 8 | private List files = new ArrayList<>(); 9 | 10 | public Folder(String name){ 11 | this.name = name; 12 | } 13 | 14 | public void addFile(File file){ 15 | files.add(file); 16 | } 17 | 18 | public void showDetails(){ 19 | System.out.println("Folder: " + name); 20 | for(File file:files){ 21 | file.showDetails(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/CompositePattern/Solution/File.cpp: -------------------------------------------------------------------------------- 1 | #ifndef FILE_CPP 2 | #define FILE_CPP 3 | 4 | #include 5 | #include 6 | #include "FileSystemComponent.cpp" 7 | 8 | class File : public FileSystemComponent { 9 | private: 10 | std::string name; 11 | 12 | public: 13 | File(const std::string& name) : name(name) {} 14 | 15 | void showDetails() override { 16 | std::cout << "File: " << name << std::endl; 17 | } 18 | }; 19 | 20 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/CompositePattern/Solution/File.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.CompositePattern.Solution; 2 | 3 | public class File implements FileSystemComponent { 4 | private String name; 5 | 6 | public File(String name){ 7 | this.name = name; 8 | } 9 | 10 | public void showDetails(){ 11 | System.out.println("File : " +name); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/CompositePattern/Solution/FileSystemApp.cpp: -------------------------------------------------------------------------------- 1 | #include "Folder.cpp" 2 | #include "File.cpp" 3 | 4 | int main() { 5 | FileSystemComponent* file1 = new File("File1.txt"); 6 | FileSystemComponent* file2 = new File("File2.txt"); 7 | 8 | Folder* folder = new Folder("Documents"); 9 | folder->addComponent(file1); 10 | folder->addComponent(file2); 11 | 12 | // Subfolder 13 | Folder* subfolder = new Folder("Subfolder"); 14 | FileSystemComponent* file3 = new File("File3.txt"); 15 | 16 | subfolder->addComponent(file3); 17 | folder->addComponent(subfolder); 18 | 19 | folder->showDetails(); 20 | 21 | // Cleanup is handled by Folder destructor 22 | delete folder; 23 | 24 | return 0; 25 | } -------------------------------------------------------------------------------- /cpp/StructuralPatterns/CompositePattern/Solution/FileSystemApp.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.CompositePattern.Solution; 2 | 3 | public class FileSystemApp { 4 | public static void main(String[] args) { 5 | FileSystemComponent file1 = new File("File1.txt"); 6 | FileSystemComponent file2 = new File("File2.txt"); 7 | Folder folder = new Folder("Documents"); 8 | folder.addComponent(file1); 9 | folder.addComponent(file2); 10 | 11 | //Subfolder 12 | Folder subfolder = new Folder("Subfolder"); 13 | FileSystemComponent file3 = new File("File3.txt"); 14 | 15 | subfolder.addComponent(file3); 16 | folder.addComponent(subfolder); 17 | 18 | folder.showDetails(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/CompositePattern/Solution/FileSystemComponent.cpp: -------------------------------------------------------------------------------- 1 | #ifndef FILESYSTEM_COMPONENT_CPP 2 | #define FILESYSTEM_COMPONENT_CPP 3 | 4 | class FileSystemComponent { 5 | public: 6 | virtual ~FileSystemComponent() {} 7 | virtual void showDetails() = 0; 8 | }; 9 | 10 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/CompositePattern/Solution/FileSystemComponent.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.CompositePattern.Solution; 2 | 3 | public interface FileSystemComponent { 4 | void showDetails(); 5 | } 6 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/CompositePattern/Solution/Folder.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.CompositePattern.Solution; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Folder implements FileSystemComponent{ 7 | private String name; 8 | private List components = new ArrayList<>(); 9 | 10 | public Folder(String name){ 11 | this.name = name; 12 | } 13 | 14 | public void addComponent(FileSystemComponent component){ 15 | components.add(component); 16 | } 17 | 18 | public void showDetails(){ 19 | System.out.println("Folder: " + name); 20 | for(FileSystemComponent component:components){ 21 | component.showDetails(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Problem/BasicPizza.cpp: -------------------------------------------------------------------------------- 1 | #ifndef BASIC_PIZZA_CPP 2 | #define BASIC_PIZZA_CPP 3 | 4 | #include "Pizza.cpp" 5 | 6 | class BasicPizza : public Pizza { 7 | public: 8 | std::string getDescription() override { 9 | return "Basic Pizza"; 10 | } 11 | 12 | double getCost() override { 13 | return 5.00; // base cost 14 | } 15 | }; 16 | 17 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Problem/BasicPizza.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Problem; 2 | 3 | public class BasicPizza implements Pizza{ 4 | @Override 5 | public String getDescription() { 6 | return "Basic Pizza"; 7 | 8 | } 9 | 10 | @Override 11 | public double getCost() { 12 | return 5.00; //base cost 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Problem/CheeseOlivePizza.cpp: -------------------------------------------------------------------------------- 1 | #ifndef CHEESE_OLIVE_PIZZA_CPP 2 | #define CHEESE_OLIVE_PIZZA_CPP 3 | 4 | #include "CheesePizza.cpp" 5 | 6 | class CheeseOlivePizza : public CheesePizza { 7 | public: 8 | std::string getDescription() override { 9 | return CheesePizza::getDescription() + ", Olives"; 10 | } 11 | 12 | double getCost() override { 13 | return CheesePizza::getCost() + 0.50; 14 | } 15 | }; 16 | 17 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Problem/CheeseOlivePizza.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Problem; 2 | 3 | public class CheeseOlivePizza extends CheesePizza{ 4 | 5 | @Override 6 | public String getDescription() { 7 | return super.getDescription() + ", Olives"; 8 | } 9 | 10 | @Override 11 | public double getCost() { 12 | return super.getCost() + 0.50; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Problem/CheesePizza.cpp: -------------------------------------------------------------------------------- 1 | #ifndef CHEESE_PIZZA_CPP 2 | #define CHEESE_PIZZA_CPP 3 | 4 | #include "BasicPizza.cpp" 5 | 6 | class CheesePizza : public BasicPizza { 7 | public: 8 | std::string getDescription() override { 9 | return BasicPizza::getDescription() + ", Cheese"; 10 | } 11 | 12 | double getCost() override { 13 | return BasicPizza::getCost() + 1.00; 14 | } 15 | }; 16 | 17 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Problem/CheesePizza.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Problem; 2 | 3 | public class CheesePizza extends BasicPizza{ 4 | @Override 5 | public String getDescription() { 6 | return super.getDescription() + ", Cheese"; 7 | } 8 | 9 | @Override 10 | public double getCost() { 11 | return super.getCost() + 1.00; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Problem/Pizza.cpp: -------------------------------------------------------------------------------- 1 | #ifndef PIZZA_CPP 2 | #define PIZZA_CPP 3 | 4 | #include 5 | 6 | class Pizza { 7 | public: 8 | virtual ~Pizza() {} 9 | virtual std::string getDescription() = 0; 10 | virtual double getCost() = 0; 11 | }; 12 | 13 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Problem/Pizza.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Problem; 2 | 3 | public interface Pizza { 4 | String getDescription(); 5 | double getCost(); 6 | } 7 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Problem/PizzaApp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "CheeseOlivePizza.cpp" 3 | 4 | int main() { 5 | Pizza* pizza = new CheeseOlivePizza(); 6 | std::cout << pizza->getDescription() << std::endl; 7 | std::cout << pizza->getCost() << std::endl; 8 | 9 | delete pizza; 10 | return 0; 11 | } -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Problem/PizzaApp.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Problem; 2 | 3 | public class PizzaApp { 4 | public static void main(String[] args) { 5 | Pizza pizza = new CheeseOlivePizza(); 6 | System.out.println(pizza.getDescription()); 7 | System.out.println(pizza.getCost()); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Solution/BasicPizza.cpp: -------------------------------------------------------------------------------- 1 | #ifndef BASIC_PIZZA_CPP 2 | #define BASIC_PIZZA_CPP 3 | 4 | #include "Pizza.cpp" 5 | 6 | class BasicPizza : public Pizza { 7 | public: 8 | std::string getDescription() override { 9 | return "Basic Pizza"; 10 | } 11 | 12 | double getCost() override { 13 | return 5.00; // base cost 14 | } 15 | }; 16 | 17 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Solution/BasicPizza.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Solution; 2 | 3 | public class BasicPizza implements Pizza { 4 | @Override 5 | public String getDescription() { 6 | return "Basic Pizza"; 7 | 8 | } 9 | 10 | @Override 11 | public double getCost() { 12 | return 5.00; //base cost 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Solution/CheeseDecorator.cpp: -------------------------------------------------------------------------------- 1 | #ifndef CHEESE_DECORATOR_CPP 2 | #define CHEESE_DECORATOR_CPP 3 | 4 | #include "PizzaDecorator.cpp" 5 | 6 | class CheeseDecorator : public PizzaDecorator { 7 | public: 8 | CheeseDecorator(Pizza* pizza) : PizzaDecorator(pizza) {} 9 | 10 | std::string getDescription() override { 11 | return decoratedPizza->getDescription() + ", Cheese"; 12 | } 13 | 14 | double getCost() override { 15 | return decoratedPizza->getCost() + 1.00; 16 | } 17 | }; 18 | 19 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Solution/CheeseDecorator.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Solution; 2 | 3 | public class CheeseDecorator extends PizzaDecorator { 4 | public CheeseDecorator(Pizza pizza){ 5 | super(pizza); 6 | } 7 | 8 | public String getDescription(){ 9 | return decoratedPizza.getDescription() + ", Cheese"; 10 | } 11 | public double getCost(){ 12 | return decoratedPizza.getCost() + 1.00; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Solution/MushroomDecorator.cpp: -------------------------------------------------------------------------------- 1 | #ifndef MUSHROOM_DECORATOR_CPP 2 | #define MUSHROOM_DECORATOR_CPP 3 | 4 | #include "PizzaDecorator.cpp" 5 | 6 | class MushroomDecorator : public PizzaDecorator { 7 | public: 8 | MushroomDecorator(Pizza* pizza) : PizzaDecorator(pizza) {} 9 | 10 | std::string getDescription() override { 11 | return decoratedPizza->getDescription() + ", Mushroom"; 12 | } 13 | 14 | double getCost() override { 15 | return decoratedPizza->getCost() + 2.00; 16 | } 17 | }; 18 | 19 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Solution/MushroomDecorator.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Solution; 2 | 3 | public class MushroomDecorator extends PizzaDecorator { 4 | public MushroomDecorator(Pizza pizza){ 5 | super(pizza); 6 | } 7 | 8 | public String getDescription(){ 9 | return decoratedPizza.getDescription() + ", Mushroom"; 10 | } 11 | public double getCost(){ 12 | return decoratedPizza.getCost() + 2.00; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Solution/OliveDecorator.cpp: -------------------------------------------------------------------------------- 1 | #ifndef OLIVE_DECORATOR_CPP 2 | #define OLIVE_DECORATOR_CPP 3 | 4 | #include "PizzaDecorator.cpp" 5 | 6 | class OliveDecorator : public PizzaDecorator { 7 | public: 8 | OliveDecorator(Pizza* pizza) : PizzaDecorator(pizza) {} 9 | 10 | std::string getDescription() override { 11 | return decoratedPizza->getDescription() + ", Olive"; 12 | } 13 | 14 | double getCost() override { 15 | return decoratedPizza->getCost() + 0.50; 16 | } 17 | }; 18 | 19 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Solution/OliveDecorator.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Solution; 2 | 3 | public class OliveDecorator extends PizzaDecorator { 4 | public OliveDecorator(Pizza pizza){ 5 | super(pizza); 6 | } 7 | 8 | public String getDescription(){ 9 | return decoratedPizza.getDescription() + ", Olive"; 10 | } 11 | public double getCost(){ 12 | return decoratedPizza.getCost() + 0.50; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Solution/Pizza.cpp: -------------------------------------------------------------------------------- 1 | #ifndef PIZZA_CPP 2 | #define PIZZA_CPP 3 | 4 | #include 5 | 6 | class Pizza { 7 | public: 8 | virtual ~Pizza() {} 9 | virtual std::string getDescription() = 0; 10 | virtual double getCost() = 0; 11 | }; 12 | 13 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Solution/Pizza.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Solution; 2 | 3 | public interface Pizza { 4 | String getDescription(); 5 | double getCost(); 6 | } 7 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Solution/PizzaApp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "BasicPizza.cpp" 3 | #include "CheeseDecorator.cpp" 4 | #include "OliveDecorator.cpp" 5 | #include "MushroomDecorator.cpp" 6 | 7 | int main() { 8 | // Basic Pizza 9 | Pizza* pizza = new BasicPizza(); 10 | 11 | // Add toppings 12 | pizza = new CheeseDecorator(pizza); 13 | pizza = new OliveDecorator(pizza); 14 | pizza = new MushroomDecorator(pizza); 15 | 16 | std::cout << pizza->getDescription() << std::endl; 17 | std::cout << pizza->getCost() << std::endl; 18 | 19 | // Cleanup is handled by decorator destructors 20 | delete pizza; 21 | 22 | return 0; 23 | } -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Solution/PizzaApp.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Solution; 2 | 3 | 4 | 5 | public class PizzaApp { 6 | public static void main(String[] args) { 7 | //Basic Pizza 8 | Pizza pizza = new BasicPizza(); 9 | 10 | //Add Cheese 11 | pizza = new CheeseDecorator(pizza); 12 | pizza = new OliveDecorator(pizza); 13 | pizza = new MushroomDecorator(pizza); 14 | 15 | System.out.println(pizza.getDescription()); 16 | System.out.println(pizza.getCost()); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Solution/PizzaDecorator.cpp: -------------------------------------------------------------------------------- 1 | #ifndef PIZZA_DECORATOR_CPP 2 | #define PIZZA_DECORATOR_CPP 3 | 4 | #include "Pizza.cpp" 5 | 6 | class PizzaDecorator : public Pizza { 7 | protected: 8 | Pizza* decoratedPizza; 9 | 10 | public: 11 | PizzaDecorator(Pizza* pizza) : decoratedPizza(pizza) {} 12 | 13 | virtual ~PizzaDecorator() { 14 | delete decoratedPizza; 15 | } 16 | 17 | std::string getDescription() override { 18 | return decoratedPizza->getDescription(); 19 | } 20 | 21 | double getCost() override { 22 | return decoratedPizza->getCost(); 23 | } 24 | }; 25 | 26 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/DecoratorPattern/Solution/PizzaDecorator.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Solution; 2 | 3 | abstract class PizzaDecorator implements Pizza{ 4 | protected Pizza decoratedPizza; 5 | 6 | public PizzaDecorator(Pizza pizza){ 7 | this.decoratedPizza = pizza; 8 | } 9 | 10 | @Override 11 | public String getDescription() { 12 | return decoratedPizza.getDescription(); 13 | } 14 | 15 | @Override 16 | public double getCost() { 17 | return decoratedPizza.getCost(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /cpp/StructuralPatterns/FacadePattern/Problem/Client.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "UserService.cpp" 3 | #include "OrderService.cpp" 4 | #include "PaymentService.cpp" 5 | 6 | int main() { 7 | // Client code interacting with different services directly 8 | UserService userService; 9 | OrderService orderService; 10 | PaymentService paymentService; 11 | 12 | // Task 13 | std::cout << userService.getUserDetails("123") << std::endl; 14 | std::cout << orderService.getOrderDetails("456") << std::endl; 15 | std::cout << paymentService.processPayment("789") << std::endl; 16 | 17 | return 0; 18 | } -------------------------------------------------------------------------------- /cpp/StructuralPatterns/FacadePattern/Problem/OrderService.cpp: -------------------------------------------------------------------------------- 1 | #ifndef ORDER_SERVICE_CPP 2 | #define ORDER_SERVICE_CPP 3 | 4 | #include 5 | 6 | class OrderService { 7 | public: 8 | std::string getOrderDetails(const std::string& orderId) { 9 | // Simulate fetching order details 10 | return "Order details for orderId: " + orderId; 11 | } 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/FacadePattern/Problem/PaymentService.cpp: -------------------------------------------------------------------------------- 1 | #ifndef PAYMENT_SERVICE_CPP 2 | #define PAYMENT_SERVICE_CPP 3 | 4 | #include 5 | 6 | class PaymentService { 7 | public: 8 | std::string processPayment(const std::string& paymentId) { 9 | // Simulate payment processing 10 | return "Processing payment with paymentId: " + paymentId; 11 | } 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/FacadePattern/Problem/UserService.cpp: -------------------------------------------------------------------------------- 1 | #ifndef USER_SERVICE_CPP 2 | #define USER_SERVICE_CPP 3 | 4 | #include 5 | 6 | class UserService { 7 | public: 8 | std::string getUserDetails(const std::string& userId) { 9 | // Simulate fetching user details 10 | return "User details for userId: " + userId; 11 | } 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/FacadePattern/Solution/Client.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "APIGateway.cpp" 3 | 4 | int main() { 5 | // Client code interacting with API Gateway (Facade) 6 | APIGateway apiGateway; 7 | 8 | // Task 9 | std::cout << apiGateway.getFullOrderDetails("123", "456", "789") << std::endl; 10 | 11 | return 0; 12 | } -------------------------------------------------------------------------------- /cpp/StructuralPatterns/FacadePattern/Solution/OrderService.cpp: -------------------------------------------------------------------------------- 1 | #ifndef ORDER_SERVICE_CPP 2 | #define ORDER_SERVICE_CPP 3 | 4 | #include 5 | 6 | class OrderService { 7 | public: 8 | std::string getOrderDetails(const std::string& orderId) { 9 | // Simulate fetching order details 10 | return "Order details for orderId: " + orderId; 11 | } 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/FacadePattern/Solution/PaymentService.cpp: -------------------------------------------------------------------------------- 1 | #ifndef PAYMENT_SERVICE_CPP 2 | #define PAYMENT_SERVICE_CPP 3 | 4 | #include 5 | 6 | class PaymentService { 7 | public: 8 | std::string processPayment(const std::string& paymentId) { 9 | // Simulate payment processing 10 | return "Processing payment with paymentId: " + paymentId; 11 | } 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/FacadePattern/Solution/UserService.cpp: -------------------------------------------------------------------------------- 1 | #ifndef USER_SERVICE_CPP 2 | #define USER_SERVICE_CPP 3 | 4 | #include 5 | 6 | class UserService { 7 | public: 8 | std::string getUserDetails(const std::string& userId) { 9 | // Simulate fetching user details 10 | return "User details for userId: " + userId; 11 | } 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/FlyWeightPattern/Problem/Bullet.cpp: -------------------------------------------------------------------------------- 1 | #ifndef BULLET_CPP 2 | #define BULLET_CPP 3 | 4 | #include 5 | #include 6 | 7 | class Bullet { 8 | private: 9 | std::string color; // Intrinsic property shared by all bullets 10 | int x, y; // Extrinsic properties unique to each bullet 11 | int velocity; 12 | 13 | public: 14 | Bullet(const std::string& color, int x, int y, int velocity) 15 | : color(color), x(x), y(y), velocity(velocity) { 16 | std::cout << "Creating bullet at (" << x << ", " << y 17 | << ") with velocity " << velocity << std::endl; 18 | } 19 | 20 | void display() { 21 | std::cout << "Bullet at (" << x << ", " << y 22 | << ") moving at velocity " << velocity << std::endl; 23 | } 24 | }; 25 | 26 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/FlyWeightPattern/Problem/Game.cpp: -------------------------------------------------------------------------------- 1 | #include "Bullet.cpp" 2 | 3 | int main() { 4 | // 5 Red Bullet Objects 5 | for(int i = 0; i < 5; i++) { 6 | Bullet bullet("Red", i*10, i*12, 5); 7 | } 8 | 9 | // 5 Green Bullet Objects 10 | for(int i = 0; i < 5; i++) { 11 | Bullet bullet("Red", i*10, i*12, 5); 12 | } 13 | 14 | // Problems 15 | // Memory Overhead : Every bullet stores redundant data like Color, Image 16 | // Performance : Slow performance when many bullets are created 17 | 18 | return 0; 19 | } -------------------------------------------------------------------------------- /cpp/StructuralPatterns/FlyWeightPattern/Solution/BulletType.cpp: -------------------------------------------------------------------------------- 1 | #ifndef BULLET_TYPE_CPP 2 | #define BULLET_TYPE_CPP 3 | 4 | #include 5 | #include 6 | 7 | // Flyweight Class 8 | class BulletType { 9 | private: 10 | std::string color; // Intrinsic Property 11 | 12 | public: 13 | BulletType(const std::string& color) : color(color) { 14 | std::cout << "Creating bulletType with color " << color << std::endl; 15 | } 16 | }; 17 | 18 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/FlyWeightPattern/Solution/BulletTypeFactory.cpp: -------------------------------------------------------------------------------- 1 | #ifndef BULLET_TYPE_FACTORY_CPP 2 | #define BULLET_TYPE_FACTORY_CPP 3 | 4 | #include 5 | #include 6 | #include "BulletType.cpp" 7 | 8 | class BulletTypeFactory { 9 | private: 10 | static std::map > bulletTypes; 11 | 12 | public: 13 | static std::shared_ptr getBulletType(const std::string& color) { 14 | if (bulletTypes.find(color) == bulletTypes.end()) { 15 | bulletTypes[color] = std::make_shared(color); 16 | } 17 | return bulletTypes[color]; 18 | } 19 | }; 20 | 21 | // Initialize static member 22 | std::map > BulletTypeFactory::bulletTypes; 23 | 24 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/FlyWeightPattern/Solution/Game.cpp: -------------------------------------------------------------------------------- 1 | #include "Bullet.cpp" 2 | 3 | int main() { 4 | // 5 Red Bullet Objects 5 | for(int i = 0; i < 5; i++) { 6 | Bullet bullet("Red", i*10, i*12, 5); 7 | } 8 | 9 | // 5 Green Bullet Objects 10 | for(int i = 0; i < 5; i++) { 11 | Bullet bullet("Red", i*10, i*12, 5); 12 | } 13 | 14 | return 0; 15 | } -------------------------------------------------------------------------------- /cpp/StructuralPatterns/ProxyPattern/Problem/Client.cpp: -------------------------------------------------------------------------------- 1 | #include "RealImage.cpp" 2 | 3 | int main() { 4 | Image* img1 = new RealImage("dog.png"); 5 | Image* img2 = new RealImage("cat.png"); 6 | 7 | // Here, the RealImage is loaded every time we create it, 8 | // which can be inefficient if the image is not always required. 9 | img1->display(); 10 | img1->display(); 11 | 12 | delete img1; 13 | delete img2; 14 | 15 | return 0; 16 | } -------------------------------------------------------------------------------- /cpp/StructuralPatterns/ProxyPattern/Problem/Image.cpp: -------------------------------------------------------------------------------- 1 | #ifndef IMAGE_CPP 2 | #define IMAGE_CPP 3 | 4 | class Image { 5 | public: 6 | virtual ~Image() {} 7 | virtual void display() = 0; 8 | }; 9 | 10 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/ProxyPattern/Problem/RealImage.cpp: -------------------------------------------------------------------------------- 1 | #ifndef REAL_IMAGE_CPP 2 | #define REAL_IMAGE_CPP 3 | 4 | #include 5 | #include 6 | #include "Image.cpp" 7 | 8 | class RealImage : public Image { 9 | private: 10 | std::string filename; 11 | 12 | void loadImageFromDisk() { 13 | std::cout << "Loading image from disk " << filename << std::endl; 14 | } 15 | 16 | public: 17 | RealImage(const std::string& filename) : filename(filename) { 18 | loadImageFromDisk(); // Expensive Operation 19 | } 20 | 21 | void display() override { 22 | std::cout << "Displaying: " << filename << std::endl; 23 | } 24 | }; 25 | 26 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/ProxyPattern/Solution/Client.cpp: -------------------------------------------------------------------------------- 1 | #include "ProxyImage.cpp" 2 | 3 | int main() { 4 | Image* img1 = new ProxyImage("dog.png"); 5 | Image* img2 = new ProxyImage("cat.png"); 6 | 7 | // The image is loaded lazily when needed, 8 | // saving time and resources if the image is never displayed. 9 | img1->display(); 10 | img1->display(); 11 | 12 | delete img1; 13 | delete img2; 14 | 15 | return 0; 16 | } -------------------------------------------------------------------------------- /cpp/StructuralPatterns/ProxyPattern/Solution/Image.cpp: -------------------------------------------------------------------------------- 1 | #ifndef IMAGE_CPP 2 | #define IMAGE_CPP 3 | 4 | class Image { 5 | public: 6 | virtual ~Image() {} 7 | virtual void display() = 0; 8 | }; 9 | 10 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/ProxyPattern/Solution/ProxyImage.cpp: -------------------------------------------------------------------------------- 1 | #ifndef PROXY_IMAGE_CPP 2 | #define PROXY_IMAGE_CPP 3 | 4 | #include 5 | #include "RealImage.cpp" 6 | 7 | using namespace std; 8 | 9 | class ProxyImage : public Image { 10 | private: 11 | string filename; 12 | RealImage* realImage; // Using raw pointer instead of unique_ptr 13 | 14 | public: 15 | ProxyImage(const std::string& filename) : filename(filename), realImage(nullptr) {} 16 | 17 | void display() { 18 | if (realImage == nullptr) { 19 | realImage = new RealImage(filename); // Image is loaded + cached 20 | } 21 | realImage->display(); 22 | } 23 | 24 | // Add destructor to clean up 25 | ~ProxyImage() { 26 | delete realImage; 27 | } 28 | }; 29 | 30 | #endif -------------------------------------------------------------------------------- /cpp/StructuralPatterns/ProxyPattern/Solution/RealImage.cpp: -------------------------------------------------------------------------------- 1 | #ifndef REAL_IMAGE_CPP 2 | #define REAL_IMAGE_CPP 3 | 4 | #include 5 | #include 6 | #include "Image.cpp" 7 | 8 | using namespace std; 9 | 10 | class RealImage : public Image { 11 | private: 12 | std::string filename; 13 | 14 | void loadImageFromDisk() { 15 | cout << "Loading image from disk " << filename << std::endl; 16 | } 17 | 18 | public: 19 | RealImage(const std::string& filename) : filename(filename) { 20 | loadImageFromDisk(); // Expensive Operation 21 | } 22 | 23 | void display() override { 24 | cout << "Displaying: " << filename << std::endl; 25 | } 26 | }; 27 | 28 | #endif -------------------------------------------------------------------------------- /design-patterns/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | !**/src/main/**/target/ 4 | !**/src/test/**/target/ 5 | 6 | ### IntelliJ IDEA ### 7 | .idea/modules.xml 8 | .idea/jarRepositories.xml 9 | .idea/compiler.xml 10 | .idea/libraries/ 11 | *.iws 12 | *.iml 13 | *.ipr 14 | 15 | ### Eclipse ### 16 | .apt_generated 17 | .classpath 18 | .factorypath 19 | .project 20 | .settings 21 | .springBeans 22 | .sts4-cache 23 | 24 | ### NetBeans ### 25 | /nbproject/private/ 26 | /nbbuild/ 27 | /dist/ 28 | /nbdist/ 29 | /.nb-gradle/ 30 | build/ 31 | !**/src/main/**/build/ 32 | !**/src/test/**/build/ 33 | 34 | ### VS Code ### 35 | .vscode/ 36 | 37 | ### Mac OS ### 38 | .DS_Store -------------------------------------------------------------------------------- /design-patterns/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /design-patterns/.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /design-patterns/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /design-patterns/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /design-patterns/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.example 8 | design-patterns 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 21 13 | 21 14 | UTF-8 15 | 16 | 17 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/Basics/OOPS/Card.java: -------------------------------------------------------------------------------- 1 | package org.prateek.Basics.OOPS; 2 | 3 | abstract public class Card implements PaymentMethod{ 4 | protected String cardNo; 5 | protected String userName; 6 | 7 | public Card(String cardNo,String name){ 8 | this.cardNo = cardNo; 9 | this.userName = name; 10 | } 11 | public String getCardNo(){ 12 | return cardNo; 13 | } 14 | public String getUserName(){ 15 | return userName; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/Basics/OOPS/Client.java: -------------------------------------------------------------------------------- 1 | package org.prateek.Basics.OOPS; 2 | 3 | public class Client { 4 | public static void main(String[] args) { 5 | PaymentService ps = new PaymentService(); 6 | ps.addPaymentMethod("PrateekDebitCard",new DebitCard("1234","Prateek Narang")); 7 | ps.addPaymentMethod("PrateekCreditCard",new CreditCard("5678","Prateek Narang")); 8 | ps.addPaymentMethod("PrateekUPI",new UPI("prateek27")); 9 | ps.addPaymentMethod("PrateekWallet",new Wallet()); 10 | ps.makePayment("PrateekUPI"); 11 | ps.makePayment("PrateekDebitCard"); 12 | ps.makePayment("PrateekWallet"); 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/Basics/OOPS/CreditCard.java: -------------------------------------------------------------------------------- 1 | package org.prateek.Basics.OOPS; 2 | 3 | public class CreditCard extends Card{ 4 | public CreditCard(String cardNo, String name) { 5 | super(cardNo, name); 6 | } 7 | 8 | @Override 9 | public void pay() { 10 | System.out.println("Making payment via Credit Card"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/Basics/OOPS/DebitCard.java: -------------------------------------------------------------------------------- 1 | package org.prateek.Basics.OOPS; 2 | 3 | public class DebitCard extends Card{ 4 | public DebitCard(String cardNo, String name) { 5 | super(cardNo, name); 6 | } 7 | 8 | @Override 9 | public void pay() { 10 | System.out.println("Making payment via Debit Card " + cardNo); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/Basics/OOPS/PaymentMethod.java: -------------------------------------------------------------------------------- 1 | package org.prateek.Basics.OOPS; 2 | 3 | public interface PaymentMethod { 4 | void pay(); 5 | } 6 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/Basics/OOPS/PaymentService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.Basics.OOPS; 2 | 3 | import java.util.HashMap; 4 | 5 | public class PaymentService { 6 | //Storing + Making payments 7 | HashMap paymentMethods; 8 | 9 | PaymentService(){ 10 | paymentMethods = new HashMap<>(); 11 | } 12 | 13 | public void addPaymentMethod(String name,PaymentMethod pm){ 14 | paymentMethods.put(name,pm); 15 | } 16 | public void makePayment(String name){ 17 | PaymentMethod pm = paymentMethods.get(name); 18 | pm.pay(); //Run Time Polymorphism 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/Basics/OOPS/UPI.java: -------------------------------------------------------------------------------- 1 | package org.prateek.Basics.OOPS; 2 | 3 | public class UPI implements PaymentMethod{ 4 | String upiId; 5 | 6 | UPI(String id){ 7 | this.upiId = id; 8 | } 9 | 10 | @Override 11 | public void pay() { 12 | System.out.println("Making payment via UPI "+upiId); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/Basics/OOPS/Wallet.java: -------------------------------------------------------------------------------- 1 | package org.prateek.Basics.OOPS; 2 | 3 | public class Wallet implements PaymentMethod{ 4 | @Override 5 | public void pay() { 6 | System.out.println("Making payment via wallet"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/Basics/UML/InheritanceExample.java: -------------------------------------------------------------------------------- 1 | package org.prateek.Basics.UML; 2 | 3 | // Superclass: Animal 4 | class Animal { 5 | public void eat() { 6 | System.out.println("This animal is eating"); 7 | } 8 | } 9 | 10 | // Subclass: Dog (inherits from Animal) 11 | class Dog extends Animal { 12 | public void bark() { 13 | System.out.println("The dog is barking"); 14 | } 15 | } 16 | 17 | // Main class 18 | public class InheritanceExample { 19 | public static void main(String[] args) { 20 | Dog dog = new Dog(); 21 | dog.eat(); // Inherited method from Animal class 22 | dog.bark(); // Method from Dog class 23 | // Output: 24 | // This animal is eating 25 | // The dog is barking 26 | } 27 | } -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/Basics/UML/RealizationExample.java: -------------------------------------------------------------------------------- 1 | package org.prateek.Basics.UML; 2 | 3 | // Payment interface (Realization) 4 | interface Payment { 5 | void pay(double amount); 6 | } 7 | 8 | // Class implementing the Payment interface 9 | class CreditCardPayment implements Payment { 10 | public void pay(double amount) { 11 | System.out.println("Paid $" + amount + " using credit card."); 12 | } 13 | } 14 | 15 | // Main class 16 | public class RealizationExample { 17 | public static void main(String[] args) { 18 | Payment payment = new CreditCardPayment(); 19 | payment.pay(100.0); // Output: Paid $100.0 using credit card. 20 | } 21 | } -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/BehaviouralPatterns/IteratorPattern/Book.java: -------------------------------------------------------------------------------- 1 | package org.prateek.BehaviouralPatterns.IteratorPattern; 2 | 3 | public class Book implements Comparable{ 4 | private String title; 5 | 6 | public Book(String title) { 7 | this.title = title; 8 | } 9 | 10 | public String getTitle() { 11 | return title; 12 | } 13 | 14 | 15 | @Override 16 | public String toString() { 17 | return "Book{" + 18 | "title='" + title + '\'' + 19 | '}'; 20 | } 21 | 22 | @Override 23 | public int compareTo(Book o) { 24 | return this.title.compareTo(o.title); 25 | } 26 | } -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/BehaviouralPatterns/IteratorPattern/BookCollectionV1.java: -------------------------------------------------------------------------------- 1 | package org.prateek.BehaviouralPatterns.IteratorPattern; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class BookCollectionV1 { 7 | private List books = new ArrayList<>(); 8 | 9 | public void addBook(Book book){ 10 | books.add(book); 11 | } 12 | 13 | public List getBooks(){ 14 | return books; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/BehaviouralPatterns/IteratorPattern/BookCollectionV3.java: -------------------------------------------------------------------------------- 1 | package org.prateek.BehaviouralPatterns.IteratorPattern; 2 | 3 | 4 | import com.sun.source.tree.Tree; 5 | 6 | import java.util.*; 7 | 8 | public class BookCollectionV3 implements Iterable{ 9 | private Set books = new TreeSet<>(); 10 | 11 | public void addBook(Book book){ 12 | books.add(book); 13 | } 14 | 15 | @Override 16 | public Iterator iterator() { 17 | return books.iterator(); 18 | } 19 | } -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/BehaviouralPatterns/IteratorPattern/ClientV1.java: -------------------------------------------------------------------------------- 1 | package org.prateek.BehaviouralPatterns.IteratorPattern; 2 | 3 | public class ClientV1 { 4 | public static void main(String[] args) { 5 | BookCollectionV1 bookCollection = new BookCollectionV1(); 6 | bookCollection.addBook(new Book("C++ Book")); 7 | bookCollection.addBook(new Book("Java Book")); 8 | bookCollection.addBook(new Book("Python Book")); 9 | 10 | for(int i=0;i iterator = bookCollection.createIterator(); 13 | while(iterator.hasNext()){ 14 | Book book = iterator.next(); 15 | System.out.println(book); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/BehaviouralPatterns/IteratorPattern/ClientV3.java: -------------------------------------------------------------------------------- 1 | package org.prateek.BehaviouralPatterns.IteratorPattern; 2 | 3 | import java.util.Iterator; 4 | 5 | public class ClientV3 { 6 | public static void main(String[] args) { 7 | BookCollectionV3 bookCollection = new BookCollectionV3(); 8 | bookCollection.addBook(new Book("Python Book")); 9 | bookCollection.addBook(new Book("C++ Book")); 10 | bookCollection.addBook(new Book("Java Book")); 11 | 12 | 13 | Iterator iterator = bookCollection.iterator(); //Standardized 14 | 15 | while(iterator.hasNext()){ 16 | Book book = iterator.next(); 17 | System.out.println(book); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/BehaviouralPatterns/MediatorPattern/WithoutMediatorPattern.java: -------------------------------------------------------------------------------- 1 | package org.prateek.BehaviouralPatterns.MediatorPattern; 2 | 3 | //Chat System 4 | class User{ 5 | private String name; 6 | 7 | public User(String name){ 8 | this.name = name; 9 | } 10 | 11 | public void sendMessage(String msg, User recipient){ 12 | System.out.println(this.name + " sending "+ msg + " to " + recipient.getName()); 13 | } 14 | 15 | public String getName(){ 16 | return name; 17 | } 18 | } 19 | 20 | 21 | public class WithoutMediatorPattern { 22 | public static void main(String[] args) { 23 | User rahul = new User("Rahul"); 24 | User amit = new User("Amit"); 25 | User neha = new User("Neha"); 26 | 27 | rahul.sendMessage("Hello",amit); 28 | rahul.sendMessage("Hello",neha); 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/BehaviouralPatterns/MementoPattern/Caretaker.java: -------------------------------------------------------------------------------- 1 | package org.prateek.BehaviouralPatterns.MementoPattern; 2 | 3 | import java.util.Stack; 4 | 5 | //Caretaker Class: Manage mementos (snapshots of the TextEditor state) 6 | public class Caretaker { 7 | private final Stack history = new Stack<>(); 8 | 9 | public void saveState(TextEditor editor){ 10 | history.push(editor.save()); 11 | } 12 | public void undo(TextEditor editor){ 13 | if(!history.empty()){ 14 | history.pop(); 15 | editor.restore(history.peek()); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/BehaviouralPatterns/MementoPattern/EditorMemento.java: -------------------------------------------------------------------------------- 1 | package org.prateek.BehaviouralPatterns.MementoPattern; 2 | 3 | //Mementor Class: Stores the internal state of the TextEditor 4 | public class EditorMemento { 5 | private final String content; 6 | 7 | public EditorMemento(String content) { 8 | this.content = content; 9 | } 10 | 11 | public String getContent(){ 12 | return content; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/BehaviouralPatterns/MementoPattern/TextEditorMain.java: -------------------------------------------------------------------------------- 1 | package org.prateek.BehaviouralPatterns.MementoPattern; 2 | 3 | public class TextEditorMain { 4 | public static void main(String[] args) { 5 | TextEditor editor = new TextEditor(); 6 | Caretaker caretaker = new Caretaker(); //History / StateMgmt 7 | 8 | editor.write("A"); 9 | caretaker.saveState(editor); 10 | 11 | editor.write("B"); 12 | caretaker.saveState(editor); 13 | //Problem - > Undo the last write! 14 | editor.write("C"); 15 | caretaker.saveState(editor); 16 | 17 | //CareTaker Undo 18 | caretaker.undo(editor); 19 | 20 | System.out.println(editor.getContent()); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/BehaviouralPatterns/StatePattern/Problem/WithoutStatePattern.java: -------------------------------------------------------------------------------- 1 | package org.prateek.BehaviouralPatterns.StatePattern.Problem; 2 | 3 | public class WithoutStatePattern { 4 | public static void main(String[] args) { 5 | DirectionService directionService = new DirectionService(TransportationMode.TRAIN); 6 | directionService.setMode(TransportationMode.CAR); 7 | 8 | System.out.println(directionService.getDirection()); 9 | directionService.getETA(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/BehaviouralPatterns/StatePattern/Solution/Car.java: -------------------------------------------------------------------------------- 1 | package org.prateek.BehaviouralPatterns.StatePattern.Solution; 2 | 3 | public class Car implements TransportationMode { 4 | @Override 5 | public int calcETA() { 6 | System.out.println("Calculating ETA (Car)"); 7 | return 3; // Example ETA for car 8 | } 9 | 10 | @Override 11 | public String getDirection() { 12 | return "Directions for driving"; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/BehaviouralPatterns/StatePattern/Solution/Cycling.java: -------------------------------------------------------------------------------- 1 | package org.prateek.BehaviouralPatterns.StatePattern.Solution; 2 | 3 | public class Cycling implements TransportationMode{ 4 | @Override 5 | public int calcETA() { 6 | System.out.println("Calculating ETA (Cycling)"); 7 | return 5; // Example ETA for cycling 8 | } 9 | 10 | @Override 11 | public String getDirection() { 12 | return "Directions for cycling"; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/BehaviouralPatterns/StatePattern/Solution/DirectionService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.BehaviouralPatterns.StatePattern.Solution; 2 | 3 | public class DirectionService { 4 | TransportationMode transportationMode; 5 | public DirectionService(TransportationMode transportationMode){ 6 | this.transportationMode = transportationMode; 7 | } 8 | public void setTransportationMode(TransportationMode mode){ 9 | this.transportationMode = mode; 10 | } 11 | //delegating the work current state's concrete class 12 | public int getETA(){ 13 | return transportationMode.calcETA(); 14 | } 15 | public String getDirection(){ 16 | return transportationMode.getDirection(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/BehaviouralPatterns/StatePattern/Solution/Train.java: -------------------------------------------------------------------------------- 1 | package org.prateek.BehaviouralPatterns.StatePattern.Solution; 2 | 3 | public class Train implements TransportationMode { 4 | @Override 5 | public int calcETA() { 6 | System.out.println("Calculating ETA (Train)"); 7 | return 7; // Example ETA for train 8 | } 9 | 10 | @Override 11 | public String getDirection() { 12 | return "Directions for train route"; 13 | } 14 | } -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/BehaviouralPatterns/StatePattern/Solution/TransportationMode.java: -------------------------------------------------------------------------------- 1 | package org.prateek.BehaviouralPatterns.StatePattern.Solution; 2 | 3 | //State Interface 4 | public interface TransportationMode { 5 | int calcETA(); 6 | String getDirection(); 7 | } 8 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/BehaviouralPatterns/StatePattern/Solution/Walking.java: -------------------------------------------------------------------------------- 1 | package org.prateek.BehaviouralPatterns.StatePattern.Solution; 2 | 3 | public class Walking implements TransportationMode{ 4 | @Override 5 | public int calcETA() { 6 | System.out.println("Calculating ETA (Walking)"); 7 | return 10; // Example ETA for walking 8 | } 9 | 10 | @Override 11 | public String getDirection() { 12 | return "Directions for walking"; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/BehaviouralPatterns/StatePattern/Solution/WithStatePattern.java: -------------------------------------------------------------------------------- 1 | package org.prateek.BehaviouralPatterns.StatePattern.Solution; 2 | 3 | 4 | public class WithStatePattern { 5 | public static void main(String[] args) { 6 | DirectionService service = new DirectionService(new Car()); 7 | // service.setTransportationMode(new Cycling()); 8 | 9 | System.out.println("ETA: " + service.getETA()); 10 | System.out.println("Direction: " + service.getDirection()); 11 | 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/BuilderPattern/Problem/WithoutBuilderPattern.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.BuilderPattern.Problem; 2 | 3 | public class WithoutBuilderPattern { 4 | public static void main(String[] args) { 5 | House house = new House("Concrete","Wood","Shingles",true,true,false); 6 | //House house2 = new House("Concrete","Wood","Shingles"); 7 | // Constructor Explosion -> Too Many Constructors 8 | // Difficult to understand and maintain this code 9 | // this is where builder pattern comes into picture 10 | System.out.println(house); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/BuilderPattern/Solution/WithBuilderPattern.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.BuilderPattern.Solution; 2 | 3 | 4 | public class WithBuilderPattern { 5 | public static void main(String[] args) { 6 | House house = new House.HouseBuilder("Concrete", "Wooden", "Tile") 7 | .setGarden(true) 8 | .setSwimmingPool(true) 9 | .setGarage(false) 10 | .build(); 11 | 12 | System.out.println(house); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/FactoryPattern/Problem/Bike.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.FactoryPattern.Problem; 2 | 3 | public class Bike implements Transport{ 4 | @Override 5 | public void deliver() { 6 | System.out.println("Deliver by bike"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/FactoryPattern/Problem/Bus.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.FactoryPattern.Problem; 2 | 3 | public class Bus implements Transport{ 4 | @Override 5 | public void deliver() { 6 | System.out.println("Deliver by bus"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/FactoryPattern/Problem/Car.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.FactoryPattern.Problem; 2 | 3 | public class Car implements Transport{ 4 | @Override 5 | public void deliver() { 6 | System.out.println("Deliver by car"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/FactoryPattern/Problem/Transport.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.FactoryPattern.Problem; 2 | 3 | public interface Transport { 4 | void deliver(); 5 | } 6 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/FactoryPattern/Problem/TransportService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.FactoryPattern.Problem; 2 | 3 | public class TransportService { 4 | public static void main(String[] args) { 5 | //Direct create objects 6 | Transport car = new Car(); 7 | Transport bike = new Bike(); 8 | //add a bus object 9 | Transport bus = new Bus(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/FactoryPattern/Solution/Bike.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.FactoryPattern.Solution; 2 | 3 | public class Bike implements Transport { 4 | @Override 5 | public void deliver() { 6 | System.out.println("Deliver by bike"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/FactoryPattern/Solution/Bus.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.FactoryPattern.Solution; 2 | 3 | public class Bus implements Transport { 4 | @Override 5 | public void deliver() { 6 | System.out.println("Deliver by bus"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/FactoryPattern/Solution/Car.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.FactoryPattern.Solution; 2 | 3 | public class Car implements Transport { 4 | @Override 5 | public void deliver() { 6 | System.out.println("Deliver by car"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/FactoryPattern/Solution/Transport.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.FactoryPattern.Solution; 2 | 3 | public interface Transport { 4 | void deliver(); 5 | } 6 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/FactoryPattern/Solution/TransportFactory.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.FactoryPattern.Solution; 2 | 3 | public class TransportFactory { 4 | public static Transport createTransport(String type){ 5 | switch(type.toLowerCase()){ 6 | case "car": 7 | return new Car(); 8 | case "bike": 9 | return new Bike(); 10 | case "bus": 11 | return new Bus(); 12 | default: 13 | throw new IllegalArgumentException("Unsupported transport type"); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/FactoryPattern/Solution/TransportService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.FactoryPattern.Solution; 2 | 3 | 4 | public class TransportService { 5 | public static void main(String[] args) { 6 | //Direct create objects 7 | Transport vehicle = TransportFactory.createTransport("car"); 8 | vehicle.deliver(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/PrototypePattern/Problem/GameBoard.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.PrototypePattern.Problem; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class GameBoard { 7 | private List pieces = new ArrayList<>(); 8 | 9 | public void addPiece(GamePiece piece){ 10 | pieces.add(piece); 11 | } 12 | 13 | public List getPieces(){ 14 | return pieces; 15 | } 16 | 17 | public void showBoardState(){ 18 | for(GamePiece piece:pieces){ 19 | System.out.println(piece); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/PrototypePattern/Problem/GameClientWithoutPrototype.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.PrototypePattern.Problem; 2 | 3 | public class GameClientWithoutPrototype { 4 | public static void main(String[] args) { 5 | GameBoard gameBoard = new GameBoard(); 6 | gameBoard.addPiece(new GamePiece("Red",1)); 7 | gameBoard.addPiece(new GamePiece("Blue",5)); 8 | gameBoard.showBoardState(); 9 | 10 | //Checkpoint this state 11 | GameBoard copiedBoard = new GameBoard(); 12 | for(GamePiece piece: gameBoard.getPieces()){ 13 | copiedBoard.addPiece(new GamePiece(piece.getColor(), piece.getPosition())); 14 | } 15 | 16 | System.out.println("Copied Board"); 17 | copiedBoard.showBoardState(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/PrototypePattern/Solution/GameClientWithPrototype.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.PrototypePattern.Solution; 2 | 3 | public class GameClientWithPrototype { 4 | public static void main(String[] args) { 5 | GameBoard gameBoard = new GameBoard(); 6 | gameBoard.addPiece(new GamePiece("Red",1)); 7 | gameBoard.addPiece(new GamePiece("Blue",5)); 8 | gameBoard.showBoardState(); 9 | 10 | //Checkpoint this state 11 | GameBoard copiedBoard = gameBoard.clone(); 12 | 13 | System.out.println("Copied Board"); 14 | copiedBoard.showBoardState(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/PrototypePattern/Solution/Prototype.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.PrototypePattern.Solution; 2 | 3 | public interface Prototype { 4 | T clone(); 5 | } 6 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/SingletonPattern/Problem/AppSettings.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.SingletonPattern.Problem; 2 | 3 | public class AppSettings { 4 | private String databaseUrl; 5 | private String apiKey; 6 | 7 | public AppSettings(){ 8 | //Read settings from a config file 9 | databaseUrl = "jdbc:mysql://localhost:3306/mydatabase"; 10 | apiKey = "12345-ABCDE"; 11 | } 12 | 13 | public String getDatabaseUrl(){ 14 | return databaseUrl; 15 | } 16 | public String getApiKey(){ 17 | return apiKey; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/SingletonPattern/Problem/WithoutSingletonPattern.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.SingletonPattern.Problem; 2 | 3 | public class WithoutSingletonPattern { 4 | public static void main(String[] args) { 5 | AppSettings appSettings = new AppSettings(); 6 | AppSettings appSettingsCopy = new AppSettings(); 7 | 8 | System.out.println(appSettingsCopy.getApiKey()); 9 | System.out.println(appSettings.getApiKey()); 10 | 11 | //More memory 12 | System.out.println(appSettings==appSettingsCopy); 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/CreationalPatterns/SingletonPattern/Solution/SingletonPattern.java: -------------------------------------------------------------------------------- 1 | package org.prateek.CreationalPatterns.SingletonPattern.Solution; 2 | 3 | 4 | public class SingletonPattern { 5 | public static void main(String[] args) { 6 | AppSettings appSettings = AppSettings.getInstance(); //change this code 7 | AppSettings appSettingsCopy = AppSettings.getInstance(); 8 | 9 | System.out.println(appSettingsCopy.getApiKey()); 10 | System.out.println(appSettings.getApiKey()); 11 | 12 | //More memory 13 | System.out.println(appSettings==appSettingsCopy); 14 | 15 | } 16 | } -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/LLDProject/RideSharingApp/V1/Driver.java: -------------------------------------------------------------------------------- 1 | package org.prateek.LLDProject.RideSharingApp.V1; 2 | 3 | public class Driver { 4 | 5 | 6 | 7 | private String name; 8 | private Vehicle vehicle; 9 | Location location; 10 | 11 | public Driver(String name,Location location,Vehicle vehicle) { 12 | this.name = name; 13 | this.vehicle = vehicle; 14 | this.location = location; 15 | } 16 | 17 | public Location getLocation() { 18 | return location; 19 | } 20 | 21 | public void setLocation(Location location) { 22 | this.location = location; 23 | } 24 | 25 | public String getName() { 26 | return name; 27 | } 28 | public Vehicle getVehicle() { 29 | return vehicle; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/LLDProject/RideSharingApp/V1/Location.java: -------------------------------------------------------------------------------- 1 | package org.prateek.LLDProject.RideSharingApp.V1; 2 | 3 | public class Location { 4 | private double latitude; 5 | private double longitude; 6 | public Location(double latitude, double longitude) { 7 | this.latitude = latitude; 8 | this.longitude = longitude; 9 | } 10 | public double getLatitude() { 11 | return latitude; 12 | } 13 | 14 | public double getLongitude() { 15 | return longitude; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/LLDProject/RideSharingApp/V1/Passenger.java: -------------------------------------------------------------------------------- 1 | package org.prateek.LLDProject.RideSharingApp.V1; 2 | 3 | public class Passenger { 4 | String name; 5 | Location location; 6 | 7 | public Passenger(String name, Location location) { 8 | this.name = name; 9 | this.location = location; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/LLDProject/RideSharingApp/V1/Vehicle.java: -------------------------------------------------------------------------------- 1 | package org.prateek.LLDProject.RideSharingApp.V1; 2 | 3 | public class Vehicle { 4 | 5 | String numberPlate; 6 | String type; 7 | 8 | public Vehicle(String numberPlate, String type) { 9 | this.numberPlate = numberPlate; 10 | this.type = type; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/LLDProject/RideSharingApp/V2/Bike.java: -------------------------------------------------------------------------------- 1 | package org.prateek.LLDProject.RideSharingApp.V2; 2 | 3 | public class Bike extends Vehicle { 4 | public Bike(String numberPlate) { 5 | super(numberPlate); 6 | } 7 | 8 | @Override 9 | public double getFarePerKm() { 10 | return 10; 11 | } 12 | } -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/LLDProject/RideSharingApp/V2/Car.java: -------------------------------------------------------------------------------- 1 | package org.prateek.LLDProject.RideSharingApp.V2; 2 | 3 | ; 4 | 5 | public class Car extends Vehicle { 6 | public Car(String numberPlate) { 7 | super(numberPlate); 8 | } 9 | 10 | @Override 11 | public double getFarePerKm() { 12 | return 20; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/LLDProject/RideSharingApp/V2/Driver.java: -------------------------------------------------------------------------------- 1 | package org.prateek.LLDProject.RideSharingApp.V2; 2 | 3 | 4 | public class Driver extends User{ 5 | private Vehicle vehicle; 6 | public Driver(String name, String email, Location location, Vehicle vehicle) { 7 | super(name, email, location); 8 | this.vehicle = vehicle; 9 | } 10 | public Vehicle getVehicle(){ 11 | return vehicle; 12 | } 13 | //Any other methods?? 14 | public void notify(String msg){ 15 | System.out.println("Driver " + msg); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/LLDProject/RideSharingApp/V2/Location.java: -------------------------------------------------------------------------------- 1 | package org.prateek.LLDProject.RideSharingApp.V2; 2 | 3 | public class Location { 4 | private double latitude; 5 | private double longitude; 6 | public Location(double latitude, double longitude) { 7 | this.latitude = latitude; 8 | this.longitude = longitude; 9 | } 10 | public double getLatitude() { 11 | return latitude; 12 | } 13 | 14 | public double getLongitude() { 15 | return longitude; 16 | } 17 | 18 | public double calcDistance(Location two){ 19 | //Euclidean Distance 20 | double dx = this.getLatitude() - two.getLatitude(); 21 | double dy = this.getLongitude() - two.getLongitude(); 22 | return Math.sqrt(dx*dx + dy*dy); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/LLDProject/RideSharingApp/V2/Passenger.java: -------------------------------------------------------------------------------- 1 | package org.prateek.LLDProject.RideSharingApp.V2; 2 | 3 | public class Passenger extends User{ 4 | public Passenger(String name, String email, Location location) { 5 | super(name, email, location); 6 | } 7 | //any other methods?? 8 | public void notify(String msg){ 9 | System.out.println("passenger : " + msg); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/LLDProject/RideSharingApp/V2/User.java: -------------------------------------------------------------------------------- 1 | package org.prateek.LLDProject.RideSharingApp.V2; 2 | 3 | import org.prateek.LLDProject.RideSharingApp.V1.Passenger; 4 | 5 | abstract class User { 6 | protected String name; 7 | protected String email; 8 | protected Location location; 9 | 10 | public User(String name,String email,Location location){ 11 | this.name = name; 12 | this.email = email; 13 | this.location = location; 14 | } 15 | //Setter 16 | public Location getLocation(){ 17 | return location; 18 | } 19 | public void setLocation(Location location){ 20 | this.location = location; 21 | } 22 | //any other methods ? 23 | public abstract void notify(String msg); 24 | 25 | } 26 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/LLDProject/RideSharingApp/V2/Vehicle.java: -------------------------------------------------------------------------------- 1 | package org.prateek.LLDProject.RideSharingApp.V2; 2 | 3 | abstract class Vehicle { 4 | protected String numberPlate; 5 | 6 | public Vehicle(String numberPlate){ 7 | this.numberPlate = numberPlate; 8 | } 9 | //Fare Calc 10 | public abstract double getFarePerKm(); 11 | } 12 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/DIP/BadCode/EmailService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.DIP.BadCode; 2 | 3 | public class EmailService { 4 | public void sendEmail(String message) { 5 | System.out.println("Sending email: " + message); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/DIP/BadCode/NotificationService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.DIP.BadCode; 2 | 3 | public class NotificationService { 4 | private EmailService emailService; 5 | private SMSService smsService; 6 | 7 | public NotificationService(){ 8 | this.emailService = new EmailService(); 9 | this.smsService = new SMSService(); 10 | } 11 | 12 | public void notifyByEmail(String msg){ 13 | emailService.sendEmail(msg); 14 | } 15 | public void notifyBySMS(String msg){ 16 | smsService.sendSMS(msg); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/DIP/BadCode/SMSService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.DIP.BadCode; 2 | 3 | class SMSService { 4 | public void sendSMS(String message) { 5 | System.out.println("Sending SMS: " + message); 6 | } 7 | } -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/DIP/GoodCode/EmailService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.DIP.GoodCode; 2 | 3 | public class EmailService implements NotificationChannel{ 4 | @Override 5 | public void send(String msg) { 6 | System.out.println("Sending Email " + msg); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/DIP/GoodCode/Main.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.DIP.GoodCode; 2 | 3 | 4 | public class Main { 5 | public static void main(String[] args) { 6 | NotificationService emailNotification = new NotificationService(new EmailService()); 7 | emailNotification.notify("Your order has been shipped"); 8 | 9 | NotificationService smsNotification = new NotificationService(new SMSService()); 10 | smsNotification.notify("OTP 1234"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/DIP/GoodCode/NotificationChannel.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.DIP.GoodCode; 2 | 3 | public interface NotificationChannel { 4 | void send(String msg); 5 | } 6 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/DIP/GoodCode/NotificationService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.DIP.GoodCode; 2 | 3 | public class NotificationService { 4 | private NotificationChannel notificationChannel; 5 | 6 | public NotificationService(NotificationChannel channel){ 7 | this.notificationChannel = channel; 8 | } 9 | 10 | public void notify(String msg){ 11 | notificationChannel.send(msg); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/DIP/GoodCode/SMSService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.DIP.GoodCode; 2 | 3 | public class SMSService implements NotificationChannel{ 4 | @Override 5 | public void send(String msg) { 6 | System.out.println("Sending SMS " + msg); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/ISP/BadCode/Document.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.ISP.BadCode; 2 | 3 | public class Document { 4 | } 5 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/ISP/BadCode/Machine.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.ISP.BadCode; 2 | 3 | // Monolithic Machine interface 4 | interface Machine { 5 | void print(Document doc); 6 | void scan(Document doc); 7 | void copy(Document doc); 8 | } 9 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/ISP/BadCode/MultiPurposeMachine.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.ISP.BadCode; 2 | 3 | public class MultiPurposeMachine implements Machine{ 4 | @Override 5 | public void print(Document doc) { 6 | System.out.println("Printing document..."); 7 | 8 | } 9 | 10 | @Override 11 | public void scan(Document doc) { 12 | System.out.println("Scan document..."); 13 | 14 | } 15 | 16 | @Override 17 | public void copy(Document doc) { 18 | System.out.println("Copy document..."); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/ISP/BadCode/SimplePrinter.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.ISP.BadCode; 2 | 3 | public class SimplePrinter implements Machine{ 4 | @Override 5 | public void print(Document doc) { 6 | System.out.println("Printing document..."); 7 | } 8 | 9 | @Override 10 | public void scan(Document doc) { 11 | throw new UnsupportedOperationException("Scan not supported."); 12 | } 13 | 14 | @Override 15 | public void copy(Document doc) { 16 | throw new UnsupportedOperationException("Copy not supported."); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/ISP/GoodCode/Copier.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.ISP.GoodCode; 2 | 3 | import org.prateek.SOLIDPrinciples.ISP.BadCode.Document; 4 | 5 | public interface Copier { 6 | void copy(Document doc); 7 | } 8 | 9 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/ISP/GoodCode/MultiPurposeMachine.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.ISP.GoodCode; 2 | 3 | import org.prateek.SOLIDPrinciples.ISP.BadCode.Document; 4 | 5 | 6 | public class MultiPurposeMachine implements Printer,Scanner,Copier { 7 | @Override 8 | public void print(Document doc) { 9 | System.out.println("Printing document..."); 10 | 11 | } 12 | 13 | @Override 14 | public void scan(Document doc) { 15 | System.out.println("Scan document..."); 16 | 17 | } 18 | 19 | @Override 20 | public void copy(Document doc) { 21 | System.out.println("Copy document..."); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/ISP/GoodCode/Printer.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.ISP.GoodCode; 2 | 3 | import org.prateek.SOLIDPrinciples.ISP.BadCode.Document; 4 | 5 | public interface Printer { 6 | void print(Document doc); 7 | } 8 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/ISP/GoodCode/Scanner.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.ISP.GoodCode; 2 | 3 | import org.prateek.SOLIDPrinciples.ISP.BadCode.Document; 4 | 5 | public interface Scanner { 6 | void scan(Document doc); 7 | } 8 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/ISP/GoodCode/SimplerPrinter.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.ISP.GoodCode; 2 | 3 | import org.prateek.SOLIDPrinciples.ISP.BadCode.Document; 4 | 5 | public class SimplerPrinter implements Printer{ 6 | @Override 7 | public void print(Document doc) { 8 | System.out.println("Printing the document"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/LSP/BadCode/File.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.LSP.BadCode; 2 | 3 | public class File { 4 | public void read(){ 5 | System.out.println("reading from file..."); 6 | } 7 | public void write(){ 8 | System.out.println("Writing to file..."); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/LSP/BadCode/Main.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.LSP.BadCode; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | File file = new ReadOnlyFile(); 6 | file.read(); //works fine 7 | file.write(); // throwing an exception, violation of LSP 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/LSP/BadCode/ReadOnlyFile.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.LSP.BadCode; 2 | 3 | public class ReadOnlyFile extends File{ 4 | public void write(){ 5 | throw new UnsupportedOperationException("Can't write to a read only file"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/LSP/GoodCode/Main.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.LSP.GoodCode; 2 | 3 | public class Main { 4 | 5 | public static void readAnyFile(ReadableFile file){ 6 | file.read(); 7 | } 8 | 9 | public static void main(String[] args) { 10 | ReadableFile readableFile = new ReadOnlyFile(); 11 | readableFile.read(); 12 | 13 | WritableFile writableFile = new WritableFile(); 14 | writableFile.read(); 15 | writableFile.write(); 16 | 17 | readAnyFile(readableFile); 18 | readAnyFile(writableFile); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/LSP/GoodCode/ReadOnlyFile.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.LSP.GoodCode; 2 | 3 | public class ReadOnlyFile extends ReadableFile{ 4 | } 5 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/LSP/GoodCode/Readable.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.LSP.GoodCode; 2 | 3 | public interface Readable { 4 | void read(); 5 | } 6 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/LSP/GoodCode/ReadableFile.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.LSP.GoodCode; 2 | 3 | public class ReadableFile implements Readable{ 4 | public void read(){ 5 | System.out.println("Reading from a file"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/LSP/GoodCode/Writable.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.LSP.GoodCode; 2 | 3 | public interface Writable { 4 | void write(); 5 | } 6 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/LSP/GoodCode/WritableFile.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.LSP.GoodCode; 2 | 3 | public class WritableFile extends ReadableFile implements Writable { 4 | 5 | @Override 6 | public void write() { 7 | System.out.println("Writing to a file ..."); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/OCP/GoodCode/CreditCard.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.OCP.GoodCode; 2 | 3 | public class CreditCard implements PaymentMethod{ 4 | 5 | @Override 6 | public void pay(double amount) { 7 | System.out.println("Making Payment via Credit Card" + amount); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/OCP/GoodCode/DebitCard.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.OCP.GoodCode; 2 | 3 | public class DebitCard implements PaymentMethod{ 4 | 5 | @Override 6 | public void pay(double amount) { 7 | System.out.println("Making Payment via Debit Card " + amount); 8 | } 9 | } -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/OCP/GoodCode/Main.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.OCP.GoodCode; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | PaymentProcessor processor = new PaymentProcessor(); 6 | PaymentMethod creditCard = new CreditCard(); 7 | PaymentMethod upi = new UPI(); 8 | 9 | processor.processPayment(creditCard,100); 10 | processor.processPayment(upi,120); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/OCP/GoodCode/PayPal.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.OCP.GoodCode; 2 | 3 | public class PayPal implements PaymentMethod{ 4 | 5 | @Override 6 | public void pay(double amount) { 7 | System.out.println("Making Payment via PayPal"); 8 | } 9 | } -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/OCP/GoodCode/PaymentMethod.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.OCP.GoodCode; 2 | 3 | public interface PaymentMethod { 4 | void pay(double amount); 5 | } 6 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/OCP/GoodCode/PaymentProcessor.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.OCP.GoodCode; 2 | 3 | public class PaymentProcessor { 4 | public void processPayment(PaymentMethod paymentMethod,double amount){ 5 | paymentMethod.pay(amount); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/OCP/GoodCode/UPI.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.OCP.GoodCode; 2 | 3 | public class UPI implements PaymentMethod{ 4 | 5 | @Override 6 | public void pay(double amount) { 7 | System.out.println("Making payment via UPI " +amount); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/SRP/BadCode/Invoice.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.SRP.BadCode; 2 | 3 | public class Invoice { 4 | private double amount; 5 | 6 | public Invoice(double amount){ 7 | this.amount = amount; 8 | } 9 | 10 | //Additional Functionality 11 | public void generateInvoice(){ 12 | System.out.println("Invoice generated & printed for amount " +amount); 13 | } 14 | 15 | public void saveToDatabase(){ 16 | System.out.println("Saving invoice to Database "); 17 | } 18 | 19 | public void sendEmailNotification(){ 20 | System.out.println("Sending email notification for invoice "); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/SRP/GoodCode/EmailService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.SRP.GoodCode; 2 | 3 | public class EmailService { 4 | public void sendEmailNotification(){ 5 | System.out.println("Sending email notification for invoice "); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/SRP/GoodCode/Invoice.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.SRP.GoodCode; 2 | 3 | public class Invoice { 4 | private double amount; 5 | 6 | public Invoice(double amount){ 7 | this.amount = amount; 8 | } 9 | 10 | //Additional Functionality 11 | public void generateInvoice(){ 12 | System.out.println("Invoice generated & printed for amount " +amount); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/SOLIDPrinciples/SRP/GoodCode/InvoiceRepository.java: -------------------------------------------------------------------------------- 1 | package org.prateek.SOLIDPrinciples.SRP.GoodCode; 2 | 3 | public class InvoiceRepository { 4 | public void saveToDatabase(){ 5 | System.out.println("Saving invoice to Database "); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/AdapterPattern/Client.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.AdapterPattern; 2 | 3 | public class Client { 4 | public static void main(String[] args) { 5 | NotificationService emailService = new EmailNotificationService(); 6 | emailService.send("customer@codingminutes.com","order confirmation","your order has been received!"); 7 | 8 | //NotificationService sendGridEmailService = new SendGridService(); 9 | NotificationService emailServiceUsingSendGrid = new SendGridAdapter(new SendGridService()); 10 | emailServiceUsingSendGrid.send("customer@codingminutes.com","order confirmation","your order has been received!"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/AdapterPattern/EmailNotificationService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.AdapterPattern; 2 | 3 | //Legacy Code: Email Notification Service 4 | public class EmailNotificationService implements NotificationService { 5 | public void send(String to,String subject,String body){ 6 | System.out.println("Sending Email to " + to); 7 | System.out.println("Subject: " + subject); 8 | System.out.println("Body: "+body); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/AdapterPattern/NotificationService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.AdapterPattern; 2 | 3 | interface NotificationService { 4 | void send(String to,String subject,String body); 5 | } 6 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/AdapterPattern/SendGridAdapter.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.AdapterPattern; 2 | 3 | public class SendGridAdapter implements NotificationService{ 4 | private SendGridService sendGridService; 5 | 6 | public SendGridAdapter(SendGridService sendGridService){ 7 | this.sendGridService = sendGridService; 8 | } 9 | 10 | @Override 11 | public void send(String to, String subject, String body) { 12 | //Adapter Method -> convert parameters and calls to SendGrid Method 13 | sendGridService.sendEmail(to,subject,body); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/AdapterPattern/SendGridService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.AdapterPattern; 2 | 3 | public class SendGridService { 4 | public void sendEmail(String recipient, String title, String content){ 5 | System.out.println("Sending email via SendGrid to " + recipient); 6 | System.out.println("Title: " + title); 7 | System.out.println("Content: " + content); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/CompositePattern/Problem/File.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.CompositePattern.Problem; 2 | 3 | public class File { 4 | private String name; 5 | 6 | public File(String name){ 7 | this.name = name; 8 | } 9 | 10 | public void showDetails(){ 11 | System.out.println("File : " +name); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/CompositePattern/Problem/FileSystemApp.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.CompositePattern.Problem; 2 | 3 | public class FileSystemApp { 4 | public static void main(String[] args) { 5 | File file1 = new File("File1.txt"); 6 | File file2 = new File("File2.txt"); 7 | Folder folder = new Folder("Documents"); 8 | folder.addFile(file1); 9 | folder.addFile(file2); 10 | 11 | folder.showDetails(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/CompositePattern/Problem/Folder.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.CompositePattern.Problem; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Folder { 7 | private String name; 8 | private List files = new ArrayList<>(); 9 | 10 | public Folder(String name){ 11 | this.name = name; 12 | } 13 | 14 | public void addFile(File file){ 15 | files.add(file); 16 | } 17 | 18 | public void showDetails(){ 19 | System.out.println("Folder: " + name); 20 | for(File file:files){ 21 | file.showDetails(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/CompositePattern/Solution/File.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.CompositePattern.Solution; 2 | 3 | public class File implements FileSystemComponent { 4 | private String name; 5 | 6 | public File(String name){ 7 | this.name = name; 8 | } 9 | 10 | public void showDetails(){ 11 | System.out.println("File : " +name); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/CompositePattern/Solution/FileSystemApp.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.CompositePattern.Solution; 2 | 3 | public class FileSystemApp { 4 | public static void main(String[] args) { 5 | FileSystemComponent file1 = new File("File1.txt"); 6 | FileSystemComponent file2 = new File("File2.txt"); 7 | Folder folder = new Folder("Documents"); 8 | folder.addComponent(file1); 9 | folder.addComponent(file2); 10 | 11 | //Subfolder 12 | Folder subfolder = new Folder("Subfolder"); 13 | FileSystemComponent file3 = new File("File3.txt"); 14 | 15 | subfolder.addComponent(file3); 16 | folder.addComponent(subfolder); 17 | 18 | folder.showDetails(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/CompositePattern/Solution/FileSystemComponent.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.CompositePattern.Solution; 2 | 3 | public interface FileSystemComponent { 4 | void showDetails(); 5 | } 6 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/CompositePattern/Solution/Folder.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.CompositePattern.Solution; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Folder implements FileSystemComponent{ 7 | private String name; 8 | private List components = new ArrayList<>(); 9 | 10 | public Folder(String name){ 11 | this.name = name; 12 | } 13 | 14 | public void addComponent(FileSystemComponent component){ 15 | components.add(component); 16 | } 17 | 18 | public void showDetails(){ 19 | System.out.println("Folder: " + name); 20 | for(FileSystemComponent component:components){ 21 | component.showDetails(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/DecoratorPattern/Problem/BasicPizza.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Problem; 2 | 3 | public class BasicPizza implements Pizza{ 4 | @Override 5 | public String getDescription() { 6 | return "Basic Pizza"; 7 | 8 | } 9 | 10 | @Override 11 | public double getCost() { 12 | return 5.00; //base cost 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/DecoratorPattern/Problem/CheeseOlivePizza.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Problem; 2 | 3 | public class CheeseOlivePizza extends CheesePizza{ 4 | 5 | @Override 6 | public String getDescription() { 7 | return super.getDescription() + ", Olives"; 8 | } 9 | 10 | @Override 11 | public double getCost() { 12 | return super.getCost() + 0.50; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/DecoratorPattern/Problem/CheesePizza.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Problem; 2 | 3 | public class CheesePizza extends BasicPizza{ 4 | @Override 5 | public String getDescription() { 6 | return super.getDescription() + ", Cheese"; 7 | } 8 | 9 | @Override 10 | public double getCost() { 11 | return super.getCost() + 1.00; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/DecoratorPattern/Problem/Pizza.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Problem; 2 | 3 | public interface Pizza { 4 | String getDescription(); 5 | double getCost(); 6 | } 7 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/DecoratorPattern/Problem/PizzaApp.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Problem; 2 | 3 | public class PizzaApp { 4 | public static void main(String[] args) { 5 | Pizza pizza = new CheeseOlivePizza(); 6 | System.out.println(pizza.getDescription()); 7 | System.out.println(pizza.getCost()); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/DecoratorPattern/Solution/BasicPizza.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Solution; 2 | 3 | public class BasicPizza implements Pizza { 4 | @Override 5 | public String getDescription() { 6 | return "Basic Pizza"; 7 | 8 | } 9 | 10 | @Override 11 | public double getCost() { 12 | return 5.00; //base cost 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/DecoratorPattern/Solution/CheeseDecorator.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Solution; 2 | 3 | public class CheeseDecorator extends PizzaDecorator { 4 | public CheeseDecorator(Pizza pizza){ 5 | super(pizza); 6 | } 7 | 8 | public String getDescription(){ 9 | return decoratedPizza.getDescription() + ", Cheese"; 10 | } 11 | public double getCost(){ 12 | return decoratedPizza.getCost() + 1.00; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/DecoratorPattern/Solution/MushroomDecorator.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Solution; 2 | 3 | public class MushroomDecorator extends PizzaDecorator { 4 | public MushroomDecorator(Pizza pizza){ 5 | super(pizza); 6 | } 7 | 8 | public String getDescription(){ 9 | return decoratedPizza.getDescription() + ", Mushroom"; 10 | } 11 | public double getCost(){ 12 | return decoratedPizza.getCost() + 2.00; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/DecoratorPattern/Solution/OliveDecorator.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Solution; 2 | 3 | public class OliveDecorator extends PizzaDecorator { 4 | public OliveDecorator(Pizza pizza){ 5 | super(pizza); 6 | } 7 | 8 | public String getDescription(){ 9 | return decoratedPizza.getDescription() + ", Olive"; 10 | } 11 | public double getCost(){ 12 | return decoratedPizza.getCost() + 0.50; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/DecoratorPattern/Solution/Pizza.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Solution; 2 | 3 | public interface Pizza { 4 | String getDescription(); 5 | double getCost(); 6 | } 7 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/DecoratorPattern/Solution/PizzaApp.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Solution; 2 | 3 | 4 | 5 | public class PizzaApp { 6 | public static void main(String[] args) { 7 | //Basic Pizza 8 | Pizza pizza = new BasicPizza(); 9 | 10 | //Add Cheese 11 | pizza = new CheeseDecorator(pizza); 12 | pizza = new OliveDecorator(pizza); 13 | pizza = new MushroomDecorator(pizza); 14 | 15 | System.out.println(pizza.getDescription()); 16 | System.out.println(pizza.getCost()); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/DecoratorPattern/Solution/PizzaDecorator.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.DecoratorPattern.Solution; 2 | 3 | abstract class PizzaDecorator implements Pizza{ 4 | protected Pizza decoratedPizza; 5 | 6 | public PizzaDecorator(Pizza pizza){ 7 | this.decoratedPizza = pizza; 8 | } 9 | 10 | @Override 11 | public String getDescription() { 12 | return decoratedPizza.getDescription(); 13 | } 14 | 15 | @Override 16 | public double getCost() { 17 | return decoratedPizza.getCost(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/FacadePattern/Problem/Client.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.FacadePattern.Problem; 2 | 3 | public class Client { 4 | public static void main(String[] args) { 5 | // Client code interacting with different services directly 6 | UserService userService = new UserService(); 7 | OrderService orderService = new OrderService(); 8 | PaymentService paymentService = new PaymentService(); 9 | 10 | //Task 11 | System.out.println(userService.getUserDetails("123")); 12 | System.out.println(orderService.getOrderDetails("456")); 13 | System.out.println(paymentService.processPayment("789")); 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/FacadePattern/Problem/OrderService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.FacadePattern.Problem; 2 | 3 | // Microservice for Order Management 4 | class OrderService { 5 | public String getOrderDetails(String orderId) { 6 | // Simulate fetching order details 7 | return "Order details for orderId: " + orderId; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/FacadePattern/Problem/PaymentService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.FacadePattern.Problem; 2 | 3 | // Microservice for Payment Processing 4 | class PaymentService { 5 | public String processPayment(String paymentId) { 6 | // Simulate payment processing 7 | return "Processing payment with paymentId: " + paymentId; 8 | } 9 | } -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/FacadePattern/Problem/UserService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.FacadePattern.Problem; 2 | 3 | // Microservice for User Management 4 | class UserService { 5 | public String getUserDetails(String userId) { 6 | // Simulate fetching user details 7 | return "User details for userId: " + userId; 8 | } 9 | } -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/FacadePattern/Solution/Client.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.FacadePattern.Solution; 2 | 3 | public class Client { 4 | public static void main(String[] args) { 5 | // Client code interacting with API Gateway (Facade) 6 | APIGateway apiGateway = new APIGateway(); 7 | //Task 8 | System.out.println(apiGateway.getFullOrderDetails("123","456","789")); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/FacadePattern/Solution/OrderService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.FacadePattern.Solution; 2 | 3 | // Microservice for Order Management 4 | class OrderService { 5 | public String getOrderDetails(String orderId) { 6 | // Simulate fetching order details 7 | return "Order details for orderId: " + orderId; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/FacadePattern/Solution/PaymentService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.FacadePattern.Solution; 2 | 3 | // Microservice for Payment Processing 4 | class PaymentService { 5 | public String processPayment(String paymentId) { 6 | // Simulate payment processing 7 | return "Processing payment with paymentId: " + paymentId; 8 | } 9 | } -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/FacadePattern/Solution/UserService.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.FacadePattern.Solution; 2 | 3 | // Microservice for User Management 4 | class UserService { 5 | public String getUserDetails(String userId) { 6 | // Simulate fetching user details 7 | return "User details for userId: " + userId; 8 | } 9 | } -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/FlyWeightPattern/Problem/Bullet.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.FlyWeightPattern.Problem; 2 | 3 | class Bullet { 4 | private String color; // Intrinsic property shared by all bullets 5 | private int x, y; // Extrinsic properties unique to each bullet 6 | private int velocity; 7 | 8 | public Bullet(String color, int x, int y, int velocity) { 9 | this.color = color; // Same for all bullets 10 | this.x = x; 11 | this.y = y; 12 | this.velocity = velocity; 13 | System.out.println("Creating bullet at (" + x + ", " + y + ") with velocity " + velocity); 14 | } 15 | public void display() { 16 | System.out.println("Bullet at (" + x + ", " + y + ") moving at velocity " + velocity); 17 | } 18 | } -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/FlyWeightPattern/Problem/Game.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.FlyWeightPattern.Problem; 2 | 3 | public class Game { 4 | public static void main(String[] args) { 5 | // 5 Red Bullet Objects 6 | for(int i=0;i<5;i++){ 7 | Bullet bullet = new Bullet("Red",i*10,i*12,5); 8 | } 9 | // 5 Green Bullet Objects 10 | for(int i=0;i<5;i++){ 11 | Bullet bullet = new Bullet("Red",i*10,i*12,5); 12 | } 13 | //Problems 14 | // Memory Overhead : Every bullet stores redundant data like Color, Image 15 | // Performance : Slow performance when many bullets are created 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/FlyWeightPattern/Solution/Bullet.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.FlyWeightPattern.Solution; 2 | 3 | class Bullet { 4 | private BulletType type; // Intrinsic property shared by all bullets 5 | private int x, y; // Extrinsic properties unique to each bullet 6 | private int velocity; 7 | 8 | public Bullet(String color, int x, int y, int velocity) { 9 | this.type = BulletTypeFactory.getBulletType(color); 10 | this.x = x; 11 | this.y = y; 12 | this.velocity = velocity; 13 | System.out.println("Creating bullet at (" + x + ", " + y + ") with velocity " + velocity); 14 | } 15 | public void display() { 16 | System.out.println("Bullet at (" + x + ", " + y + ") moving at velocity " + velocity); 17 | } 18 | } -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/FlyWeightPattern/Solution/BulletType.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.FlyWeightPattern.Solution; 2 | 3 | //Flyweight Class 4 | public class BulletType { 5 | private String color; //Intrinsic Property 6 | 7 | public BulletType(String color){ 8 | this.color = color; 9 | System.out.println("Creating bulletType with color " + color); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/FlyWeightPattern/Solution/BulletTypeFactory.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.FlyWeightPattern.Solution; 2 | 3 | import java.util.HashMap; 4 | 5 | public class BulletTypeFactory { 6 | private static final HashMap bulletTypes = new HashMap<>(); 7 | 8 | public static BulletType getBulletType(String color){ 9 | if(!bulletTypes.containsKey(color)){ 10 | bulletTypes.put(color,new BulletType(color)); 11 | } 12 | return bulletTypes.get(color); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/FlyWeightPattern/Solution/Game.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.FlyWeightPattern.Solution; 2 | 3 | public class Game { 4 | public static void main(String[] args) { 5 | // 5 Red Bullet Objects 6 | for(int i=0;i<5;i++){ 7 | Bullet bullet = new Bullet("Red",i*10,i*12,5); 8 | } 9 | // 5 Green Bullet Objects 10 | for(int i=0;i<5;i++){ 11 | Bullet bullet = new Bullet("Red",i*10,i*12,5); 12 | } 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/ProxyPattern/Problem/Client.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.ProxyPattern.Problem; 2 | 3 | public class Client { 4 | public static void main(String[] args) { 5 | Image img1 = new RealImage("dog.png"); 6 | Image img2 = new RealImage("cat.png"); 7 | //Here, the RealImage is loaded every time we create it, 8 | // which can be inefficient if the image is not always required. 9 | img1.display(); 10 | img1.display(); 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/ProxyPattern/Problem/Image.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.ProxyPattern.Problem; 2 | 3 | public interface Image { 4 | void display(); 5 | } 6 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/ProxyPattern/Problem/RealImage.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.ProxyPattern.Problem; 2 | 3 | public class RealImage implements Image{ 4 | private String filename; 5 | public RealImage(String filename){ 6 | this.filename = filename; 7 | loadImageFromDisk(); //Expensive Operation 8 | } 9 | 10 | private void loadImageFromDisk(){ 11 | System.out.println("Loading image from disk " + filename); 12 | } 13 | 14 | @Override 15 | public void display() { 16 | System.out.println("Displaying: " +filename); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/ProxyPattern/Solution/Client.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.ProxyPattern.Solution; 2 | 3 | public class Client { 4 | public static void main(String[] args) { 5 | Image img1 = new ProxyImage("dog.png"); 6 | Image img2 = new ProxyImage("cat.png"); 7 | //The image is loaded lazily when needed, 8 | // saving time and resources if the 9 | // image is never displayed. 10 | img1.display(); 11 | img1.display(); 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/ProxyPattern/Solution/Image.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.ProxyPattern.Solution; 2 | 3 | public interface Image { 4 | void display(); 5 | } 6 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/ProxyPattern/Solution/ProxyImage.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.ProxyPattern.Solution; 2 | 3 | public class ProxyImage implements Image{ 4 | private String filename; 5 | private RealImage realImage;//Proxy reference to real Image 6 | 7 | public ProxyImage(String filename){ 8 | this.filename = filename; 9 | } 10 | @Override 11 | public void display() { 12 | if(realImage==null){ 13 | realImage = new RealImage(filename); //Image is loaded + cached 14 | } 15 | realImage.display(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /design-patterns/src/main/java/org/prateek/StructuralPatterns/ProxyPattern/Solution/RealImage.java: -------------------------------------------------------------------------------- 1 | package org.prateek.StructuralPatterns.ProxyPattern.Solution; 2 | 3 | public class RealImage implements Image { 4 | private String filename; 5 | public RealImage(String filename){ 6 | this.filename = filename; 7 | loadImageFromDisk(); //Expensive Operation 8 | } 9 | 10 | private void loadImageFromDisk(){ 11 | System.out.println("Loading image from disk " + filename); 12 | } 13 | 14 | @Override 15 | public void display() { 16 | System.out.println("Displaying: " +filename); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /solutions/Adapter/LegacyWeatherService.java: -------------------------------------------------------------------------------- 1 | package Adapter; 2 | 3 | public class LegacyWeatherService implements WeatherService { 4 | 5 | private String temperature; 6 | private String condition; 7 | 8 | public LegacyWeatherService(String temperature, String condition) { 9 | this.temperature = temperature; 10 | this.condition = condition; 11 | } 12 | 13 | @Override 14 | public String getWeatherData() { 15 | return "" + temperature + "" + condition + ""; 16 | } 17 | } -------------------------------------------------------------------------------- /solutions/Adapter/NewWeatherService.java: -------------------------------------------------------------------------------- 1 | package Adapter; 2 | 3 | public class NewWeatherService { 4 | 5 | private String temperature; 6 | private String condition; 7 | 8 | public NewWeatherService(String temperature, String condition) { 9 | this.temperature = temperature; 10 | this.condition = condition; 11 | } 12 | 13 | public String fetchWeather() { 14 | return "{\"temperature\": " + temperature + ", \"condition\": \"" + condition + "\"}"; 15 | } 16 | } -------------------------------------------------------------------------------- /solutions/Adapter/NewWeatherServiceAdapter.java: -------------------------------------------------------------------------------- 1 | package Adapter; 2 | 3 | public class NewWeatherServiceAdapter implements WeatherService { 4 | 5 | private NewWeatherService newWeatherService; 6 | 7 | public NewWeatherServiceAdapter(NewWeatherService newWeatherService) { 8 | this.newWeatherService = newWeatherService; 9 | } 10 | 11 | @Override 12 | public String getWeatherData() { 13 | String json = newWeatherService.fetchWeather(); 14 | return json; 15 | } 16 | } -------------------------------------------------------------------------------- /solutions/Adapter/WeatherService.java: -------------------------------------------------------------------------------- 1 | package Adapter; 2 | 3 | public interface WeatherService { 4 | String getWeatherData(); 5 | } -------------------------------------------------------------------------------- /solutions/Builder/MealBuilder.java: -------------------------------------------------------------------------------- 1 | package Builder; 2 | 3 | public class MealBuilder { 4 | 5 | public String mainDish; 6 | public String sideDish; 7 | public String drink; 8 | public String dessert = "Default Dessert"; 9 | public String appetizer = "Default Appetizer"; 10 | 11 | public MealBuilder(String mainDish, String sideDish, String drink) { 12 | this.mainDish = mainDish; 13 | this.sideDish = sideDish; 14 | this.drink = drink; 15 | } 16 | 17 | public MealBuilder setDessert(String dessert) { 18 | this.dessert = dessert; 19 | return this; 20 | } 21 | 22 | public MealBuilder setAppetizer(String appetizer) { 23 | this.appetizer = appetizer; 24 | return this; 25 | } 26 | 27 | public Meal build() { 28 | return Meal.getInstance(this); 29 | } 30 | } -------------------------------------------------------------------------------- /solutions/Command/Command.java: -------------------------------------------------------------------------------- 1 | package Command; 2 | 3 | public interface Command { 4 | void execute(); 5 | } -------------------------------------------------------------------------------- /solutions/Command/Fan.java: -------------------------------------------------------------------------------- 1 | package Command; 2 | 3 | public class Fan { 4 | 5 | public void turnOn() { 6 | System.out.println("The fan is on."); 7 | } 8 | 9 | public void turnOff() { 10 | System.out.println("The fan is off."); 11 | } 12 | } -------------------------------------------------------------------------------- /solutions/Command/FanCommands.java: -------------------------------------------------------------------------------- 1 | package Command; 2 | 3 | public class FanCommands { 4 | 5 | public static class FanOnCommand implements Command { 6 | 7 | private Fan fan; 8 | 9 | public FanOnCommand(Fan fan) { 10 | this.fan = fan; 11 | } 12 | 13 | @Override 14 | public void execute() { 15 | fan.turnOn(); 16 | } 17 | } 18 | 19 | public static class FanOffCommand implements Command { 20 | 21 | private Fan fan; 22 | 23 | public FanOffCommand(Fan fan) { 24 | this.fan = fan; 25 | } 26 | 27 | @Override 28 | public void execute() { 29 | fan.turnOff(); 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /solutions/Command/Light.java: -------------------------------------------------------------------------------- 1 | package Command; 2 | 3 | public class Light { 4 | 5 | public void turnOn() { 6 | System.out.println("The light is on."); 7 | } 8 | 9 | public void turnOff() { 10 | System.out.println("The light is off."); 11 | } 12 | } -------------------------------------------------------------------------------- /solutions/Command/LightCommands.java: -------------------------------------------------------------------------------- 1 | package Command; 2 | 3 | public class LightCommands { 4 | 5 | public static class LightOnCommand implements Command { 6 | 7 | private Light light; 8 | 9 | public LightOnCommand(Light light) { 10 | this.light = light; 11 | } 12 | 13 | @Override 14 | public void execute() { 15 | light.turnOn(); 16 | } 17 | } 18 | 19 | public static class LightOffCommand implements Command { 20 | 21 | private Light light; 22 | 23 | public LightOffCommand(Light light) { 24 | this.light = light; 25 | } 26 | 27 | @Override 28 | public void execute() { 29 | light.turnOff(); 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /solutions/Composite/MenuComponent.java: -------------------------------------------------------------------------------- 1 | package Composite; 2 | 3 | public interface MenuComponent { 4 | void print(); 5 | } -------------------------------------------------------------------------------- /solutions/Composite/MenuItem.java: -------------------------------------------------------------------------------- 1 | package Composite; 2 | 3 | public class MenuItem implements MenuComponent { 4 | private String name; 5 | private String description; 6 | private double price; 7 | 8 | public MenuItem(String name, String description, double price) { 9 | this.name = name; 10 | this.description = description; 11 | this.price = price; 12 | } 13 | 14 | @Override 15 | public void print() { 16 | System.out.printf("Item: %s\nDescription: %s\nPrice: $%.2f\n", name, description, price); 17 | } 18 | } -------------------------------------------------------------------------------- /solutions/Composite/MenuSection.java: -------------------------------------------------------------------------------- 1 | package Composite; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class MenuSection implements MenuComponent { 7 | private String sectionName; 8 | private List menuComponents; 9 | 10 | public MenuSection(String sectionName) { 11 | this.sectionName = sectionName; 12 | this.menuComponents = new ArrayList<>(); 13 | } 14 | 15 | public void add(MenuComponent menuComponent) { 16 | menuComponents.add(menuComponent); 17 | } 18 | 19 | @Override 20 | public void print() { 21 | System.out.println("Section: " + sectionName); 22 | for (MenuComponent menuComponent : menuComponents) { 23 | menuComponent.print(); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /solutions/Decorator/BasicCoffee.java: -------------------------------------------------------------------------------- 1 | package Decorator; 2 | 3 | public class BasicCoffee implements Coffee { 4 | 5 | @Override 6 | public String getDescription() { 7 | return "Basic Coffee"; 8 | } 9 | 10 | @Override 11 | public double getCost() { 12 | return 3.00; 13 | } 14 | } -------------------------------------------------------------------------------- /solutions/Decorator/Coffee.java: -------------------------------------------------------------------------------- 1 | package Decorator; 2 | 3 | public interface Coffee { 4 | String getDescription(); 5 | double getCost(); 6 | } -------------------------------------------------------------------------------- /solutions/Decorator/CoffeeDecorator.java: -------------------------------------------------------------------------------- 1 | package Decorator; 2 | 3 | public abstract class CoffeeDecorator implements Coffee { 4 | protected Coffee coffee; 5 | 6 | public CoffeeDecorator(Coffee coffee) { 7 | this.coffee = coffee; 8 | } 9 | 10 | @Override 11 | public String getDescription() { 12 | return coffee.getDescription(); 13 | } 14 | 15 | @Override 16 | public double getCost() { 17 | return coffee.getCost(); 18 | } 19 | } -------------------------------------------------------------------------------- /solutions/Decorator/Milk.java: -------------------------------------------------------------------------------- 1 | package Decorator; 2 | 3 | public class Milk extends CoffeeDecorator { 4 | 5 | public Milk(Coffee coffee) { 6 | super(coffee); 7 | } 8 | 9 | @Override 10 | public String getDescription() { 11 | return coffee.getDescription() + ", Milk"; 12 | } 13 | 14 | @Override 15 | public double getCost() { 16 | return coffee.getCost() + 0.50; 17 | } 18 | } -------------------------------------------------------------------------------- /solutions/Decorator/Sugar.java: -------------------------------------------------------------------------------- 1 | package Decorator; 2 | 3 | public class Sugar extends CoffeeDecorator { 4 | 5 | public Sugar(Coffee coffee) { 6 | super(coffee); 7 | } 8 | 9 | @Override 10 | public String getDescription() { 11 | return coffee.getDescription() + ", Sugar"; 12 | } 13 | 14 | @Override 15 | public double getCost() { 16 | return coffee.getCost() + 0.30; 17 | } 18 | } -------------------------------------------------------------------------------- /solutions/Decorator/WhippedCream.java: -------------------------------------------------------------------------------- 1 | package Decorator; 2 | 3 | public class WhippedCream extends CoffeeDecorator { 4 | 5 | public WhippedCream(Coffee coffee) { 6 | super(coffee); 7 | } 8 | 9 | @Override 10 | public String getDescription() { 11 | return coffee.getDescription() + ", Whipped Cream"; 12 | } 13 | 14 | @Override 15 | public double getCost() { 16 | return coffee.getCost() + 0.70; 17 | } 18 | } -------------------------------------------------------------------------------- /solutions/Facade/DVDPlayer.java: -------------------------------------------------------------------------------- 1 | package Facade; 2 | 3 | public class DVDPlayer { 4 | 5 | public void play() { 6 | System.out.println("DVD Player: Playing the movie"); 7 | } 8 | 9 | public void pause() { 10 | System.out.println("DVD Player: Paused the movie"); 11 | } 12 | 13 | public void stop() { 14 | System.out.println("DVD Player: Stopped the movie"); 15 | } 16 | } -------------------------------------------------------------------------------- /solutions/Facade/Exercise.java: -------------------------------------------------------------------------------- 1 | package Facade; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Exercise { 6 | 7 | public void run() { 8 | 9 | Scanner sc = new Scanner(System.in); 10 | HomeTheaterFacade homeTheater = new HomeTheaterFacade(); 11 | 12 | int dimmingPercentage = sc.nextInt(); 13 | 14 | int volumeLevel = sc.nextInt(); 15 | 16 | homeTheater.watchMovie(dimmingPercentage, volumeLevel); 17 | 18 | sc.close(); 19 | } 20 | } -------------------------------------------------------------------------------- /solutions/Facade/LightingControl.java: -------------------------------------------------------------------------------- 1 | package Facade; 2 | 3 | public class LightingControl { 4 | 5 | public void dim(int level) { 6 | System.out.println("Lighting Control: Dimming lights to " + level + "%"); 7 | } 8 | 9 | public void on() { 10 | System.out.println("Lighting Control: Lights are on"); 11 | } 12 | 13 | public void off() { 14 | System.out.println("Lighting Control: Lights are off"); 15 | } 16 | } -------------------------------------------------------------------------------- /solutions/Facade/Projector.java: -------------------------------------------------------------------------------- 1 | package Facade; 2 | 3 | public class Projector { 4 | 5 | public void on() { 6 | System.out.println("Projector: Turned on"); 7 | } 8 | 9 | public void off() { 10 | System.out.println("Projector: Turned off"); 11 | } 12 | 13 | public void setInput() { 14 | System.out.println("Projector: Input set to DVD"); 15 | } 16 | } -------------------------------------------------------------------------------- /solutions/Facade/SoundSystem.java: -------------------------------------------------------------------------------- 1 | package Facade; 2 | 3 | public class SoundSystem { 4 | 5 | public void on() { 6 | System.out.println("Sound System: Turned on"); 7 | } 8 | 9 | public void off() { 10 | System.out.println("Sound System: Turned off"); 11 | } 12 | 13 | public void setVolume(int level) { 14 | System.out.println("Sound System: Volume set to " + level); 15 | } 16 | } -------------------------------------------------------------------------------- /solutions/Factory/Document.java: -------------------------------------------------------------------------------- 1 | package Factory; 2 | 3 | public abstract class Document { 4 | public abstract void displayType(); 5 | } -------------------------------------------------------------------------------- /solutions/Factory/DocumentFactory.java: -------------------------------------------------------------------------------- 1 | package Factory; 2 | 3 | public class DocumentFactory { 4 | 5 | public static Document createDocument(String type) { 6 | 7 | switch (type.toLowerCase()) { 8 | case "pdf": 9 | return new PDFDocument(); 10 | case "word": 11 | return new WordDocument(); 12 | case "html": 13 | return new HTMLDocument(); 14 | default: 15 | throw new IllegalArgumentException("Unknown document type: " + type); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /solutions/Factory/Exercise.java: -------------------------------------------------------------------------------- 1 | package Factory; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Exercise { 6 | 7 | public void run() { 8 | 9 | Scanner sc = new Scanner(System.in); 10 | 11 | String documentType = sc.nextLine(); 12 | 13 | try { 14 | Document document = DocumentFactory.createDocument(documentType); 15 | document.displayType(); 16 | } catch (IllegalArgumentException e) { 17 | System.out.println(e.getMessage()); 18 | } 19 | 20 | sc.close(); 21 | } 22 | } -------------------------------------------------------------------------------- /solutions/Factory/HTMLDocument.java: -------------------------------------------------------------------------------- 1 | package Factory; 2 | 3 | public class HTMLDocument extends Document { 4 | 5 | @Override 6 | public void displayType() { 7 | System.out.println("Creating an HTML Document"); 8 | } 9 | } -------------------------------------------------------------------------------- /solutions/Factory/PDFDocument.java: -------------------------------------------------------------------------------- 1 | package Factory; 2 | 3 | public class PDFDocument extends Document { 4 | 5 | @Override 6 | public void displayType() { 7 | System.out.println("Creating a PDF Document"); 8 | } 9 | } -------------------------------------------------------------------------------- /solutions/Factory/WordDocument.java: -------------------------------------------------------------------------------- 1 | package Factory; 2 | 3 | public class WordDocument extends Document { 4 | 5 | @Override 6 | public void displayType() { 7 | System.out.println("Creating a Word Document"); 8 | } 9 | } -------------------------------------------------------------------------------- /solutions/Flyweight/CharacterFactory.java: -------------------------------------------------------------------------------- 1 | package Flyweight; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class CharacterFactory { 7 | private final Map characters = new HashMap<>(); 8 | 9 | public CharacterFlyweight getCharacter(String fontStyle, int fontSize, String color) { 10 | String key = fontStyle + fontSize + color; 11 | 12 | if (!characters.containsKey(key)) { 13 | System.out.println("Creating new character: " + fontStyle + " " + fontSize + " " + color); 14 | characters.put(key, new ConcreteCharacter(fontStyle, fontSize, color)); 15 | } else { 16 | System.out.println("Reusing character: " + fontStyle + " " + fontSize + " " + color); 17 | } 18 | 19 | return characters.get(key); 20 | } 21 | } -------------------------------------------------------------------------------- /solutions/Flyweight/CharacterFlyweight.java: -------------------------------------------------------------------------------- 1 | package Flyweight; 2 | 3 | interface CharacterFlyweight { 4 | void display(String character); 5 | } -------------------------------------------------------------------------------- /solutions/Flyweight/ConcreteCharacter.java: -------------------------------------------------------------------------------- 1 | package Flyweight; 2 | 3 | public class ConcreteCharacter implements CharacterFlyweight { 4 | private final String fontStyle; 5 | private final int fontSize; 6 | private final String color; 7 | 8 | public ConcreteCharacter(String fontStyle, int fontSize, String color) { 9 | this.fontStyle = fontStyle; 10 | this.fontSize = fontSize; 11 | this.color = color; 12 | } 13 | 14 | @Override 15 | public void display(String character) { 16 | System.out.printf("Character: %s, Font Style: %s, Font Size: %d, Color: %s%n", 17 | character, fontStyle, fontSize, color); 18 | } 19 | } -------------------------------------------------------------------------------- /solutions/Flyweight/Document.java: -------------------------------------------------------------------------------- 1 | package Flyweight; 2 | 3 | public class Document { 4 | private final StringBuilder content = new StringBuilder(); 5 | private final CharacterFactory characterFactory = new CharacterFactory(); 6 | 7 | public void addCharacter(String character, String fontStyle, int fontSize, String color) { 8 | CharacterFlyweight characterFlyweight = characterFactory.getCharacter(fontStyle, fontSize, color); 9 | content.append(character); 10 | characterFlyweight.display(character); 11 | } 12 | 13 | public void render() { 14 | System.out.println("Document Content: " + content.toString()); 15 | } 16 | } -------------------------------------------------------------------------------- /solutions/Flyweight/Exercise.java: -------------------------------------------------------------------------------- 1 | package Flyweight; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Exercise { 6 | 7 | public void run() { 8 | 9 | Scanner sc = new Scanner(System.in); 10 | Document doc = new Document(); 11 | 12 | int numberOfCharacters = sc.nextInt(); 13 | sc.nextLine(); 14 | 15 | for (int i = 0; i < numberOfCharacters; i++) { 16 | String character = sc.nextLine(); 17 | String fontStyle = sc.nextLine(); 18 | String color = sc.nextLine(); 19 | int fontSize = sc.nextInt(); 20 | sc.nextLine(); 21 | 22 | doc.addCharacter(character, fontStyle, fontSize, color); 23 | } 24 | 25 | doc.render(); 26 | 27 | sc.close(); 28 | } 29 | } -------------------------------------------------------------------------------- /solutions/Iterator/Notification.java: -------------------------------------------------------------------------------- 1 | package Iterator; 2 | 3 | public class Notification { 4 | private String message; 5 | 6 | public Notification(String message) { 7 | this.message = message; 8 | } 9 | 10 | public String getMessage() { 11 | return message; 12 | } 13 | } -------------------------------------------------------------------------------- /solutions/Iterator/NotificationCollection.java: -------------------------------------------------------------------------------- 1 | package Iterator; 2 | 3 | import java.util.Iterator; 4 | 5 | public interface NotificationCollection { 6 | public Iterator createIterator(); 7 | } -------------------------------------------------------------------------------- /solutions/Mediator/Airplane.java: -------------------------------------------------------------------------------- 1 | package Mediator; 2 | 3 | public class Airplane { 4 | private String id; 5 | private Mediator mediator; 6 | 7 | public Airplane(String id) { 8 | this.id = id; 9 | } 10 | 11 | public void setMediator(Mediator mediator) { 12 | this.mediator = mediator; 13 | } 14 | 15 | public void requestTakeoff() { 16 | System.out.println("Airplane " + id + " requesting takeoff"); 17 | mediator.handleTakeoffRequest(this); 18 | } 19 | 20 | public void requestLanding() { 21 | System.out.println("Airplane " + id + " requesting landing"); 22 | mediator.handleLandingRequest(this); 23 | } 24 | 25 | public void receiveNotification(String message) { 26 | System.out.println("Airplane " + id + ": " + message); 27 | } 28 | 29 | public String getId() { 30 | return id; 31 | } 32 | } -------------------------------------------------------------------------------- /solutions/Mediator/Mediator.java: -------------------------------------------------------------------------------- 1 | package Mediator; 2 | 3 | public interface Mediator { 4 | void registerAirplane(Airplane airplane); 5 | void handleTakeoffRequest(Airplane airplane); 6 | void handleLandingRequest(Airplane airplane); 7 | } -------------------------------------------------------------------------------- /solutions/Memento/Caretaker.java: -------------------------------------------------------------------------------- 1 | package Memento; 2 | 3 | import java.util.Stack; 4 | 5 | public class Caretaker { 6 | 7 | private final Stack history = new Stack<>(); 8 | 9 | public void saveState(GraphicEditor graphicEditor) { 10 | history.push(graphicEditor.save()); 11 | } 12 | 13 | public void undo(GraphicEditor graphicEditor){ 14 | if(!history.empty()){ 15 | history.pop(); 16 | graphicEditor.restore(history.peek()); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /solutions/Memento/EditorMemento.java: -------------------------------------------------------------------------------- 1 | package Memento; 2 | 3 | public class EditorMemento { 4 | 5 | private final String shapeType; 6 | private final int x; 7 | private final int y; 8 | private final String color; 9 | private final int size; 10 | 11 | public EditorMemento(String shapeType, int x, int y, String color, int size) { 12 | this.shapeType = shapeType; 13 | this.x = x; 14 | this.y = y; 15 | this.color = color; 16 | this.size = size; 17 | } 18 | 19 | public String getShapeType() { 20 | return shapeType; 21 | } 22 | 23 | public int getX() { 24 | return x; 25 | } 26 | 27 | public int getY() { 28 | return y; 29 | } 30 | 31 | public String getColor() { 32 | return color; 33 | } 34 | 35 | public int getSize() { 36 | return size; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /solutions/Observer/InvestorA.java: -------------------------------------------------------------------------------- 1 | package Observer; 2 | 3 | public class InvestorA implements Observer { 4 | 5 | @Override 6 | public void update(String stockSymbol, double newPrice) { 7 | System.out.println("Investor A notified: Stock " + stockSymbol + " has a new price: $" + newPrice); 8 | } 9 | } -------------------------------------------------------------------------------- /solutions/Observer/InvestorB.java: -------------------------------------------------------------------------------- 1 | package Observer; 2 | 3 | public class InvestorB implements Observer { 4 | 5 | @Override 6 | public void update(String stockSymbol, double newPrice) { 7 | System.out.println("Investor B notified: Stock " + stockSymbol + " has a new price: $" + newPrice); 8 | } 9 | } -------------------------------------------------------------------------------- /solutions/Observer/Observer.java: -------------------------------------------------------------------------------- 1 | package Observer; 2 | 3 | public interface Observer { 4 | void update(String stockSymbol, double newPrice); 5 | } -------------------------------------------------------------------------------- /solutions/Observer/Subject.java: -------------------------------------------------------------------------------- 1 | package Observer; 2 | 3 | public interface Subject { 4 | void registerObserver(Observer o); 5 | void removeObserver(Observer o); 6 | void notifyObservers(String stockSymbol, double newPrice); 7 | } -------------------------------------------------------------------------------- /solutions/Prototype/Character.java: -------------------------------------------------------------------------------- 1 | package Prototype; 2 | 3 | public interface Character { 4 | Character clone(); 5 | void displayAttributes(); 6 | } -------------------------------------------------------------------------------- /solutions/Proxy/Exercise.java: -------------------------------------------------------------------------------- 1 | package Proxy; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Exercise { 6 | 7 | public void run() { 8 | 9 | NetworkService networkService = new NetworkServiceProxy(); 10 | Scanner sc = new Scanner(System.in); 11 | 12 | String userInput = sc.nextLine(); 13 | 14 | // First call: should fetch from the remote server 15 | String firstFetch = networkService.fetchData(userInput); 16 | System.out.println(firstFetch); 17 | 18 | // Second call: should retrieve from the cache 19 | String secondFetch = networkService.fetchData(userInput); 20 | System.out.println(secondFetch); 21 | 22 | sc.close(); 23 | } 24 | } -------------------------------------------------------------------------------- /solutions/Proxy/NetworkService.java: -------------------------------------------------------------------------------- 1 | package Proxy; 2 | 3 | public interface NetworkService { 4 | String fetchData(String input); 5 | } -------------------------------------------------------------------------------- /solutions/Proxy/RealNetworkService.java: -------------------------------------------------------------------------------- 1 | package Proxy; 2 | 3 | public class RealNetworkService implements NetworkService { 4 | 5 | private String data; 6 | 7 | @Override 8 | public String fetchData(String input) { 9 | data = "Data fetched from remote server for input: " + input; 10 | return data; 11 | } 12 | } -------------------------------------------------------------------------------- /solutions/Singleton/Exercise.java: -------------------------------------------------------------------------------- 1 | package Singleton; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Exercise { 6 | 7 | public void run() { 8 | 9 | Logger logger = Logger.getInstance(); 10 | Scanner sc = new Scanner(System.in); 11 | 12 | // Get an info message from the user 13 | System.out.print("Enter an info message: "); 14 | String infoMessage = sc.nextLine(); 15 | logger.info(infoMessage); 16 | 17 | // Get a warning message from the user 18 | System.out.print("Enter a warning message: "); 19 | String warnMessage = sc.nextLine(); 20 | logger.warn(warnMessage); 21 | 22 | // Get an error message from the user 23 | System.out.print("Enter an error message: "); 24 | String errorMessage = sc.nextLine(); 25 | logger.error(errorMessage); 26 | 27 | sc.close(); 28 | } 29 | } -------------------------------------------------------------------------------- /solutions/State/MediaPlayer.java: -------------------------------------------------------------------------------- 1 | package State; 2 | 3 | public class MediaPlayer { 4 | 5 | private State state; 6 | 7 | public MediaPlayer() { 8 | // Initial state is playing 9 | state = new PlayingState(); 10 | } 11 | 12 | public void setState(State state) { 13 | this.state = state; 14 | } 15 | 16 | public void play() { 17 | state.pressPlay(); 18 | } 19 | 20 | public void stop() { 21 | state.pressStop(); 22 | } 23 | 24 | public void pause() { 25 | state.pressPause(); 26 | } 27 | 28 | public void displayState() { 29 | state.display(); 30 | } 31 | } -------------------------------------------------------------------------------- /solutions/State/PausedState.java: -------------------------------------------------------------------------------- 1 | package State; 2 | 3 | public class PausedState implements State { 4 | 5 | @Override 6 | public void pressPlay() { 7 | System.out.println("Resuming playback"); 8 | } 9 | 10 | @Override 11 | public void pressStop() { 12 | System.out.println("Stopping playback from pause"); 13 | } 14 | 15 | @Override 16 | public void pressPause() { 17 | System.out.println("Pausing playback"); 18 | } 19 | 20 | @Override 21 | public void display() { 22 | System.out.println("Current State: Paused"); 23 | } 24 | } -------------------------------------------------------------------------------- /solutions/State/PlayingState.java: -------------------------------------------------------------------------------- 1 | package State; 2 | 3 | public class PlayingState implements State { 4 | 5 | @Override 6 | public void pressPlay() { 7 | System.out.println("Starting playback"); 8 | } 9 | 10 | @Override 11 | public void pressStop() { 12 | System.out.println("Stopping playback"); 13 | } 14 | 15 | @Override 16 | public void pressPause() { 17 | System.out.println("Pausing playback"); 18 | } 19 | 20 | @Override 21 | public void display() { 22 | System.out.println("Current State: Playing"); 23 | } 24 | } -------------------------------------------------------------------------------- /solutions/State/State.java: -------------------------------------------------------------------------------- 1 | package State; 2 | 3 | public interface State { 4 | void pressPlay(); 5 | void pressStop(); 6 | void pressPause(); 7 | void display(); 8 | } -------------------------------------------------------------------------------- /solutions/State/StoppedState.java: -------------------------------------------------------------------------------- 1 | package State; 2 | 3 | public class StoppedState implements State { 4 | 5 | @Override 6 | public void pressPlay() { 7 | System.out.println("Starting playback"); 8 | } 9 | 10 | @Override 11 | public void pressStop() { 12 | System.out.println("Stopping playback"); 13 | } 14 | 15 | @Override 16 | public void pressPause() { 17 | System.out.println("Can't pause. Media is already stopped"); 18 | } 19 | 20 | @Override 21 | public void display() { 22 | System.out.println("Current State: Stopped"); 23 | } 24 | } -------------------------------------------------------------------------------- /solutions/Strategy/Document.java: -------------------------------------------------------------------------------- 1 | package Strategy; 2 | 3 | public class Document { 4 | 5 | private String content; 6 | private TextFormatter formatter; 7 | 8 | public void setContent(String content) { 9 | this.content = content; 10 | } 11 | 12 | public void setFormatter(TextFormatter formatter) { 13 | this.formatter = formatter; 14 | } 15 | 16 | public void display() { 17 | System.out.println(formatter.format(content)); 18 | } 19 | } -------------------------------------------------------------------------------- /solutions/Strategy/HTMLFormatter.java: -------------------------------------------------------------------------------- 1 | package Strategy; 2 | 3 | public class HTMLFormatter implements TextFormatter { 4 | 5 | @Override 6 | public String format(String text) { 7 | return "" + text + ""; // Wraps content in HTML tags 8 | } 9 | } -------------------------------------------------------------------------------- /solutions/Strategy/MarkdownFormatter.java: -------------------------------------------------------------------------------- 1 | package Strategy; 2 | 3 | public class MarkdownFormatter implements TextFormatter { 4 | 5 | @Override 6 | public String format(String text) { 7 | return "**" + text + "**"; // For simplicity, wraps content in Markdown bold syntax 8 | } 9 | } -------------------------------------------------------------------------------- /solutions/Strategy/PlainTextFormatter.java: -------------------------------------------------------------------------------- 1 | package Strategy; 2 | 3 | public class PlainTextFormatter implements TextFormatter { 4 | 5 | @Override 6 | public String format(String text) { 7 | return text; // Returns plain text as-is 8 | } 9 | } -------------------------------------------------------------------------------- /solutions/Strategy/TextFormatter.java: -------------------------------------------------------------------------------- 1 | package Strategy; 2 | 3 | public interface TextFormatter { 4 | String format(String text); 5 | } -------------------------------------------------------------------------------- /solutions/Template/EmployeeReport.java: -------------------------------------------------------------------------------- 1 | package Template; 2 | 3 | import java.util.Scanner; 4 | 5 | public class EmployeeReport extends ReportTemplate { 6 | 7 | private Scanner sc; 8 | 9 | public EmployeeReport(Scanner sc) { 10 | this.sc = sc; 11 | } 12 | 13 | @Override 14 | protected void gatherData() { 15 | String gatherData = sc.nextLine(); 16 | System.out.println(gatherData); 17 | } 18 | 19 | @Override 20 | protected void processData() { 21 | String processData = sc.nextLine(); 22 | System.out.println(processData); 23 | } 24 | } -------------------------------------------------------------------------------- /solutions/Template/InventoryReport.java: -------------------------------------------------------------------------------- 1 | package Template; 2 | 3 | import java.util.Scanner; 4 | 5 | public class InventoryReport extends ReportTemplate { 6 | 7 | private Scanner sc; 8 | 9 | public InventoryReport(Scanner sc) { 10 | this.sc = sc; 11 | } 12 | 13 | @Override 14 | protected void gatherData() { 15 | String gatherData = sc.nextLine(); 16 | System.out.println(gatherData); 17 | } 18 | 19 | @Override 20 | protected void processData() { 21 | String processData = sc.nextLine(); 22 | System.out.println(processData); 23 | } 24 | } -------------------------------------------------------------------------------- /solutions/Template/SalesReport.java: -------------------------------------------------------------------------------- 1 | package Template; 2 | 3 | import java.util.Scanner; 4 | 5 | public class SalesReport extends ReportTemplate { 6 | 7 | private Scanner sc; 8 | 9 | public SalesReport(Scanner sc) { 10 | this.sc = sc; 11 | } 12 | 13 | @Override 14 | protected void gatherData() { 15 | String gatherData = sc.nextLine(); 16 | System.out.println(gatherData); 17 | } 18 | 19 | @Override 20 | protected void processData() { 21 | String processData = sc.nextLine(); 22 | System.out.println(processData); 23 | } 24 | } --------------------------------------------------------------------------------