├── .gitignore ├── ChainOfResponsibility └── ChainOfResponsibility │ ├── .gitignore │ ├── build.gradle │ ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ ├── settings.gradle │ └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── dailycodebuffer │ │ │ └── chainofresponsibility │ │ │ ├── BankPaymentHandler.java │ │ │ ├── ChainOfResponsibilityApplication.java │ │ │ ├── CreditCardPaymentHandler.java │ │ │ ├── PayPalPaymentHandler.java │ │ │ └── PaymentHandler.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── dailycodebuffer │ └── chainofresponsibility │ └── ChainOfResponsibilityApplicationTests.java ├── README.md ├── abstract_factory ├── .gradle │ ├── 7.1 │ │ ├── dependencies-accessors │ │ │ ├── dependencies-accessors.lock │ │ │ └── gc.properties │ │ ├── executionHistory │ │ │ ├── executionHistory.bin │ │ │ └── executionHistory.lock │ │ ├── fileChanges │ │ │ └── last-build.bin │ │ ├── fileHashes │ │ │ ├── fileHashes.bin │ │ │ └── fileHashes.lock │ │ └── gc.properties │ ├── buildOutputCleanup │ │ ├── buildOutputCleanup.lock │ │ ├── cache.properties │ │ └── outputFiles.bin │ ├── checksums │ │ └── checksums.lock │ └── vcs-1 │ │ └── gc.properties ├── build.gradle ├── gradle │ └── wrapper │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ └── main │ └── java │ └── demo │ └── component │ ├── Application.java │ ├── Button.java │ ├── CheckBox.java │ ├── Main.java │ ├── os │ ├── mac │ │ ├── MacButton.java │ │ └── MacCheckBox.java │ └── win │ │ ├── WinButton.java │ │ └── WinCheckBox.java │ └── uifactory │ ├── MacUIFactory.java │ ├── UIFactory.java │ └── WinUIFactory.java ├── adapter ├── gradle │ └── wrapper │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ └── main │ └── java │ ├── FoodItem.java │ ├── GroceryItem.java │ ├── GroceryItemAdapter.java │ ├── GroceryProduct.java │ ├── Item.java │ ├── Main.java │ └── SwiggyStore.java ├── bridge ├── build.gradle ├── gradle │ └── wrapper │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ └── main │ └── java │ ├── HDProcessor.java │ ├── Main.java │ ├── NetflixVideo.java │ ├── UHD4KProcessor.java │ ├── Video.java │ ├── VideoProcessor.java │ └── YoutubeVideo.java ├── builder ├── build.gradle ├── gradle │ └── wrapper │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ └── main │ └── java │ ├── Burger.java │ ├── Main.java │ ├── Meal.java │ ├── MealBuilder.java │ ├── MealDirector.java │ ├── NonVegMealBuilder.java │ └── VegMealBuilder.java ├── command ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── dailycodebuffer │ │ │ └── command │ │ │ ├── CommandApplication.java │ │ │ ├── OpenTextFileOperation.java │ │ │ ├── SaveTextFileOperation.java │ │ │ ├── TextFile.java │ │ │ ├── TextFileOperation.java │ │ │ └── TextFileOperationExecutor.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── dailycodebuffer │ └── command │ └── CommandApplicationTests.java ├── composite ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── dailycodebuffer │ │ │ └── composite │ │ │ ├── CompositeApplication.java │ │ │ ├── Department.java │ │ │ ├── FinancialDepartment.java │ │ │ ├── HeadDepartment.java │ │ │ └── SalesDepartment.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── dailycodebuffer │ └── composite │ └── CompositeApplicationTests.java ├── decorator ├── build.gradle ├── gradle │ └── wrapper │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ └── main │ └── java │ ├── BasePizza.java │ ├── CheeseBurstDecorator.java │ ├── JalepanoDecorator.java │ ├── Main.java │ ├── Pizza.java │ └── PizzaDecorator.java ├── facade ├── build.gradle ├── gradle │ └── wrapper │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ └── main │ └── java │ ├── DeliveryBoy.java │ ├── DeliveryTeam.java │ ├── Main.java │ ├── Restaurant.java │ └── ZomatoFacade.java ├── factory ├── .gradle │ ├── 7.1 │ │ ├── dependencies-accessors │ │ │ ├── dependencies-accessors.lock │ │ │ └── gc.properties │ │ ├── executionHistory │ │ │ ├── executionHistory.bin │ │ │ └── executionHistory.lock │ │ ├── fileChanges │ │ │ └── last-build.bin │ │ ├── fileHashes │ │ │ ├── fileHashes.bin │ │ │ └── fileHashes.lock │ │ └── gc.properties │ ├── buildOutputCleanup │ │ ├── buildOutputCleanup.lock │ │ ├── cache.properties │ │ └── outputFiles.bin │ ├── checksums │ │ └── checksums.lock │ └── vcs-1 │ │ └── gc.properties ├── build.gradle ├── gradle │ └── wrapper │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ └── main │ └── java │ ├── OperatingSystemFactory.java │ └── factories │ ├── LinuxOperatingSystem.java │ ├── OperatingSystem.java │ └── WindowsOperatingSysten.java ├── flyweight ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── dailycodebuffer │ │ │ └── flyweight │ │ │ ├── DrawingClient.java │ │ │ ├── Line.java │ │ │ ├── Oval.java │ │ │ ├── Shape.java │ │ │ └── ShapeFactory.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── dailycodebuffer │ └── flyweight │ └── FlyweightApplicationTests.java ├── interpreter ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── dailycodebuffer │ │ │ └── interpreter │ │ │ ├── AndExpression.java │ │ │ ├── Expression.java │ │ │ ├── InterpreterApplication.java │ │ │ ├── OrExpression.java │ │ │ └── TerminalExpression.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── dailycodebuffer │ └── interpreter │ └── InterpreterApplicationTests.java ├── mediator ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── dailycodebuffer │ │ │ └── mediator │ │ │ ├── ChatMediator.java │ │ │ ├── ChatMediatorImpl.java │ │ │ ├── MediatorApplication.java │ │ │ ├── User.java │ │ │ └── UserImpl.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── dailycodebuffer │ └── mediator │ └── MediatorApplicationTests.java ├── memento ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── dailycodebuffer │ │ │ └── memento │ │ │ ├── CareTaker.java │ │ │ ├── Memento.java │ │ │ ├── MementoApplication.java │ │ │ └── Originator.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── dailycodebuffer │ └── memento │ └── MementoApplicationTests.java ├── observer ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── dailycodebuffer │ │ │ └── observer │ │ │ ├── Channel.java │ │ │ ├── NewsAgency.java │ │ │ ├── NewsChannel.java │ │ │ └── ObserverApplication.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── dailycodebuffer │ └── observer │ └── ObserverApplicationTests.java ├── prototype ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ └── main │ └── java │ ├── FourWheelerVehicle.java │ ├── Main.java │ ├── TwoWheelerVehicle.java │ ├── Vehicle.java │ └── VehicleRegistry.java ├── proxy ├── build.gradle ├── gradle │ └── wrapper │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ └── main │ └── java │ ├── ATM.java │ ├── Account.java │ ├── BankAccount.java │ └── Main.java ├── singleton ├── .gradle │ ├── 7.1 │ │ ├── dependencies-accessors │ │ │ ├── dependencies-accessors.lock │ │ │ └── gc.properties │ │ ├── executionHistory │ │ │ ├── executionHistory.bin │ │ │ └── executionHistory.lock │ │ ├── fileChanges │ │ │ └── last-build.bin │ │ ├── fileHashes │ │ │ ├── fileHashes.bin │ │ │ └── fileHashes.lock │ │ └── gc.properties │ ├── buildOutputCleanup │ │ ├── buildOutputCleanup.lock │ │ ├── cache.properties │ │ └── outputFiles.bin │ ├── checksums │ │ └── checksums.lock │ └── vcs-1 │ │ └── gc.properties ├── build.gradle ├── build │ └── tmp │ │ └── compileJava │ │ └── previous-compilation-data.bin ├── gradle │ └── wrapper │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ └── main │ └── java │ ├── EagerSingleton.java │ ├── EnumSingleton.java │ ├── LazySingleton.java │ ├── Main.java │ ├── MultithreadSingleton.java │ └── SerializableSingleton.java ├── solid_principles ├── .gradle │ ├── 7.1 │ │ ├── dependencies-accessors │ │ │ ├── dependencies-accessors.lock │ │ │ └── gc.properties │ │ ├── executionHistory │ │ │ ├── executionHistory.bin │ │ │ └── executionHistory.lock │ │ ├── fileChanges │ │ │ └── last-build.bin │ │ ├── fileHashes │ │ │ ├── fileHashes.bin │ │ │ └── fileHashes.lock │ │ └── gc.properties │ ├── buildOutputCleanup │ │ ├── buildOutputCleanup.lock │ │ ├── cache.properties │ │ └── outputFiles.bin │ ├── checksums │ │ └── checksums.lock │ └── vcs-1 │ │ └── gc.properties ├── build.gradle ├── gradle │ └── wrapper │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ └── main │ └── java │ └── com │ └── solid │ ├── dependencyinversion │ ├── bad │ │ ├── AddOperation.java │ │ ├── Calculator.java │ │ └── SubOperation.java │ └── good │ │ ├── AddOperation.java │ │ ├── Calculator.java │ │ ├── CalculatorOperation.java │ │ └── SubOperation.java │ ├── interfacesegregation │ ├── BadDAOInterface.java │ ├── BadDBDaoConnection.java │ ├── BadFileDaoConnection.java │ └── good │ │ ├── DAOInterface.java │ │ ├── DBDaoConnection.java │ │ ├── DBInterface.java │ │ ├── FileDaoConnection.java │ │ └── FileInterface.java │ ├── liskov │ ├── bad │ │ ├── CreditCardLoan.java │ │ ├── HomeLoan.java │ │ ├── LoanClosureService.java │ │ └── LoanPayment.java │ └── good │ │ ├── CreditCardLoan.java │ │ ├── HomeLoan.java │ │ ├── LoanClosureService.java │ │ ├── LoanPayment.java │ │ └── SecureLoan.java │ ├── openclosed │ ├── AddOperation.java │ ├── BadCalculator.java │ ├── Calculator.java │ ├── Operation.java │ └── SubstractOperation.java │ └── singleresponsiblity │ ├── Account.java │ ├── AccountOperations.java │ ├── Main.java │ └── TransactionOperations.java ├── state ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── dailycodebuffer │ │ │ └── state │ │ │ ├── Context.java │ │ │ ├── StartState.java │ │ │ ├── State.java │ │ │ ├── StateApplication.java │ │ │ └── StopState.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── dailycodebuffer │ └── state │ └── StateApplicationTests.java ├── strategy ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── dailycodebuffer │ │ │ └── strategy │ │ │ ├── Context.java │ │ │ ├── OperationAdd.java │ │ │ ├── OperationMultiply.java │ │ │ ├── OperationSubtract.java │ │ │ ├── Strategy.java │ │ │ └── StrategyApplication.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── dailycodebuffer │ └── strategy │ └── StrategyApplicationTests.java └── template ├── .gitignore ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── dailycodebuffer │ │ └── template │ │ ├── Cricket.java │ │ ├── Football.java │ │ ├── Game.java │ │ └── TemplateApplication.java └── resources │ └── application.properties └── test └── java └── com └── dailycodebuffer └── template └── TemplateApplicationTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | # generated files 2 | bin/** 3 | gen/** 4 | # project based files 5 | .idea/ 6 | *.iml 7 | *.ipr 8 | *.iws 9 | .gradletasknamecache 10 | .gradle/ 11 | build/ 12 | bin/ 13 | -------------------------------------------------------------------------------- /ChainOfResponsibility/ChainOfResponsibility/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /ChainOfResponsibility/ChainOfResponsibility/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '2.7.7' 4 | id 'io.spring.dependency-management' version '1.0.15.RELEASE' 5 | } 6 | 7 | group = 'com.dailycodebuffer' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '11' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | dependencies { 16 | implementation 'org.springframework.boot:spring-boot-starter' 17 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 18 | } 19 | 20 | tasks.named('test') { 21 | useJUnitPlatform() 22 | } 23 | -------------------------------------------------------------------------------- /ChainOfResponsibility/ChainOfResponsibility/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/ChainOfResponsibility/ChainOfResponsibility/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /ChainOfResponsibility/ChainOfResponsibility/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /ChainOfResponsibility/ChainOfResponsibility/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'ChainOfResponsibility' 2 | -------------------------------------------------------------------------------- /ChainOfResponsibility/ChainOfResponsibility/src/main/java/com/dailycodebuffer/chainofresponsibility/BankPaymentHandler.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.chainofresponsibility; 2 | 3 | public class BankPaymentHandler extends PaymentHandler{ 4 | public void handlePayment(double amount) { 5 | if (amount <= 500) { 6 | System.out.println("Paid using bank account: $" + amount); 7 | } else { 8 | next.handlePayment(amount); 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /ChainOfResponsibility/ChainOfResponsibility/src/main/java/com/dailycodebuffer/chainofresponsibility/ChainOfResponsibilityApplication.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.chainofresponsibility; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class ChainOfResponsibilityApplication { 8 | 9 | public static void main(String[] args) { 10 | PaymentHandler bank = new BankPaymentHandler(); 11 | PaymentHandler creditCard = new CreditCardPaymentHandler(); 12 | PaymentHandler paypal = new PayPalPaymentHandler(); 13 | bank.setNext(creditCard); 14 | creditCard.setNext(paypal); 15 | 16 | bank.handlePayment(600); 17 | bank.handlePayment(200); 18 | bank.handlePayment(1200); 19 | bank.handlePayment(600); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /ChainOfResponsibility/ChainOfResponsibility/src/main/java/com/dailycodebuffer/chainofresponsibility/CreditCardPaymentHandler.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.chainofresponsibility; 2 | 3 | public class CreditCardPaymentHandler extends PaymentHandler{ 4 | public void handlePayment(double amount) { 5 | if (amount <= 1000) { 6 | System.out.println("Paid using credit card: $" + amount); 7 | } else { 8 | next.handlePayment(amount); 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /ChainOfResponsibility/ChainOfResponsibility/src/main/java/com/dailycodebuffer/chainofresponsibility/PayPalPaymentHandler.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.chainofresponsibility; 2 | 3 | public class PayPalPaymentHandler extends PaymentHandler{ 4 | public void handlePayment(double amount) { 5 | if (amount <= 1500) { 6 | System.out.println("Paid using PayPal: $" + amount); 7 | } else { 8 | next.handlePayment(amount); 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /ChainOfResponsibility/ChainOfResponsibility/src/main/java/com/dailycodebuffer/chainofresponsibility/PaymentHandler.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.chainofresponsibility; 2 | /** 3 | * Chain of Responsibility is a behavioral design pattern that lets you pass requests along a chain of handlers. 4 | * Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain. 5 | * 6 | * The Chain of Responsibility pattern allows a number of classes to attempt to handle a request independently. 7 | * 8 | * Reference: https://refactoring.guru/design-patterns/chain-of-responsibility 9 | **/ 10 | public abstract class PaymentHandler { 11 | protected PaymentHandler next; 12 | public void setNext(PaymentHandler next) { 13 | this.next = next; 14 | } 15 | public abstract void handlePayment(double amount); 16 | } 17 | -------------------------------------------------------------------------------- /ChainOfResponsibility/ChainOfResponsibility/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /ChainOfResponsibility/ChainOfResponsibility/src/test/java/com/dailycodebuffer/chainofresponsibility/ChainOfResponsibilityApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.chainofresponsibility; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class ChainOfResponsibilityApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # design_patterns 2 | design_patterns 3 | -------------------------------------------------------------------------------- /abstract_factory/.gradle/7.1/dependencies-accessors/dependencies-accessors.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/abstract_factory/.gradle/7.1/dependencies-accessors/dependencies-accessors.lock -------------------------------------------------------------------------------- /abstract_factory/.gradle/7.1/dependencies-accessors/gc.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/abstract_factory/.gradle/7.1/dependencies-accessors/gc.properties -------------------------------------------------------------------------------- /abstract_factory/.gradle/7.1/executionHistory/executionHistory.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/abstract_factory/.gradle/7.1/executionHistory/executionHistory.bin -------------------------------------------------------------------------------- /abstract_factory/.gradle/7.1/executionHistory/executionHistory.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/abstract_factory/.gradle/7.1/executionHistory/executionHistory.lock -------------------------------------------------------------------------------- /abstract_factory/.gradle/7.1/fileChanges/last-build.bin: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /abstract_factory/.gradle/7.1/fileHashes/fileHashes.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/abstract_factory/.gradle/7.1/fileHashes/fileHashes.bin -------------------------------------------------------------------------------- /abstract_factory/.gradle/7.1/fileHashes/fileHashes.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/abstract_factory/.gradle/7.1/fileHashes/fileHashes.lock -------------------------------------------------------------------------------- /abstract_factory/.gradle/7.1/gc.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/abstract_factory/.gradle/7.1/gc.properties -------------------------------------------------------------------------------- /abstract_factory/.gradle/buildOutputCleanup/buildOutputCleanup.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/abstract_factory/.gradle/buildOutputCleanup/buildOutputCleanup.lock -------------------------------------------------------------------------------- /abstract_factory/.gradle/buildOutputCleanup/cache.properties: -------------------------------------------------------------------------------- 1 | #Wed Oct 19 22:36:12 IST 2022 2 | gradle.version=7.1 3 | -------------------------------------------------------------------------------- /abstract_factory/.gradle/buildOutputCleanup/outputFiles.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/abstract_factory/.gradle/buildOutputCleanup/outputFiles.bin -------------------------------------------------------------------------------- /abstract_factory/.gradle/checksums/checksums.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/abstract_factory/.gradle/checksums/checksums.lock -------------------------------------------------------------------------------- /abstract_factory/.gradle/vcs-1/gc.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/abstract_factory/.gradle/vcs-1/gc.properties -------------------------------------------------------------------------------- /abstract_factory/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'org.example' 6 | version '1.0-SNAPSHOT' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' 14 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' 15 | } 16 | 17 | test { 18 | useJUnitPlatform() 19 | } -------------------------------------------------------------------------------- /abstract_factory/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /abstract_factory/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /abstract_factory/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'abstract_factory' 2 | 3 | -------------------------------------------------------------------------------- /abstract_factory/src/main/java/demo/component/Application.java: -------------------------------------------------------------------------------- 1 | package demo.component; 2 | 3 | import demo.component.uifactory.UIFactory; 4 | 5 | public class Application { 6 | private Button button; 7 | private CheckBox checkbox; 8 | 9 | public Application(UIFactory factory) { 10 | button = factory.createButton(); 11 | checkbox = factory.createCheckBox(); 12 | } 13 | 14 | public void paint() { 15 | button.paint(); 16 | checkbox.paint(); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /abstract_factory/src/main/java/demo/component/Button.java: -------------------------------------------------------------------------------- 1 | package demo.component; 2 | 3 | public interface Button { 4 | void paint(); 5 | } 6 | -------------------------------------------------------------------------------- /abstract_factory/src/main/java/demo/component/CheckBox.java: -------------------------------------------------------------------------------- 1 | package demo.component; 2 | 3 | public interface CheckBox { 4 | void paint(); 5 | } 6 | -------------------------------------------------------------------------------- /abstract_factory/src/main/java/demo/component/Main.java: -------------------------------------------------------------------------------- 1 | package demo.component; 2 | 3 | import demo.component.uifactory.MacUIFactory; 4 | import demo.component.uifactory.WinUIFactory; 5 | 6 | /** 7 | * As we know in factory pattern we took control of creating object and details by taking type. 8 | * Now you have to use factory when your application support different product families example Computer can be PC,Server or Assembled. 9 | * So what client needs to do is just pass the family of the product and that product will be built i.e. created. 10 | * Since we are dealing with creation of objects it is falling under creational design pattern. 11 | * 12 | * You ensure that when we say multiple product families , it should be related. 13 | * 14 | * A abstract factory contains main following : 15 | * 1. Abstract product class , in our case : Button and Checkbox 16 | * 2. Actual products that is MacButton,WinButton etc. 17 | * 3. Abstract factory - which helps for interacting for creation and product factories will extend that to ensure right 18 | * product gets created. - Here UIFactory 19 | * 4. Actual product factories - WinUIFactory , MacUIFactory 20 | * 5. Client - Application will take the respective factory and creates object, and then you can paint UI. 21 | * 22 | * Java lib example which is most famous that DOM Parser .It uses abstract factory pattern for creations. 23 | * The DocumentBuilderFactory is an abstract factory, a factory that is created as a new instance of DocumentBuilderFactory and the Document is an interface that is implemented by the factory to return the response. 24 | * We don't know here which type of DocumentBuilder we got but based on our input it has given correct instance. 25 | * 26 | * Reference example : https://refactoring.guru/design-patterns/abstract-factory/java/example 27 | */ 28 | public class Main { 29 | public static void main(String[] args) { 30 | Application application 31 | = new Application(new MacUIFactory()); 32 | application.paint(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /abstract_factory/src/main/java/demo/component/os/mac/MacButton.java: -------------------------------------------------------------------------------- 1 | package demo.component.os.mac; 2 | 3 | import demo.component.Button; 4 | 5 | public class MacButton implements Button { 6 | @Override 7 | public void paint() { 8 | System.out.println("Mac Button"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /abstract_factory/src/main/java/demo/component/os/mac/MacCheckBox.java: -------------------------------------------------------------------------------- 1 | package demo.component.os.mac; 2 | 3 | import demo.component.CheckBox; 4 | 5 | public class MacCheckBox implements CheckBox { 6 | @Override 7 | public void paint() { 8 | System.out.println("Mac Checkbox"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /abstract_factory/src/main/java/demo/component/os/win/WinButton.java: -------------------------------------------------------------------------------- 1 | package demo.component.os.win; 2 | 3 | import demo.component.Button; 4 | 5 | public class WinButton implements Button { 6 | @Override 7 | public void paint() { 8 | System.out.println("Win Button"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /abstract_factory/src/main/java/demo/component/os/win/WinCheckBox.java: -------------------------------------------------------------------------------- 1 | package demo.component.os.win; 2 | 3 | import demo.component.CheckBox; 4 | 5 | public class WinCheckBox implements CheckBox { 6 | @Override 7 | public void paint() { 8 | System.out.println("Win Checkbox"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /abstract_factory/src/main/java/demo/component/uifactory/MacUIFactory.java: -------------------------------------------------------------------------------- 1 | package demo.component.uifactory; 2 | 3 | import demo.component.Button; 4 | import demo.component.CheckBox; 5 | import demo.component.os.mac.MacButton; 6 | import demo.component.os.mac.MacCheckBox; 7 | 8 | public class MacUIFactory implements UIFactory { 9 | @Override 10 | public Button createButton() { 11 | return new MacButton(); 12 | } 13 | 14 | @Override 15 | public CheckBox createCheckBox() { 16 | return new MacCheckBox(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /abstract_factory/src/main/java/demo/component/uifactory/UIFactory.java: -------------------------------------------------------------------------------- 1 | package demo.component.uifactory; 2 | 3 | import demo.component.Button; 4 | import demo.component.CheckBox; 5 | 6 | public interface UIFactory { 7 | Button createButton(); 8 | CheckBox createCheckBox(); 9 | } 10 | -------------------------------------------------------------------------------- /abstract_factory/src/main/java/demo/component/uifactory/WinUIFactory.java: -------------------------------------------------------------------------------- 1 | package demo.component.uifactory; 2 | 3 | import demo.component.Button; 4 | import demo.component.CheckBox; 5 | import demo.component.os.win.WinButton; 6 | import demo.component.os.win.WinCheckBox; 7 | 8 | public class WinUIFactory implements UIFactory { 9 | @Override 10 | public Button createButton() { 11 | return new WinButton(); 12 | } 13 | 14 | @Override 15 | public CheckBox createCheckBox() { 16 | return new WinCheckBox(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /adapter/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /adapter/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /adapter/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'adapter' 2 | 3 | -------------------------------------------------------------------------------- /adapter/src/main/java/FoodItem.java: -------------------------------------------------------------------------------- 1 | public class FoodItem implements Item{ 2 | @Override 3 | public String getItemName() { 4 | return null; 5 | } 6 | 7 | @Override 8 | public String getPrice() { 9 | return null; 10 | } 11 | 12 | @Override 13 | public String getRestaurantName() { 14 | return null; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /adapter/src/main/java/GroceryItem.java: -------------------------------------------------------------------------------- 1 | public interface GroceryItem { 2 | String getName(); 3 | String getPrice(); 4 | String getStoreName(); 5 | } 6 | -------------------------------------------------------------------------------- /adapter/src/main/java/GroceryItemAdapter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * This is the example of object level adater because we are adapting groceryItem using 3 | * instance of that particular class. 4 | */ 5 | public class GroceryItemAdapter implements Item { 6 | private GroceryItem item; 7 | public GroceryItemAdapter(GroceryItem item) { 8 | this.item = item; 9 | } 10 | 11 | @Override 12 | public String getItemName() { 13 | return item.getName(); 14 | } 15 | 16 | @Override 17 | public String getPrice() { 18 | return item.getPrice(); 19 | } 20 | 21 | @Override 22 | public String getRestaurantName() { 23 | return item.getStoreName(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /adapter/src/main/java/GroceryProduct.java: -------------------------------------------------------------------------------- 1 | public class GroceryProduct implements GroceryItem{ 2 | @Override 3 | public String getName() { 4 | return null; 5 | } 6 | 7 | @Override 8 | public String getPrice() { 9 | return null; 10 | } 11 | 12 | @Override 13 | public String getStoreName() { 14 | return null; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /adapter/src/main/java/Item.java: -------------------------------------------------------------------------------- 1 | public interface Item { 2 | String getItemName(); 3 | String getPrice(); 4 | String getRestaurantName(); 5 | } 6 | -------------------------------------------------------------------------------- /adapter/src/main/java/Main.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Adapter patterns comes under structural pattern as it deals with how classes are interacting. 3 | * As name suggests adapter pattern is used adapt two different incompatible system. 4 | * 5 | * Adapter pattern also helps and be connector between your system and some third party or legacy system. 6 | * For example your system expects data in one format to process and third party sends in one format. 7 | * Example : Consider you have to invoke some third party soap service which is xml base however your system is built on JSON 8 | * with some advanced fields at that time you create JSON-to-XML adapter which will help to interact with thirdparty. 9 | * Adapter pattern can be achieved in two ways : 10 | * 1. Class Level: class level mean to adapt something you are extending and doing inheritance of that class. 11 | * 2. Object level : Object level mean you keep has-a relationship with class rather doing tight coupling in system. 12 | * 13 | * One of the example is we know java supports both array and list to store data. Now you have legacy system 14 | * which is using array and you want to use collection functionalities to do so we have to convert, so Arrays.asList work as adaper 15 | * between array to list and then use collections. 16 | * 17 | * A java.io.InputStreamReader translates a byte stream into a character stream, and a java.io.OutputStreamWriter translates a character stream into a byte stream. These classes exemplify the Adapter pattern. 18 | * In particular, they change input/output stream interfaces to the required reader/writer interfaces 19 | * https://cecs.wright.edu/~tkprasad/courses/ceg860/paper/node26.html 20 | * 21 | * In this example we will see that Swiggy is selling food products now suddenly lockdown arise 22 | * and they thought to provide service of delivering grocery items for sometime so they write adapter which 23 | * helps them to convert similar to food item without touching their food delivery business. 24 | * 25 | * https://www.javadevjournal.com/java-design-patterns/adapter-design-pattern/ 26 | * 27 | * Reference : https://www.programmergirl.com/java-adapter-pattern/ 28 | */ 29 | public class Main { 30 | public static void main(String[] args) { 31 | SwiggyStore swiggyStore = new SwiggyStore(); 32 | swiggyStore.addItems(new FoodItem()); 33 | swiggyStore.addItems(new FoodItem()); 34 | //Adapter grocery which was incompatible with food. 35 | swiggyStore.addItems(new GroceryItemAdapter(new GroceryProduct())); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /adapter/src/main/java/SwiggyStore.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class SwiggyStore { 5 | List items = new ArrayList<>(); 6 | public void addItems(Item item) { 7 | items.add(item); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /bridge/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'org.example' 6 | version '1.0-SNAPSHOT' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' 14 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' 15 | } 16 | 17 | test { 18 | useJUnitPlatform() 19 | } -------------------------------------------------------------------------------- /bridge/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /bridge/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /bridge/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'bridge' 2 | 3 | -------------------------------------------------------------------------------- /bridge/src/main/java/HDProcessor.java: -------------------------------------------------------------------------------- 1 | public class HDProcessor implements VideoProcessor { 2 | @Override 3 | public void process(String videoFile) { 4 | //Process 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /bridge/src/main/java/Main.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Bridge Pattern : Bridge pattern is also structural pattern similar to adapter,facade. 3 | * As the name suggest Bridge - we are creating bridge between two implementation using composition rather than going by 4 | * inheritance. While dealing with abstraction we usually create inheritance hierarchies to achieve abstraction. 5 | * However inheritance is not a good option everytime as it creates tightly couple application and one change in base class 6 | * cause issues in whole inheritance hierarchy. 7 | * 8 | * The bridge pattern does it by separating the abstraction and the implementation in separate class hierarchies. The bridge between the class hierarchies is achieved through composition. 9 | * 10 | * When we want a parent abstract class to define the set of basic rules, and the concrete classes to add additional rules 11 | * 12 | * When we go via inheritance it keeps growing the hierarchy. For example we have Shape class 13 | * which has Rectangle and Triangle. And each shape has two color variants red and yellow so you extended and Created RedRectangleShape and YellowRentangleShape and same triangle. 14 | * So we have now this 4 different variants of shape , consider you decided to expand for Blue color and Circle shape. So your classes keep getting increased. 15 | * 16 | * Rather lets implement bridge pattern which says separate out function in different hierarchies one color and one shape 17 | * So your shape has a color and uses it . So you can keep expanding your system now. 18 | * 19 | * Major components to achieve bridge patterns are : 20 | * 1. Abstraction : This is main abstract class which client uses. 21 | * 2. RefinedAbstraction - This is the class which extends abstraction 22 | * 3. Implementor : Interface for the implementation hierarchy. 23 | * 4. Concrete Implementor - Implementation of the implementor. 24 | * 25 | * https://howtodoinjava.com/design-patterns/structural/bridge-design-pattern/ 26 | * https://springframework.guru/gang-of-four-design-patterns/bridge-pattern/ 27 | * 28 | * Consider example of video processing provider. 29 | * Where we process youtube and netflix video in 4K and HD for now. 30 | * 31 | * We can simply go in a way Youtube4kProcess , YoutubeHDProcess and same for netflix. However as you know it is not scalable and became more complex. 32 | * 33 | * So we implement this bridge pattern where: 34 | * 1. Abstraction : Video has a video processor 35 | * 2. RefinedAbstraction : Which is our Youtube and Netflix 36 | * 3. Implementor : VideoProcessor 37 | * 4. Concrete Implementor : 4KProcessor and HDProcessor 38 | * As you see in example you can simply expand the processor and video provider without affect. 39 | * Here we have implemented has-a relationship. 40 | */ 41 | public class Main { 42 | public static void main(String[] args) { 43 | Video youtubeVideo = new YoutubeVideo(new HDProcessor()); 44 | youtubeVideo.play("abc.mp4"); 45 | Video netflixVideo = new NetflixVideo(new UHD4KProcessor()); 46 | netflixVideo.play("abc.mp4"); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /bridge/src/main/java/NetflixVideo.java: -------------------------------------------------------------------------------- 1 | public class NetflixVideo extends Video{ 2 | public NetflixVideo(VideoProcessor processor) { 3 | super(processor); 4 | } 5 | 6 | @Override 7 | public void play(String videoFile) { 8 | processor.process(videoFile); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /bridge/src/main/java/UHD4KProcessor.java: -------------------------------------------------------------------------------- 1 | public class UHD4KProcessor implements VideoProcessor{ 2 | @Override 3 | public void process(String videoFile) { 4 | //process 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /bridge/src/main/java/Video.java: -------------------------------------------------------------------------------- 1 | public abstract class Video { 2 | protected VideoProcessor processor; 3 | public Video(VideoProcessor processor){ 4 | this.processor = processor; 5 | } 6 | public abstract void play(String videoFile); 7 | } 8 | -------------------------------------------------------------------------------- /bridge/src/main/java/VideoProcessor.java: -------------------------------------------------------------------------------- 1 | public interface VideoProcessor { 2 | void process(String videoFile); 3 | } 4 | -------------------------------------------------------------------------------- /bridge/src/main/java/YoutubeVideo.java: -------------------------------------------------------------------------------- 1 | public class YoutubeVideo extends Video{ 2 | public YoutubeVideo(VideoProcessor processor) { 3 | super(processor); 4 | } 5 | 6 | @Override 7 | public void play(String videoFile) { 8 | processor.process(videoFile); //Processed as per given processor 9 | //Now play 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /builder/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'org.example' 6 | version '1.0-SNAPSHOT' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | 14 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' 15 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' 16 | } 17 | 18 | test { 19 | useJUnitPlatform() 20 | } -------------------------------------------------------------------------------- /builder/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /builder/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /builder/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'builder' 2 | 3 | -------------------------------------------------------------------------------- /builder/src/main/java/Burger.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Most Common Way to implement builder pattern is to have Builder class as innner class because : - You might have seen at most of the places. -Joshua Bloch's Builder pattern 3 | * 1. We don't want to expose our constructor which eventually creates confusion at later stage. 4 | * 2. We don't want to have in-consistent object by having setters exposed. 5 | * 3. Now since constructor is private we will need inner class to access that. - Which will have same inputs what we have in class. But without getters. 6 | */ 7 | public class Burger { 8 | 9 | private String size; 10 | private boolean egg; 11 | private boolean extraCheese; 12 | private boolean mayonese; 13 | private boolean onion; 14 | private boolean lettuce; 15 | 16 | private Burger(BurgerBuilder burgerBuilder) { 17 | // Initialize all fields and you can also add validations. 18 | } 19 | 20 | public String getSize() { 21 | return size; 22 | } 23 | 24 | public boolean isEgg() { 25 | return egg; 26 | } 27 | 28 | public boolean isExtraCheese() { 29 | return extraCheese; 30 | } 31 | 32 | public boolean isMayonese() { 33 | return mayonese; 34 | } 35 | 36 | public boolean isOnion() { 37 | return onion; 38 | } 39 | 40 | public boolean isLettuce() { 41 | return lettuce; 42 | } 43 | 44 | //Return same object everytime that is builder instance 45 | //Once build method invoke return actual object. 46 | public static class BurgerBuilder { 47 | private String size; 48 | private boolean egg; 49 | private boolean extraCheese; 50 | private boolean mayonese; 51 | private boolean onion; 52 | private boolean lettuce; 53 | public BurgerBuilder size(String size) { 54 | this.size = size; 55 | return this; 56 | } 57 | public BurgerBuilder egg(boolean egg) { 58 | this.egg = egg; 59 | return this; 60 | } 61 | public BurgerBuilder extraCheese(boolean extraCheese) { 62 | this.extraCheese = extraCheese; 63 | return this; 64 | } 65 | public BurgerBuilder mayonese(boolean mayonese) { 66 | this.mayonese = mayonese; 67 | return this; 68 | } 69 | public BurgerBuilder onion(boolean onion) { 70 | this.onion = onion; 71 | return this; 72 | } 73 | public BurgerBuilder lettuce(boolean lettuce) { 74 | this.lettuce = lettuce; 75 | return this; 76 | } 77 | public Burger build() { 78 | 79 | return new Burger(this); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /builder/src/main/java/Main.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Builder pattern : It is creational design pattern used to create complex presentation of objects. 3 | * Let's say you have class which has initially 4 fields, so you decided to go with constructor then few more fields added 4 | * in same class which are optional and class modification goes on. So one choice is to have different args constructor. 5 | * That is good but till some extent how we will remember which argument number for what if list is so big!!! 6 | * Having this type of constructor is called as Telescoping constructor pattern where we keep having separate constructor as and when 7 | * we have new arguments. 8 | * 9 | * One more option is to use setters method but that has chances of missing pieces of some mandatory fields which leads to inconsistent object. 10 | * 11 | * By builder patter we take responsibility of creating object and providing back to client. Client just provides input and until 12 | * they won't call build method we won't create object. 13 | * 14 | * Builder pattern is also used when single class has different object representation meaning let's say We are creating 15 | * Burger which can be Veg, non veg ... which can have extra cheese or less cheese, bread size medium , large. 16 | * As user, you will say only I need one extra cheese large veg burger. 17 | * 18 | * To do so you can also have different builders which eventually passes the argument which are required to create that object. 19 | * 20 | * 21 | * Reference : https://www.tutorialspoint.com/design_pattern/builder_pattern.htm 22 | * https://springframework.guru/gang-of-four-design-patterns/builder-pattern/ 23 | * 24 | * 25 | */ 26 | public class Main { 27 | public static void main(String[] args) { 28 | //Using builder we have created the object and we as implementer of builder pattern need to assure that this is not inconsistent object. 29 | Burger burger = new Burger.BurgerBuilder() 30 | .mayonese(true) 31 | .onion(false) 32 | .egg(false) 33 | .extraCheese(true) 34 | .size("LARGE") 35 | .build(); 36 | 37 | //GOF Builder example 38 | Meal meal = new MealDirector(new VegMealBuilder()).prepareMeal(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /builder/src/main/java/Meal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * If we go via GOF Definition "The intent of the Builder design pattern is to separate the construction of a complex object from its representation. By doing so, the same construction process can create different representations.: 3 | * It means for this Meal class lets say we have different representation which VegMeal and NonVegMeal 4 | * Also this helps when you want to create object step by step too. 5 | * So to achieve GOF we have following components as part builder pattern. 6 | * 1. Product - Which we are building 7 | * 2. AbstractBuilder - Which is helpful to provide the product 8 | * 3. Concrete builder : It is actual builder which helps us to provide specific representation of the object. 9 | * 4. Director : Which uses this concrete builder and provides the 10 | */ 11 | public class Meal { 12 | private String curry; 13 | private String bread; 14 | private String coldDrink; 15 | private String briyani; 16 | 17 | public String getCurry() { 18 | return curry; 19 | } 20 | 21 | public void setCurry(String curry) { 22 | this.curry = curry; 23 | } 24 | 25 | public String getBread() { 26 | return bread; 27 | } 28 | 29 | public void setBread(String bread) { 30 | this.bread = bread; 31 | } 32 | 33 | public String getColdDrink() { 34 | return coldDrink; 35 | } 36 | 37 | public void setColdDrink(String coldDrink) { 38 | this.coldDrink = coldDrink; 39 | } 40 | 41 | public String getBriyani() { 42 | return briyani; 43 | } 44 | 45 | public void setBriyani(String briyani) { 46 | this.briyani = briyani; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /builder/src/main/java/MealBuilder.java: -------------------------------------------------------------------------------- 1 | public abstract class MealBuilder { 2 | public abstract void addBriyani(); 3 | public abstract void addBread(); 4 | public abstract void addColdDrink(); 5 | public abstract void addCurry(); 6 | public abstract Meal build(); 7 | } 8 | -------------------------------------------------------------------------------- /builder/src/main/java/MealDirector.java: -------------------------------------------------------------------------------- 1 | //Client will interact with this director which helps to provide the meal. 2 | //Note that we can have this as per our choice there is no standard way , we can also have two different method getVegMeal and getNonVegMeal 3 | // Which will use the builders directly inside the method , in this example we are taking input which builder which type of builder needing. 4 | public class MealDirector { 5 | private MealBuilder mealBuilder; 6 | public MealDirector(MealBuilder mealBuilder) { 7 | this.mealBuilder = mealBuilder; 8 | } 9 | public Meal prepareMeal() { 10 | mealBuilder.addBread(); 11 | mealBuilder.addBriyani(); 12 | mealBuilder.addCurry(); 13 | mealBuilder.addColdDrink(); 14 | return mealBuilder.build(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /builder/src/main/java/NonVegMealBuilder.java: -------------------------------------------------------------------------------- 1 | public class NonVegMealBuilder extends MealBuilder{ 2 | private Meal meal; 3 | public NonVegMealBuilder() { 4 | meal = new Meal(); 5 | } 6 | @Override 7 | public void addBriyani() { 8 | this.meal.setBriyani("Chicken"); 9 | } 10 | 11 | @Override 12 | public void addBread() { 13 | this.meal.setBread("Roti"); 14 | 15 | } 16 | 17 | @Override 18 | public void addColdDrink() { 19 | this.meal.setColdDrink("Sprite"); 20 | 21 | } 22 | 23 | @Override 24 | public void addCurry() { 25 | this.meal.setCurry("Non-Veg"); 26 | } 27 | 28 | @Override 29 | public Meal build() { 30 | return meal; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /builder/src/main/java/VegMealBuilder.java: -------------------------------------------------------------------------------- 1 | public class VegMealBuilder extends MealBuilder{ 2 | private Meal meal; 3 | public VegMealBuilder() { 4 | meal = new Meal(); 5 | } 6 | @Override 7 | public void addBriyani() { 8 | this.meal.setBriyani("Veg"); 9 | } 10 | 11 | @Override 12 | public void addBread() { 13 | this.meal.setBread("Naan"); 14 | 15 | } 16 | 17 | @Override 18 | public void addColdDrink() { 19 | this.meal.setColdDrink("Sprite"); 20 | 21 | } 22 | 23 | @Override 24 | public void addCurry() { 25 | this.meal.setCurry("Veg"); 26 | } 27 | 28 | @Override 29 | public Meal build() { 30 | return meal; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /command/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /command/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '2.7.7' 4 | id 'io.spring.dependency-management' version '1.0.15.RELEASE' 5 | } 6 | 7 | group = 'com.dailycodebuffer' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '11' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | dependencies { 16 | implementation 'org.springframework.boot:spring-boot-starter' 17 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 18 | } 19 | 20 | tasks.named('test') { 21 | useJUnitPlatform() 22 | } 23 | -------------------------------------------------------------------------------- /command/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/command/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /command/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /command/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /command/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'command' 2 | -------------------------------------------------------------------------------- /command/src/main/java/com/dailycodebuffer/command/CommandApplication.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.command; 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | 5 | /** 6 | * Command is a behavioral design pattern that turns a request into a stand-alone object that contains all 7 | * information about the request. This transformation lets you pass requests as a method arguments, delay 8 | * or queue a request’s execution, and support undoable operations. 9 | * 10 | * Reference: https://refactoring.guru/design-patterns/command 11 | * https://www.baeldung.com/java-command-pattern 12 | */ 13 | 14 | @SpringBootApplication 15 | public class CommandApplication { 16 | 17 | public static void main(String[] args) { 18 | TextFileOperationExecutor textFileOperationExecutor 19 | = new TextFileOperationExecutor(); 20 | textFileOperationExecutor.executeOperation( 21 | new OpenTextFileOperation(new TextFile("file1.txt"))); 22 | textFileOperationExecutor.executeOperation( 23 | new SaveTextFileOperation(new TextFile("file2.txt"))); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /command/src/main/java/com/dailycodebuffer/command/OpenTextFileOperation.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.command; 2 | 3 | public class OpenTextFileOperation implements TextFileOperation{ 4 | 5 | private TextFile textFile; 6 | 7 | public OpenTextFileOperation(TextFile textFile) { 8 | this.textFile = textFile; 9 | } 10 | 11 | @Override 12 | public String execute() { 13 | return textFile.open(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /command/src/main/java/com/dailycodebuffer/command/SaveTextFileOperation.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.command; 2 | 3 | public class SaveTextFileOperation implements TextFileOperation{ 4 | private TextFile textFile; 5 | 6 | public SaveTextFileOperation(TextFile textFile) { 7 | this.textFile = textFile; 8 | } 9 | 10 | @Override 11 | public String execute() { 12 | return textFile.save(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /command/src/main/java/com/dailycodebuffer/command/TextFile.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.command; 2 | 3 | public class TextFile { 4 | 5 | private String name; 6 | 7 | public TextFile(String name) { 8 | this.name = name; 9 | } 10 | 11 | public String open() { 12 | return "Opening file " + name; 13 | } 14 | 15 | public String save() { 16 | return "Saving file " + name; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /command/src/main/java/com/dailycodebuffer/command/TextFileOperation.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.command; 2 | 3 | @FunctionalInterface 4 | public interface TextFileOperation { 5 | String execute(); 6 | } 7 | -------------------------------------------------------------------------------- /command/src/main/java/com/dailycodebuffer/command/TextFileOperationExecutor.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.command; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class TextFileOperationExecutor { 7 | 8 | private final List textFileOperations 9 | = new ArrayList<>(); 10 | 11 | public String executeOperation(TextFileOperation textFileOperation) { 12 | textFileOperations.add(textFileOperation); 13 | return textFileOperation.execute(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /command/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /command/src/test/java/com/dailycodebuffer/command/CommandApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.command; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class CommandApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /composite/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /composite/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '2.7.7' 4 | id 'io.spring.dependency-management' version '1.0.15.RELEASE' 5 | } 6 | 7 | group = 'com.dailycodebuffer' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '11' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | dependencies { 16 | implementation 'org.springframework.boot:spring-boot-starter' 17 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 18 | } 19 | 20 | tasks.named('test') { 21 | useJUnitPlatform() 22 | } 23 | -------------------------------------------------------------------------------- /composite/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/composite/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /composite/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /composite/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'composite' 2 | -------------------------------------------------------------------------------- /composite/src/main/java/com/dailycodebuffer/composite/CompositeApplication.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.composite; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class CompositeApplication { 8 | 9 | public static void main(String[] args) { 10 | //SpringApplication.run(CompositeApplication.class, args); 11 | Department salesDepartment = new SalesDepartment( 12 | 1, "Sales department"); 13 | Department financialDepartment = new FinancialDepartment( 14 | 2, "Financial department"); 15 | 16 | HeadDepartment headDepartment = new HeadDepartment( 17 | 3, "Head department"); 18 | 19 | headDepartment.addDepartment(salesDepartment); 20 | headDepartment.addDepartment(financialDepartment); 21 | 22 | headDepartment.printDepartmentName(); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /composite/src/main/java/com/dailycodebuffer/composite/Department.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.composite; 2 | 3 | /** 4 | * Composite pattern : Composite is a structural design pattern that lets you compose objects 5 | * into tree structures and then work with these structures as if they were individual objects. 6 | * 7 | * Reference: https://www.baeldung.com/java-composite-pattern 8 | * https://refactoring.guru/design-patterns/composite 9 | * 10 | * It can be viewed as a tree structure made up of types that inherit a base type, 11 | * and it can represent a single part or a whole hierarchy of objects. 12 | * 13 | * Component – is the base interface for all the objects in the composition. It should be either an interface 14 | * or an abstract class with the common methods to manage the child composites. 15 | * Leaf – implements the default behavior of the base component. It doesn't contain a reference to the other objects. 16 | * Composite – has leaf elements. It implements the base component methods and defines the child-related operations. 17 | * 18 | */ 19 | public interface Department { 20 | void printDepartmentName(); 21 | } 22 | -------------------------------------------------------------------------------- /composite/src/main/java/com/dailycodebuffer/composite/FinancialDepartment.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.composite; 2 | 3 | public class FinancialDepartment implements Department{ 4 | 5 | private Integer id; 6 | private String name; 7 | 8 | public FinancialDepartment(int id, String name) { 9 | this.id = id; 10 | this.name = name; 11 | } 12 | 13 | @Override 14 | public void printDepartmentName() { 15 | System.out.println(getClass().getSimpleName()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /composite/src/main/java/com/dailycodebuffer/composite/HeadDepartment.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.composite; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class HeadDepartment implements Department{ 7 | 8 | private Integer id; 9 | private String name; 10 | 11 | private List childDepartments; 12 | 13 | public HeadDepartment(Integer id, String name) { 14 | this.id = id; 15 | this.name = name; 16 | this.childDepartments = new ArrayList<>(); 17 | } 18 | 19 | public void printDepartmentName() { 20 | childDepartments.forEach(Department::printDepartmentName); 21 | } 22 | 23 | public void addDepartment(Department department) { 24 | childDepartments.add(department); 25 | } 26 | 27 | public void removeDepartment(Department department) { 28 | childDepartments.remove(department); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /composite/src/main/java/com/dailycodebuffer/composite/SalesDepartment.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.composite; 2 | 3 | public class SalesDepartment implements Department{ 4 | 5 | private Integer id; 6 | private String name; 7 | 8 | public SalesDepartment(int id, String name) { 9 | this.id = id; 10 | this.name = name; 11 | } 12 | 13 | @Override 14 | public void printDepartmentName() { 15 | System.out.println(getClass().getSimpleName()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /composite/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /composite/src/test/java/com/dailycodebuffer/composite/CompositeApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.composite; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class CompositeApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /decorator/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'org.example' 6 | version '1.0-SNAPSHOT' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' 14 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' 15 | } 16 | 17 | test { 18 | useJUnitPlatform() 19 | } -------------------------------------------------------------------------------- /decorator/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /decorator/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /decorator/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'decorator' 2 | 3 | -------------------------------------------------------------------------------- /decorator/src/main/java/BasePizza.java: -------------------------------------------------------------------------------- 1 | public class BasePizza implements Pizza{ 2 | @Override 3 | public String bake() { 4 | return "Base Pizza"; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /decorator/src/main/java/CheeseBurstDecorator.java: -------------------------------------------------------------------------------- 1 | public class CheeseBurstDecorator extends PizzaDecorator{ 2 | public CheeseBurstDecorator(Pizza pizza) { 3 | super(pizza); 4 | } 5 | public String bake() { 6 | return pizza.bake() + addCheese(); 7 | } 8 | 9 | public String addCheese(){ 10 | return "Cheese"; 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /decorator/src/main/java/JalepanoDecorator.java: -------------------------------------------------------------------------------- 1 | public class JalepanoDecorator extends PizzaDecorator{ 2 | public JalepanoDecorator(Pizza pizza) { 3 | super(pizza); 4 | } 5 | public String bake() { 6 | return pizza.bake() + addJalepano(); 7 | } 8 | 9 | public String addJalepano(){ 10 | return "jalepeno"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /decorator/src/main/java/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Collections; 2 | 3 | /** 4 | * Decorator - It is a design pattern categorized in structural pattern. It helps to decorate the object meaning 5 | * It basically keeps expanding behaviour of the object.The decorator design pattern is used to change an object’s functionality during runtime. 6 | * Other instances of the same class will be unaffected, therefore each object will have its behavior changed. 7 | * 8 | * Since we can keep supporting adding new decorator we are getting dynamic object extension. 9 | * After all we are creating stack of wrapper , certain system becomes so coupled that it becomes difficult to 10 | * remove certain decorators. 11 | * 12 | * Inheritance also helps to expand the functionality but that is at compiletime not at runtime. 13 | * One of the best example of decorator is customized pizza. Where you have pizza and you have different decorator 14 | * like addExtraChese, cheeseburst, olives yes, jalepeno yes. We keep adding topups and we finally get pizza. 15 | * 16 | * You can also think of Account -> Saving Account -> Salary Account -> Preferred Account. 17 | * Where base is Account now based on different accounttype it keeps adding new features and offers to same account. 18 | * To achieve decorator pattern you need following: 19 | * Create Interface - Base product 20 | * Create abstract class - Base product's base impl 21 | * Abstract Decorator - which implements base product - This works as foundation of decorator what other decorator needs to do minimum. 22 | * Different decorators - Which takes this product input and decorate it. 23 | * 24 | * Java example : Collection.unmodifiableMap - this is decorator which is extending Map's functionality and 25 | * making unmodifiable. 26 | * https://cecs.wright.edu/~tkprasad/courses/ceg860/paper/node26.html 27 | * 28 | * More details : https://www.javadevjournal.com/java-design-patterns/decorator-design-pattern/ 29 | * 30 | */ 31 | public class Main { 32 | 33 | 34 | public static void main(String[] args) { 35 | // We got pizza with different topings , we can keep adding topings 36 | Pizza pizza = new JalepanoDecorator(new CheeseBurstDecorator(new BasePizza())); 37 | System.out.println(pizza.bake()); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /decorator/src/main/java/Pizza.java: -------------------------------------------------------------------------------- 1 | public interface Pizza { 2 | public String bake(); 3 | } 4 | -------------------------------------------------------------------------------- /decorator/src/main/java/PizzaDecorator.java: -------------------------------------------------------------------------------- 1 | public abstract class PizzaDecorator implements Pizza { 2 | protected Pizza pizza; 3 | 4 | public PizzaDecorator(Pizza pizza) { 5 | this.pizza = pizza; 6 | } 7 | 8 | public String bake() { 9 | return pizza.bake(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /facade/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'org.example' 6 | version '1.0-SNAPSHOT' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' 14 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' 15 | } 16 | 17 | test { 18 | useJUnitPlatform() 19 | } -------------------------------------------------------------------------------- /facade/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /facade/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /facade/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'facade' 2 | 3 | -------------------------------------------------------------------------------- /facade/src/main/java/DeliveryBoy.java: -------------------------------------------------------------------------------- 1 | public class DeliveryBoy { 2 | public void pickUpOrder() { 3 | 4 | } 5 | public void deliverOrder() { 6 | 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /facade/src/main/java/DeliveryTeam.java: -------------------------------------------------------------------------------- 1 | public class DeliveryTeam { 2 | public void assignDeliveryBoy() { 3 | 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /facade/src/main/java/Main.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Facade pattern : This is also a structural pattern where it defines how classes needs to be structured in a way that 3 | * for complex functionalities there is single entry point to that function. 4 | * We should use facade pattern when we have complex subsystems , calling each leads to a single operation for client. 5 | * In this case we should introduce facade which helps to do interaction with all this subsystem and gives us single output, 6 | * Facade pattern basically adds one level of abstractions in the system. 7 | * 8 | * To implement facade you have to write one class which interacts with other services in down stream. 9 | * 10 | * Consider example you have to place order in the zomato and you want to get food 11 | * 1. Customer sees menu and place order 12 | * 2. Restaurant got this order and prepare order 13 | * 3. Delivery team assigns delivery person 14 | * 4. Delivery boy picks up order and deliver. 15 | * 16 | * Here Zomato api is facade for us where we just clicked place order and it done. Think to get food 17 | * after placing order you have to call restaurant to prepare order and give it to delivery boy. 18 | * 19 | * https://www.decipherzone.com/blog-detail/facade-design-pattern 20 | */ 21 | public class Main { 22 | 23 | } 24 | -------------------------------------------------------------------------------- /facade/src/main/java/Restaurant.java: -------------------------------------------------------------------------------- 1 | public class Restaurant { 2 | public void prepareOrder() { 3 | 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /facade/src/main/java/ZomatoFacade.java: -------------------------------------------------------------------------------- 1 | public class ZomatoFacade { 2 | private Restaurant restaurant; 3 | private DeliveryBoy deliveryBoy; 4 | private DeliveryTeam deliveryTeam; 5 | 6 | public void placeOrder() { 7 | restaurant.prepareOrder(); 8 | deliveryTeam.assignDeliveryBoy(); 9 | deliveryBoy.pickUpOrder(); 10 | deliveryBoy.deliverOrder(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /factory/.gradle/7.1/dependencies-accessors/dependencies-accessors.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/factory/.gradle/7.1/dependencies-accessors/dependencies-accessors.lock -------------------------------------------------------------------------------- /factory/.gradle/7.1/dependencies-accessors/gc.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/factory/.gradle/7.1/dependencies-accessors/gc.properties -------------------------------------------------------------------------------- /factory/.gradle/7.1/executionHistory/executionHistory.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/factory/.gradle/7.1/executionHistory/executionHistory.bin -------------------------------------------------------------------------------- /factory/.gradle/7.1/executionHistory/executionHistory.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/factory/.gradle/7.1/executionHistory/executionHistory.lock -------------------------------------------------------------------------------- /factory/.gradle/7.1/fileChanges/last-build.bin: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /factory/.gradle/7.1/fileHashes/fileHashes.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/factory/.gradle/7.1/fileHashes/fileHashes.bin -------------------------------------------------------------------------------- /factory/.gradle/7.1/fileHashes/fileHashes.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/factory/.gradle/7.1/fileHashes/fileHashes.lock -------------------------------------------------------------------------------- /factory/.gradle/7.1/gc.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/factory/.gradle/7.1/gc.properties -------------------------------------------------------------------------------- /factory/.gradle/buildOutputCleanup/buildOutputCleanup.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/factory/.gradle/buildOutputCleanup/buildOutputCleanup.lock -------------------------------------------------------------------------------- /factory/.gradle/buildOutputCleanup/cache.properties: -------------------------------------------------------------------------------- 1 | #Mon Oct 17 21:49:10 IST 2022 2 | gradle.version=7.1 3 | -------------------------------------------------------------------------------- /factory/.gradle/buildOutputCleanup/outputFiles.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/factory/.gradle/buildOutputCleanup/outputFiles.bin -------------------------------------------------------------------------------- /factory/.gradle/checksums/checksums.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/factory/.gradle/checksums/checksums.lock -------------------------------------------------------------------------------- /factory/.gradle/vcs-1/gc.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/factory/.gradle/vcs-1/gc.properties -------------------------------------------------------------------------------- /factory/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'org.example' 6 | version '1.0-SNAPSHOT' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' 14 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' 15 | } 16 | 17 | test { 18 | useJUnitPlatform() 19 | } -------------------------------------------------------------------------------- /factory/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /factory/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /factory/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'factory' 2 | 3 | -------------------------------------------------------------------------------- /factory/src/main/java/OperatingSystemFactory.java: -------------------------------------------------------------------------------- 1 | import factories.LinuxOperatingSystem; 2 | import factories.OperatingSystem; 3 | import factories.WindowsOperatingSysten; 4 | 5 | /** 6 | * Factory : As name suggest it is factory where we can create objects. 7 | * Since it creates object it falls in creational design pattern 8 | * Factory pattern has two important element in its design. 9 | * 10 | * 1. Interface/Abstract class : This is base element for which we are making factory i.e. we are going to get object of this type 11 | * In this case it is "OperatingSystem" which has type available Windows and Linux. 12 | * 13 | * 2. Factory : This will have nothing but Object creation logic. Let's say as a library you introduce one more subtype that is 14 | * MacOperatingSystem. Now your caller is automatically extended this facility of third type , also we have taken responsibility of 15 | * creating of object. 16 | * 17 | * In java this pattern is heavily used: 18 | * 1. Calendar.getInstance : Calendar is abstract class amd based on Locale and Timezone we provided it is giving calendar instance. 19 | * Note in this case we really don't know what type of calendar we got. 20 | * 2. In reflection Class.forname : the type of class you pass it gets loaded. 21 | * 22 | * Best link to learn java and patterns used : https://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns-in-javas-core-libraries 23 | */ 24 | public class OperatingSystemFactory { 25 | 26 | private OperatingSystemFactory() { 27 | 28 | } 29 | /* 30 | // One more advantage , tomorrow you planned to change OS here , you can simply change this and everything works as is. 31 | 32 | Example creation of object. 33 | OperatingSystem operatingSystem = OperatingSystemFactory.getInstance("WINDOWS" , "WIN7" ,"x64"); 34 | OperatingSystem operatingSystem2 = OperatingSystemFactory.getInstance("LINUX" , "DEB" ,"x64"); 35 | */ 36 | public static OperatingSystem getInstance(String type, String version, String architecture) { 37 | switch (type){ 38 | case "WINDOWS": 39 | return new WindowsOperatingSysten(version,architecture); 40 | case "LINUX": 41 | return new LinuxOperatingSystem(version,architecture); 42 | default: 43 | throw new IllegalArgumentException("OS Not supported"); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /factory/src/main/java/factories/LinuxOperatingSystem.java: -------------------------------------------------------------------------------- 1 | package factories; 2 | 3 | public class LinuxOperatingSystem extends OperatingSystem{ 4 | 5 | public LinuxOperatingSystem(String version, String architecture) { 6 | super(version, architecture); 7 | } 8 | 9 | @Override 10 | public void changeDir(String dir) { 11 | 12 | } 13 | 14 | @Override 15 | public void removeDir(String dir) { 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /factory/src/main/java/factories/OperatingSystem.java: -------------------------------------------------------------------------------- 1 | package factories; 2 | 3 | public abstract class OperatingSystem { 4 | private String version; 5 | private String architecture; 6 | 7 | public String getVersion() { 8 | return version; 9 | } 10 | 11 | public void setVersion(String version) { 12 | this.version = version; 13 | } 14 | 15 | public String getArchitecture() { 16 | return architecture; 17 | } 18 | 19 | public void setArchitecture(String architecture) { 20 | this.architecture = architecture; 21 | } 22 | 23 | public OperatingSystem(String version, String architecture) { 24 | this.version = version; 25 | this.architecture = architecture; 26 | } 27 | 28 | public abstract void changeDir(String dir); 29 | public abstract void removeDir(String dir); 30 | } 31 | -------------------------------------------------------------------------------- /factory/src/main/java/factories/WindowsOperatingSysten.java: -------------------------------------------------------------------------------- 1 | package factories; 2 | 3 | public class WindowsOperatingSysten extends OperatingSystem{ 4 | public WindowsOperatingSysten(String version, String architecture) { 5 | super(version,architecture); 6 | } 7 | 8 | @Override 9 | public void changeDir(String dir) { 10 | //Windows command 11 | } 12 | 13 | @Override 14 | public void removeDir(String dir) { 15 | //Windows command 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /flyweight/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /flyweight/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '3.0.6' 4 | id 'io.spring.dependency-management' version '1.1.0' 5 | } 6 | 7 | group = 'com.dailycodebuffer' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '17' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | dependencies { 16 | implementation 'org.springframework.boot:spring-boot-starter' 17 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 18 | } 19 | 20 | tasks.named('test') { 21 | useJUnitPlatform() 22 | } 23 | -------------------------------------------------------------------------------- /flyweight/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/flyweight/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /flyweight/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /flyweight/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'flyweight' 2 | -------------------------------------------------------------------------------- /flyweight/src/main/java/com/dailycodebuffer/flyweight/DrawingClient.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.flyweight; 2 | 3 | /* 4 | References: https://www.digitalocean.com/community/tutorials/flyweight-design-pattern-java 5 | */ 6 | 7 | import javax.swing.*; 8 | import java.awt.*; 9 | import java.awt.event.ActionEvent; 10 | import java.awt.event.ActionListener; 11 | 12 | import static com.dailycodebuffer.flyweight.ShapeFactory.ShapeType; 13 | 14 | public class DrawingClient extends JFrame { 15 | 16 | private static final long serialVersionUID = -1350200437285282550L; 17 | private final int WIDTH; 18 | private final int HEIGHT; 19 | 20 | private static final ShapeType shapes[] = { ShapeType.LINE, ShapeType.OVAL_FILL,ShapeType.OVAL_NOFILL }; 21 | private static final Color colors[] = { Color.RED, Color.GREEN, Color.YELLOW }; 22 | 23 | public DrawingClient(int width, int height){ 24 | this.WIDTH=width; 25 | this.HEIGHT=height; 26 | Container contentPane = getContentPane(); 27 | 28 | JButton startButton = new JButton("Draw"); 29 | final JPanel panel = new JPanel(); 30 | 31 | contentPane.add(panel, BorderLayout.CENTER); 32 | contentPane.add(startButton, BorderLayout.SOUTH); 33 | setSize(WIDTH, HEIGHT); 34 | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 35 | setVisible(true); 36 | 37 | startButton.addActionListener(new ActionListener() { 38 | public void actionPerformed(ActionEvent event) { 39 | Graphics g = panel.getGraphics(); 40 | for (int i = 0; i < 20; ++i) { 41 | Shape shape = ShapeFactory.getShape(getRandomShape()); 42 | shape.draw(g, getRandomX(), getRandomY(), getRandomWidth(), 43 | getRandomHeight(), getRandomColor()); 44 | } 45 | } 46 | }); 47 | } 48 | 49 | private ShapeType getRandomShape() { 50 | return shapes[(int) (Math.random() * shapes.length)]; 51 | } 52 | 53 | private int getRandomX() { 54 | return (int) (Math.random() * WIDTH); 55 | } 56 | 57 | private int getRandomY() { 58 | return (int) (Math.random() * HEIGHT); 59 | } 60 | 61 | private int getRandomWidth() { 62 | return (int) (Math.random() * (WIDTH / 10)); 63 | } 64 | 65 | private int getRandomHeight() { 66 | return (int) (Math.random() * (HEIGHT / 10)); 67 | } 68 | 69 | private Color getRandomColor() { 70 | return colors[(int) (Math.random() * colors.length)]; 71 | } 72 | 73 | public static void main(String[] args) { 74 | DrawingClient drawing = new DrawingClient(500,600); 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /flyweight/src/main/java/com/dailycodebuffer/flyweight/Line.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.flyweight; 2 | 3 | import java.awt.*; 4 | 5 | public class Line implements Shape { 6 | 7 | public Line(){ 8 | System.out.println("Creating Line object"); 9 | //adding time delay 10 | try { 11 | Thread.sleep(2000); 12 | } catch (InterruptedException e) { 13 | e.printStackTrace(); 14 | } 15 | } 16 | @Override 17 | public void draw(Graphics line, int x1, int y1, int x2, int y2, 18 | Color color) { 19 | line.setColor(color); 20 | line.drawLine(x1, y1, x2, y2); 21 | } 22 | 23 | } -------------------------------------------------------------------------------- /flyweight/src/main/java/com/dailycodebuffer/flyweight/Oval.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.flyweight; 2 | 3 | import java.awt.*; 4 | 5 | public class Oval implements Shape { 6 | 7 | //intrinsic property 8 | private boolean fill; 9 | 10 | public Oval(boolean f){ 11 | this.fill=f; 12 | System.out.println("Creating Oval object with fill="+f); 13 | //adding time delay 14 | try { 15 | Thread.sleep(2000); 16 | } catch (InterruptedException e) { 17 | e.printStackTrace(); 18 | } 19 | } 20 | @Override 21 | public void draw(Graphics circle, int x, int y, int width, int height, 22 | Color color) { 23 | circle.setColor(color); 24 | circle.drawOval(x, y, width, height); 25 | if(fill){ 26 | circle.fillOval(x, y, width, height); 27 | } 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /flyweight/src/main/java/com/dailycodebuffer/flyweight/Shape.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.flyweight; 2 | 3 | import java.awt.*; 4 | 5 | public interface Shape { 6 | 7 | public void draw(Graphics g, int x, int y, int width, int height, 8 | Color color); 9 | } 10 | -------------------------------------------------------------------------------- /flyweight/src/main/java/com/dailycodebuffer/flyweight/ShapeFactory.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.flyweight; 2 | 3 | import java.util.HashMap; 4 | 5 | public class ShapeFactory { 6 | 7 | private static final HashMap shapes = new HashMap(); 8 | 9 | public static Shape getShape(ShapeType type) { 10 | Shape shapeImpl = shapes.get(type); 11 | 12 | if (shapeImpl == null) { 13 | if (type.equals(ShapeType.OVAL_FILL)) { 14 | shapeImpl = new Oval(true); 15 | } else if (type.equals(ShapeType.OVAL_NOFILL)) { 16 | shapeImpl = new Oval(false); 17 | } else if (type.equals(ShapeType.LINE)) { 18 | shapeImpl = new Line(); 19 | } 20 | shapes.put(type, shapeImpl); 21 | } 22 | return shapeImpl; 23 | } 24 | 25 | public static enum ShapeType{ 26 | OVAL_FILL,OVAL_NOFILL,LINE; 27 | } 28 | } -------------------------------------------------------------------------------- /flyweight/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /flyweight/src/test/java/com/dailycodebuffer/flyweight/FlyweightApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.flyweight; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class FlyweightApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /interpreter/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /interpreter/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '3.0.6' 4 | id 'io.spring.dependency-management' version '1.1.0' 5 | } 6 | 7 | group = 'com.dailycodebuffer' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '17' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | dependencies { 16 | implementation 'org.springframework.boot:spring-boot-starter' 17 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 18 | } 19 | 20 | tasks.named('test') { 21 | useJUnitPlatform() 22 | } 23 | -------------------------------------------------------------------------------- /interpreter/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/interpreter/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /interpreter/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /interpreter/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'interpreter' 2 | -------------------------------------------------------------------------------- /interpreter/src/main/java/com/dailycodebuffer/interpreter/AndExpression.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.interpreter; 2 | 3 | public class AndExpression implements Expression { 4 | 5 | private Expression expr1 = null; 6 | private Expression expr2 = null; 7 | 8 | public AndExpression(Expression expr1, Expression expr2) { 9 | this.expr1 = expr1; 10 | this.expr2 = expr2; 11 | } 12 | 13 | @Override 14 | public boolean interpret(String context) { 15 | return expr1.interpret(context) && expr2.interpret(context); 16 | } 17 | } -------------------------------------------------------------------------------- /interpreter/src/main/java/com/dailycodebuffer/interpreter/Expression.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.interpreter; 2 | 3 | public interface Expression { 4 | public boolean interpret(String context); 5 | } 6 | -------------------------------------------------------------------------------- /interpreter/src/main/java/com/dailycodebuffer/interpreter/InterpreterApplication.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.interpreter; 2 | 3 | /* 4 | References: https://www.tutorialspoint.com/design_pattern/interpreter_pattern.htm 5 | */ 6 | public class InterpreterApplication { 7 | 8 | //Rule: Robert and John are male 9 | public static Expression getMaleExpression(){ 10 | Expression robert = new TerminalExpression("Robert"); 11 | Expression john = new TerminalExpression("John"); 12 | return new OrExpression(robert, john); 13 | } 14 | 15 | //Rule: Julie is a married women 16 | public static Expression getMarriedWomanExpression(){ 17 | Expression julie = new TerminalExpression("Julie"); 18 | Expression married = new TerminalExpression("Married"); 19 | return new AndExpression(julie, married); 20 | } 21 | public static void main(String[] args) { 22 | Expression isMale = getMaleExpression(); 23 | Expression isMarriedWoman = getMarriedWomanExpression(); 24 | 25 | System.out.println("John is male? " + isMale.interpret("John")); 26 | System.out.println("Julie is a married women? " + isMarriedWoman.interpret("Married Julie")); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /interpreter/src/main/java/com/dailycodebuffer/interpreter/OrExpression.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.interpreter; 2 | 3 | public class OrExpression implements Expression { 4 | 5 | private Expression expr1 = null; 6 | private Expression expr2 = null; 7 | 8 | public OrExpression(Expression expr1, Expression expr2) { 9 | this.expr1 = expr1; 10 | this.expr2 = expr2; 11 | } 12 | 13 | @Override 14 | public boolean interpret(String context) { 15 | return expr1.interpret(context) || expr2.interpret(context); 16 | } 17 | } -------------------------------------------------------------------------------- /interpreter/src/main/java/com/dailycodebuffer/interpreter/TerminalExpression.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.interpreter; 2 | 3 | public class TerminalExpression implements Expression { 4 | 5 | private String data; 6 | 7 | public TerminalExpression(String data){ 8 | this.data = data; 9 | } 10 | 11 | @Override 12 | public boolean interpret(String context) { 13 | 14 | if(context.contains(data)){ 15 | return true; 16 | } 17 | return false; 18 | } 19 | } -------------------------------------------------------------------------------- /interpreter/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /interpreter/src/test/java/com/dailycodebuffer/interpreter/InterpreterApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.interpreter; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class InterpreterApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /mediator/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /mediator/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '2.7.8' 4 | id 'io.spring.dependency-management' version '1.0.15.RELEASE' 5 | } 6 | 7 | group = 'com.dailycodebuffer' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '11' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | dependencies { 16 | implementation 'org.springframework.boot:spring-boot-starter' 17 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 18 | } 19 | 20 | tasks.named('test') { 21 | useJUnitPlatform() 22 | } 23 | -------------------------------------------------------------------------------- /mediator/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/mediator/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /mediator/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /mediator/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'mediator' 2 | -------------------------------------------------------------------------------- /mediator/src/main/java/com/dailycodebuffer/mediator/ChatMediator.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.mediator; 2 | 3 | /** 4 | * Mediator is a behavioral design pattern that lets you reduce chaotic dependencies between objects. 5 | * The pattern restricts direct communications between the objects and forces them to collaborate only via a mediator object. 6 | * 7 | * References: https://refactoring.guru/design-patterns/mediator 8 | * https://www.digitalocean.com/community/tutorials/mediator-design-pattern-java 9 | */ 10 | public interface ChatMediator { 11 | public void sendMessage(String msg, User user); 12 | 13 | void addUser(User user); 14 | } 15 | -------------------------------------------------------------------------------- /mediator/src/main/java/com/dailycodebuffer/mediator/ChatMediatorImpl.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.mediator; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class ChatMediatorImpl implements ChatMediator{ 7 | private List users; 8 | 9 | public ChatMediatorImpl(){ 10 | this.users=new ArrayList<>(); 11 | } 12 | 13 | @Override 14 | public void addUser(User user){ 15 | this.users.add(user); 16 | } 17 | 18 | @Override 19 | public void sendMessage(String msg, User user) { 20 | for(User u : this.users){ 21 | //message should not be received by the user sending it 22 | if(u != user){ 23 | u.receive(msg); 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /mediator/src/main/java/com/dailycodebuffer/mediator/MediatorApplication.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.mediator; 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | 5 | @SpringBootApplication 6 | public class MediatorApplication { 7 | 8 | public static void main(String[] args) { 9 | ChatMediator mediator = new ChatMediatorImpl(); 10 | User user1 = new UserImpl(mediator, "Nikhil"); 11 | User user2 = new UserImpl(mediator, "Shivam"); 12 | User user3 = new UserImpl(mediator, "Vishrut"); 13 | User user4 = new UserImpl(mediator, "Ali"); 14 | mediator.addUser(user1); 15 | mediator.addUser(user2); 16 | mediator.addUser(user3); 17 | mediator.addUser(user4); 18 | 19 | user1.send("Subscribe to Daily Code Buffer!!"); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /mediator/src/main/java/com/dailycodebuffer/mediator/User.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.mediator; 2 | 3 | public abstract class User { 4 | protected ChatMediator mediator; 5 | protected String name; 6 | 7 | public User(ChatMediator med, String name){ 8 | this.mediator=med; 9 | this.name=name; 10 | } 11 | 12 | public abstract void send(String msg); 13 | 14 | public abstract void receive(String msg); 15 | } 16 | -------------------------------------------------------------------------------- /mediator/src/main/java/com/dailycodebuffer/mediator/UserImpl.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.mediator; 2 | 3 | public class UserImpl extends User { 4 | public UserImpl(ChatMediator med, String name) { 5 | super(med, name); 6 | } 7 | 8 | @Override 9 | public void send(String msg){ 10 | System.out.println(this.name+": Sending Message="+msg); 11 | mediator.sendMessage(msg, this); 12 | } 13 | @Override 14 | public void receive(String msg) { 15 | System.out.println(this.name+": Received Message:"+msg); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /mediator/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /mediator/src/test/java/com/dailycodebuffer/mediator/MediatorApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.mediator; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class MediatorApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /memento/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /memento/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '3.0.6' 4 | id 'io.spring.dependency-management' version '1.1.0' 5 | } 6 | 7 | group = 'com.dailycodebuffer' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '17' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | dependencies { 16 | implementation 'org.springframework.boot:spring-boot-starter' 17 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 18 | } 19 | 20 | tasks.named('test') { 21 | useJUnitPlatform() 22 | } 23 | -------------------------------------------------------------------------------- /memento/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/memento/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /memento/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /memento/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /memento/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'memento' 2 | -------------------------------------------------------------------------------- /memento/src/main/java/com/dailycodebuffer/memento/CareTaker.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.memento; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class CareTaker { 7 | private List mementoList = new ArrayList(); 8 | 9 | public void add(Memento state){ 10 | mementoList.add(state); 11 | } 12 | 13 | public Memento get(int index){ 14 | return mementoList.get(index); 15 | } 16 | } -------------------------------------------------------------------------------- /memento/src/main/java/com/dailycodebuffer/memento/Memento.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.memento; 2 | 3 | public class Memento { 4 | private String state; 5 | 6 | public Memento(String state){ 7 | this.state = state; 8 | } 9 | 10 | public String getState(){ 11 | return state; 12 | } 13 | } -------------------------------------------------------------------------------- /memento/src/main/java/com/dailycodebuffer/memento/MementoApplication.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.memento; 2 | 3 | /* 4 | Resources: https://www.tutorialspoint.com/design_pattern/memento_pattern.htm 5 | https://refactoring.guru/design-patterns/memento 6 | */ 7 | 8 | public class MementoApplication { 9 | 10 | public static void main(String[] args) { 11 | Originator originator = new Originator(); 12 | CareTaker careTaker = new CareTaker(); 13 | 14 | originator.setState("State #1"); 15 | originator.setState("State #2"); 16 | careTaker.add(originator.saveStateToMemento()); 17 | 18 | originator.setState("State #3"); 19 | careTaker.add(originator.saveStateToMemento()); 20 | 21 | originator.setState("State #4"); 22 | System.out.println("Current State: " + originator.getState()); 23 | 24 | originator.getStateFromMemento(careTaker.get(0)); 25 | System.out.println("First saved State: " + originator.getState()); 26 | originator.getStateFromMemento(careTaker.get(1)); 27 | System.out.println("Second saved State: " + originator.getState()); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /memento/src/main/java/com/dailycodebuffer/memento/Originator.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.memento; 2 | 3 | public class Originator { 4 | private String state; 5 | 6 | public void setState(String state){ 7 | this.state = state; 8 | } 9 | 10 | public String getState(){ 11 | return state; 12 | } 13 | 14 | public Memento saveStateToMemento(){ 15 | return new Memento(state); 16 | } 17 | 18 | public void getStateFromMemento(Memento memento){ 19 | state = memento.getState(); 20 | } 21 | } -------------------------------------------------------------------------------- /memento/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /memento/src/test/java/com/dailycodebuffer/memento/MementoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.memento; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class MementoApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /observer/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /observer/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '2.7.8' 4 | id 'io.spring.dependency-management' version '1.0.15.RELEASE' 5 | } 6 | 7 | group = 'com.dailycodebuffer' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '11' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | dependencies { 16 | implementation 'org.springframework.boot:spring-boot-starter' 17 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 18 | } 19 | 20 | tasks.named('test') { 21 | useJUnitPlatform() 22 | } 23 | -------------------------------------------------------------------------------- /observer/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/observer/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /observer/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /observer/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'observer' 2 | -------------------------------------------------------------------------------- /observer/src/main/java/com/dailycodebuffer/observer/Channel.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.observer; 2 | 3 | public interface Channel { 4 | public void update(Object o); 5 | } 6 | -------------------------------------------------------------------------------- /observer/src/main/java/com/dailycodebuffer/observer/NewsAgency.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.observer; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple 8 | * objects about any events that happen to the object they’re observing. 9 | * 10 | * Reference: https://refactoring.guru/design-patterns/observer 11 | * https://www.baeldung.com/java-observer-pattern 12 | * 13 | */ 14 | public class NewsAgency { 15 | private String news; 16 | private List channels = new ArrayList<>(); 17 | 18 | public void addObserver(Channel channel) { 19 | this.channels.add(channel); 20 | } 21 | 22 | public void removeObserver(Channel channel) { 23 | this.channels.remove(channel); 24 | } 25 | 26 | public void setNews(String news) { 27 | this.news = news; 28 | for (Channel channel : this.channels) { 29 | channel.update(this.news); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /observer/src/main/java/com/dailycodebuffer/observer/NewsChannel.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.observer; 2 | 3 | public class NewsChannel implements Channel { 4 | private String news; 5 | 6 | @Override 7 | public void update(Object news) { 8 | this.setNews((String) news); 9 | } 10 | 11 | public String getNews() { 12 | return news; 13 | } 14 | 15 | public void setNews(String news) { 16 | this.news = news; 17 | } 18 | } -------------------------------------------------------------------------------- /observer/src/main/java/com/dailycodebuffer/observer/ObserverApplication.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.observer; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class ObserverApplication { 8 | 9 | public static void main(String[] args) { 10 | NewsAgency observable = new NewsAgency(); 11 | NewsChannel observer = new NewsChannel(); 12 | 13 | observable.addObserver(observer); 14 | observable.setNews("news"); 15 | System.out.println(observer.getNews()); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /observer/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /observer/src/test/java/com/dailycodebuffer/observer/ObserverApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.observer; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class ObserverApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /prototype/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /prototype/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'prototype' 2 | 3 | -------------------------------------------------------------------------------- /prototype/src/main/java/FourWheelerVehicle.java: -------------------------------------------------------------------------------- 1 | public class FourWheelerVehicle extends Vehicle{ 2 | private boolean automatic; 3 | private boolean isDiesel; 4 | 5 | public FourWheelerVehicle(String engine, String model, boolean automatic, long price, boolean isDiesel) { 6 | super(engine, model, price); 7 | this.automatic = automatic; 8 | this.isDiesel = isDiesel; 9 | } 10 | 11 | protected FourWheelerVehicle clone() throws CloneNotSupportedException { 12 | return (FourWheelerVehicle) super.clone(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /prototype/src/main/java/Main.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Prototype pattern comes into creational design pattern. As the name suggest 3 | * As the name state prototype meaning creating object from some reference which we already have. 4 | * It is mainly useful when we have Object which is already created with costly operations at that time we keep that object after creation whenever we need 5 | * new object we simply clone object and tweak or do slight modification in the object and use it. 6 | * In addition to this it is useful when we want to hide the creation of object. 7 | * Here when we say cost of creation which means lets say your object got created by some database operations or io operation. 8 | * 9 | * In cloning its totally upto implementor whether we want to have shallow copy or depp copy while cloning. 10 | * 11 | * There are mainly three components involved in simple Prototype design pattern. 12 | * 1. Prototype : Type of class which has clone method and a super class of all prototypes. 13 | * 2. Sub-Classes - Which implements cloning. 14 | * 3. Client which uses this subclass and clone 15 | * In this additionally you can maintain registry which helps to give you specific prototype. 16 | * In our example lets say we have vehicle and which different types of vehicle , so you can store in 17 | * vehicle registry with different type of vehicles. 18 | * https://simpletechtalks.com/prototype-design-pattern/ 19 | * http://www.jasondeoliveira.com/2011/05/tutorial-common-design-patterns-in-c-40_07.html 20 | * https://reactiveprogramming.io/blog/en/design-patterns/prototype 21 | */ 22 | public class Main { 23 | } 24 | -------------------------------------------------------------------------------- /prototype/src/main/java/TwoWheelerVehicle.java: -------------------------------------------------------------------------------- 1 | public class TwoWheelerVehicle extends Vehicle { 2 | private boolean isElectric; 3 | 4 | 5 | public TwoWheelerVehicle(String engine, String model, long price, boolean isElectric) { 6 | super(engine, model, price); 7 | this.isElectric = isElectric; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /prototype/src/main/java/Vehicle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * This is abstract prototype. 3 | */ 4 | public abstract class Vehicle implements Cloneable { 5 | private String engine; 6 | private String model; 7 | private long price; 8 | 9 | public Vehicle(String engine, String model, long price) { 10 | this.engine = engine; 11 | this.model = model; 12 | this.price = price; 13 | } 14 | 15 | public String getModel() { 16 | return model; 17 | } 18 | 19 | public void setModel(String model) { 20 | this.model = model; 21 | } 22 | 23 | 24 | public long getPrice() { 25 | return price; 26 | } 27 | 28 | public void setPrice(long price) { 29 | this.price = price; 30 | } 31 | 32 | public String getEngine() { 33 | return engine; 34 | } 35 | 36 | public void setEngine(String engine) { 37 | this.engine = engine; 38 | } 39 | 40 | protected Vehicle clone() throws CloneNotSupportedException { 41 | return (Vehicle) super.clone(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /prototype/src/main/java/VehicleRegistry.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class VehicleRegistry { 5 | private static Map mapVehicles = new HashMap<>(); 6 | static { 7 | mapVehicles.put("TWO", new TwoWheelerVehicle("120","royal",100000,false)); 8 | mapVehicles.put("FOUR", new FourWheelerVehicle("120","bmw", false,100000,false)); 9 | 10 | } 11 | public Vehicle getVehicle(String vehicle) throws CloneNotSupportedException { 12 | return mapVehicles.get(vehicle).clone(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /proxy/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'org.example' 6 | version '1.0-SNAPSHOT' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' 14 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' 15 | } 16 | 17 | test { 18 | useJUnitPlatform() 19 | } -------------------------------------------------------------------------------- /proxy/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /proxy/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /proxy/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'proxy' 2 | 3 | -------------------------------------------------------------------------------- /proxy/src/main/java/ATM.java: -------------------------------------------------------------------------------- 1 | public class ATM implements Account{ // This is proxy to bank account object not real 2 | @Override 3 | public void withdraw() { 4 | //Access using actual object. You can also have checks on withdraw to achieve authentication or pin is correct or not. 5 | BankAccount bankAccount = new BankAccount(); 6 | bankAccount.withdraw(); 7 | } 8 | 9 | @Override 10 | public void getAccountNumber() { 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /proxy/src/main/java/Account.java: -------------------------------------------------------------------------------- 1 | public interface Account { 2 | public void withdraw(); 3 | void getAccountNumber(); 4 | } 5 | -------------------------------------------------------------------------------- /proxy/src/main/java/BankAccount.java: -------------------------------------------------------------------------------- 1 | public class BankAccount implements Account{ 2 | @Override 3 | public void withdraw() { 4 | 5 | } 6 | 7 | @Override 8 | public void getAccountNumber() { 9 | 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /proxy/src/main/java/Main.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Proxy pattern : Proxy pattern is structural pattern. We use proxy when we don't want to expose real object and provide proxy object to deal with. 3 | * Many times when you are dealing with remote servers and do lookup from the naming server it provides you proxy object from remote server not actual one. 4 | * Even in hibernate if remember we have concept of lazy loading where whenever we load data from db we get proxy object of 5 | * database and return it however if we get it then only it gets loaded from database. This is one of the best example of proxy object. 6 | * 7 | * Another example can be Spring AOP where AOP objects are proxy and treated on advice aspects. 8 | * 9 | * Different type of proxies are : 10 | * 1. Remote proxy : When you are dealing with remote system , you require remote object to interact with the system. Usually in past it get used in ejb where beans gets created in container 11 | * and client gets object using JNDI system. 12 | * 2. Virtual proxy :Delay the object creation until it is required, as explained hibernate uses this. 13 | * 3. Protection proxy : this proxy is used when we are dealing with security system where before invoking system implementation we want to check access. 14 | * 4. Snart proxy - Perform some additional steps before accessing object. 15 | * 16 | * Proxy pattern has mainly three components : 17 | * 1. A common interface 18 | * 2. Real Class 19 | * 3. Proxy class - this uses the realclass and it is proxy of real class. 20 | * 21 | * https://www.javadevjournal.com/java-design-patterns/proxy-design-pattern/ 22 | * Example consider as Bank Account and ATM where to operate your bank account you have ATM which is proxy of doing process in bank account. 23 | * 24 | */ 25 | public class Main { 26 | public static void main(String[] args) { 27 | ATM atm = new ATM(); 28 | atm.withdraw(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /singleton/.gradle/7.1/dependencies-accessors/dependencies-accessors.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/singleton/.gradle/7.1/dependencies-accessors/dependencies-accessors.lock -------------------------------------------------------------------------------- /singleton/.gradle/7.1/dependencies-accessors/gc.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/singleton/.gradle/7.1/dependencies-accessors/gc.properties -------------------------------------------------------------------------------- /singleton/.gradle/7.1/executionHistory/executionHistory.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/singleton/.gradle/7.1/executionHistory/executionHistory.bin -------------------------------------------------------------------------------- /singleton/.gradle/7.1/executionHistory/executionHistory.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/singleton/.gradle/7.1/executionHistory/executionHistory.lock -------------------------------------------------------------------------------- /singleton/.gradle/7.1/fileChanges/last-build.bin: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /singleton/.gradle/7.1/fileHashes/fileHashes.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/singleton/.gradle/7.1/fileHashes/fileHashes.bin -------------------------------------------------------------------------------- /singleton/.gradle/7.1/fileHashes/fileHashes.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/singleton/.gradle/7.1/fileHashes/fileHashes.lock -------------------------------------------------------------------------------- /singleton/.gradle/7.1/gc.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/singleton/.gradle/7.1/gc.properties -------------------------------------------------------------------------------- /singleton/.gradle/buildOutputCleanup/buildOutputCleanup.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/singleton/.gradle/buildOutputCleanup/buildOutputCleanup.lock -------------------------------------------------------------------------------- /singleton/.gradle/buildOutputCleanup/cache.properties: -------------------------------------------------------------------------------- 1 | #Thu Oct 13 09:08:08 IST 2022 2 | gradle.version=7.1 3 | -------------------------------------------------------------------------------- /singleton/.gradle/buildOutputCleanup/outputFiles.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/singleton/.gradle/buildOutputCleanup/outputFiles.bin -------------------------------------------------------------------------------- /singleton/.gradle/checksums/checksums.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/singleton/.gradle/checksums/checksums.lock -------------------------------------------------------------------------------- /singleton/.gradle/vcs-1/gc.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/singleton/.gradle/vcs-1/gc.properties -------------------------------------------------------------------------------- /singleton/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'org.example' 6 | version '1.0-SNAPSHOT' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' 14 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' 15 | } 16 | 17 | test { 18 | useJUnitPlatform() 19 | } -------------------------------------------------------------------------------- /singleton/build/tmp/compileJava/previous-compilation-data.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/singleton/build/tmp/compileJava/previous-compilation-data.bin -------------------------------------------------------------------------------- /singleton/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /singleton/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /singleton/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'singleton' 2 | 3 | -------------------------------------------------------------------------------- /singleton/src/main/java/EagerSingleton.java: -------------------------------------------------------------------------------- 1 | /** 2 | * This is eager initialization concept where 3 | * as soon as JVM start the object will be created irrespective whether it got accessed by 4 | * any code in application or not. 5 | * When to use : One possible usage can be let say your application has some static cache which is required to be loaded. 6 | * Drawback : As mention consumes resource even if application does not use it. 7 | */ 8 | public class EagerSingleton { 9 | private static final EagerSingleton instance = new EagerSingleton(); 10 | private EagerSingleton() { 11 | // Do your init work here 12 | } 13 | public static EagerSingleton getInstance() { 14 | return instance; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /singleton/src/main/java/EnumSingleton.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Here we described creating singleton using enum but why? 3 | * Let's say in Lazy Init method you access constructor by reflection (Reason being you can access private constructor using reflection!!) 4 | * and create the object which eventually creates the problem by having multiple instances. 5 | * 6 | * ENUM's constructor gets invoked by JVM not by User who is using so it is safe to use. 7 | * Another advantage of using enum is , we don't need to worry about threads as it is thread safe. 8 | * It also solved the problem of Serialization as JVM takes care to return same object. 9 | * 10 | */ 11 | public enum EnumSingleton { 12 | INSTANCE; 13 | public void doSomething() { 14 | System.out.println("Cool"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /singleton/src/main/java/LazySingleton.java: -------------------------------------------------------------------------------- 1 | import java.io.Serializable; 2 | 3 | /** 4 | * Lazy initialization mean application will create instance when it is requested. 5 | * However, this can be used when you have non-thread-safe application. If used in multi threading it might break, 6 | * Why? because your getinstance method if invoked by two thread at same time then!!!! 7 | * 8 | * When to use? Non thread safe and creating common resource like db connection. 9 | * 10 | * 11 | */ 12 | public class LazySingleton implements Serializable { 13 | private static LazySingleton instance = null; 14 | 15 | private LazySingleton() { 16 | 17 | } 18 | 19 | public static LazySingleton getInstance() { 20 | if(instance == null){ 21 | instance = new LazySingleton(); 22 | } 23 | return instance; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /singleton/src/main/java/Main.java: -------------------------------------------------------------------------------- 1 | // References https://www.digitalocean.com/community/tutorials/java-singleton-design-pattern-best-practices-examples 2 | //https://www.geeksforgeeks.org/java-singleton-design-pattern-practices-examples/ 3 | 4 | import java.io.*; 5 | import java.lang.reflect.Constructor; 6 | import java.lang.reflect.InvocationTargetException; 7 | 8 | //Before jumping into pattern just explain what is lazy loading and eager loading 9 | // Mainly this class used to show violations using serializable and reflection. 10 | public class Main { 11 | public static void main(String[] args) throws IOException, ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException { 12 | //exampleSerialization(); 13 | exampleReflection(); 14 | } 15 | private static void exampleSerialization() throws IOException, ClassNotFoundException { 16 | LazySingleton lazySingleton = LazySingleton.getInstance(); 17 | ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("object.obj")); 18 | objectOutputStream.writeObject(lazySingleton); 19 | objectOutputStream.close(); 20 | ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("object.obj")); 21 | LazySingleton deserializedLazy = (LazySingleton) objectInputStream.readObject(); 22 | objectInputStream.close(); 23 | System.out.println("Object 1 :" + lazySingleton.hashCode()); 24 | System.out.println("Object 2 :" + deserializedLazy.hashCode()); 25 | 26 | SerializableSingleton serializableSingleton = SerializableSingleton.getInstance(); 27 | ObjectOutputStream objectOutputStream2 = new ObjectOutputStream(new FileOutputStream("object1.obj")); 28 | objectOutputStream2.writeObject(serializableSingleton); 29 | objectOutputStream2.close(); 30 | ObjectInputStream objectInputStream2 = new ObjectInputStream(new FileInputStream("object1.obj")); 31 | SerializableSingleton deserializedInstance = (SerializableSingleton) objectInputStream2.readObject(); 32 | objectInputStream2.close(); 33 | System.out.println("SerializableSingleton Object 1 :" + serializableSingleton.hashCode()); 34 | System.out.println(" SerializableSingleton Object 2 :" + deserializedInstance.hashCode()); 35 | } 36 | private static void exampleReflection() throws InvocationTargetException, InstantiationException, IllegalAccessException { 37 | Constructor[] constructors = LazySingleton.class.getDeclaredConstructors(); 38 | //Knowing only one constructor taking it using index 39 | Constructor constructor = constructors[0]; 40 | constructor.setAccessible(true); 41 | LazySingleton lazySingleton = (LazySingleton) constructor.newInstance(); 42 | LazySingleton instance = LazySingleton.getInstance(); 43 | System.out.println("Reflected hashcode singleton :"+lazySingleton.hashCode()); 44 | System.out.println("Singleton instance : "+ instance.hashCode()); 45 | 46 | //Solution to this is go by enum 47 | EnumSingleton.INSTANCE.doSomething(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /singleton/src/main/java/MultithreadSingleton.java: -------------------------------------------------------------------------------- 1 | /** 2 | * As mentioned in Lazy Initialization if our get instance method invoked by two thread at the 3 | * same time then there are chances that two objects created, and we violate singleton pattern. 4 | * To avoid we have two choices : 5 | * 1. Create getinstance synchronized so that only one instance can invoke that method. However, disadvantage is lets say 6 | * there are 3 thread t1 is inside getinstance and t2,t3 waiting. Now t2 will get into method and simply return instance created by 7 | * t1 and t3 still waiting. So it had lead to unnecessary of locks. 8 | * 9 | * 2. To avoid we have synchronized block which we will implement here. 10 | */ 11 | public class MultithreadSingleton { 12 | private static MultithreadSingleton instance = null; 13 | private MultithreadSingleton() { 14 | 15 | } 16 | 17 | public static MultithreadSingleton getInstance() { 18 | // Question arise why we have two null check here. 19 | // Reason for first null check is same as explained in method level synchronization why create lock if our object is already created. 20 | if(instance == null) { 21 | // Our method is static, so we have class level locking here 22 | synchronized (MultithreadSingleton.class) { 23 | //Reason for second null check is lets say two object are come inside first null at same time 24 | // One call has taken lock and proceeds for creating object first time. Now once lock is released for t1 25 | // t2 should not create object because its already created and that's why we have second null check. 26 | if(instance == null) { 27 | instance = new MultithreadSingleton(); 28 | } 29 | } 30 | } 31 | return instance; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /singleton/src/main/java/SerializableSingleton.java: -------------------------------------------------------------------------------- 1 | import java.io.Serializable; 2 | 3 | /** 4 | * Let's say your singleton has implemented serialization. Now what will happen if you serialize object and deserialize. 5 | * During deserialization it will create the new object every time if we go in traditional way. 6 | * To resolve it add readResolve method which will ensure that during deserialize we return same instance. 7 | * 8 | * Check Main class for violation example 9 | */ 10 | public class SerializableSingleton implements Serializable { 11 | private static SerializableSingleton instance = null; 12 | private SerializableSingleton() { 13 | 14 | } 15 | 16 | public static SerializableSingleton getInstance() { 17 | if(instance == null) { 18 | instance = new SerializableSingleton(); 19 | } 20 | return instance; 21 | } 22 | 23 | /** 24 | * This is the key method which is responsible during deserialization process 25 | * This method get invoked, and we are simply returning already created object 26 | * @return 27 | */ 28 | protected Object readResolve() { 29 | return instance; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /solid_principles/.gradle/7.1/dependencies-accessors/dependencies-accessors.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/solid_principles/.gradle/7.1/dependencies-accessors/dependencies-accessors.lock -------------------------------------------------------------------------------- /solid_principles/.gradle/7.1/dependencies-accessors/gc.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/solid_principles/.gradle/7.1/dependencies-accessors/gc.properties -------------------------------------------------------------------------------- /solid_principles/.gradle/7.1/executionHistory/executionHistory.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/solid_principles/.gradle/7.1/executionHistory/executionHistory.bin -------------------------------------------------------------------------------- /solid_principles/.gradle/7.1/executionHistory/executionHistory.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/solid_principles/.gradle/7.1/executionHistory/executionHistory.lock -------------------------------------------------------------------------------- /solid_principles/.gradle/7.1/fileChanges/last-build.bin: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /solid_principles/.gradle/7.1/fileHashes/fileHashes.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/solid_principles/.gradle/7.1/fileHashes/fileHashes.bin -------------------------------------------------------------------------------- /solid_principles/.gradle/7.1/fileHashes/fileHashes.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/solid_principles/.gradle/7.1/fileHashes/fileHashes.lock -------------------------------------------------------------------------------- /solid_principles/.gradle/7.1/gc.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/solid_principles/.gradle/7.1/gc.properties -------------------------------------------------------------------------------- /solid_principles/.gradle/buildOutputCleanup/buildOutputCleanup.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/solid_principles/.gradle/buildOutputCleanup/buildOutputCleanup.lock -------------------------------------------------------------------------------- /solid_principles/.gradle/buildOutputCleanup/cache.properties: -------------------------------------------------------------------------------- 1 | #Thu Aug 18 10:04:44 IST 2022 2 | gradle.version=7.1 3 | -------------------------------------------------------------------------------- /solid_principles/.gradle/buildOutputCleanup/outputFiles.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/solid_principles/.gradle/buildOutputCleanup/outputFiles.bin -------------------------------------------------------------------------------- /solid_principles/.gradle/checksums/checksums.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/solid_principles/.gradle/checksums/checksums.lock -------------------------------------------------------------------------------- /solid_principles/.gradle/vcs-1/gc.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/solid_principles/.gradle/vcs-1/gc.properties -------------------------------------------------------------------------------- /solid_principles/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'org.example' 6 | version '1.0-SNAPSHOT' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' 14 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' 15 | } 16 | 17 | test { 18 | useJUnitPlatform() 19 | } -------------------------------------------------------------------------------- /solid_principles/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /solid_principles/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /solid_principles/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'solid_principles' 2 | 3 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/dependencyinversion/bad/AddOperation.java: -------------------------------------------------------------------------------- 1 | package com.solid.dependencyinversion.bad; 2 | 3 | /** 4 | * Lets take similar example which we have in Open Closed. 5 | * Here we are having calculator with add and sub functionality 6 | * and user is sending choice for it. 7 | * This operations are called as sub module in the system 8 | * 9 | */ 10 | public class AddOperation { 11 | public int add(int a, int b){ 12 | return a+b; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/dependencyinversion/bad/Calculator.java: -------------------------------------------------------------------------------- 1 | package com.solid.dependencyinversion.bad; 2 | 3 | /** 4 | * Parent module or main module of calculator which help to calculate 5 | * as per user's choice. 6 | * As per DIP rule it states : 7 | * High-level modules should not depend on low-level modules. Both should depend on abstractions. 8 | * --- So above rule is broken our calculator class is directly dependent on low level class. 9 | * Abstractions should not depend on details. Details should depend on abstractions 10 | * --- Also is dependent on actual class. 11 | */ 12 | public class Calculator { 13 | public int calculate(int a,int b, String operation){ 14 | int result = 0; 15 | switch (operation){ 16 | case "add": 17 | AddOperation addOperation = new AddOperation(); 18 | result = addOperation.add(a,b); 19 | case "sub": 20 | SubOperation subOperation = new SubOperation(); 21 | result = subOperation.sub(a,b); 22 | } 23 | return result; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/dependencyinversion/bad/SubOperation.java: -------------------------------------------------------------------------------- 1 | package com.solid.dependencyinversion.bad; 2 | 3 | /** 4 | * One more sub module for substration 5 | */ 6 | public class SubOperation { 7 | public int sub(int a, int b){ 8 | return a-b; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/dependencyinversion/good/AddOperation.java: -------------------------------------------------------------------------------- 1 | package com.solid.dependencyinversion.good; 2 | 3 | /** 4 | * So we will have this class but it will be taken care 5 | * via interface implementation. 6 | * 7 | */ 8 | public class AddOperation implements CalculatorOperation { 9 | public int calculate(int a, int b){ 10 | return a+b; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/dependencyinversion/good/Calculator.java: -------------------------------------------------------------------------------- 1 | package com.solid.dependencyinversion.good; 2 | 3 | /** 4 | * As per DIP rule it states : 5 | * High-level modules should not depend on low-level modules. Both should depend on abstractions. 6 | * --- So low level is depdendent via CalculatorOperation rather being depend on add or substract operations. 7 | * Abstractions should not depend on details. Details should depend on abstractions 8 | * ---Abstraction is achieved as via interface we are entering in low level. 9 | */ 10 | public class Calculator { 11 | public int calculate(int a,int b, CalculatorOperation operation){ 12 | return operation.calculate(a,b); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/dependencyinversion/good/CalculatorOperation.java: -------------------------------------------------------------------------------- 1 | package com.solid.dependencyinversion.good; 2 | 3 | /** 4 | * This is low level modules interface so anything 5 | * to invoke in lowlevel modules needs to go via this interface 6 | * by this we will achieve both loossely couple between high level and low level moduler 7 | * and abstration as well. 8 | */ 9 | public interface CalculatorOperation { 10 | public int calculate(int a,int b); 11 | } 12 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/dependencyinversion/good/SubOperation.java: -------------------------------------------------------------------------------- 1 | package com.solid.dependencyinversion.good; 2 | 3 | /** 4 | * One more sub module for substration 5 | */ 6 | public class SubOperation implements CalculatorOperation{ 7 | public int calculate(int a, int b){ 8 | return a-b; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/interfacesegregation/BadDAOInterface.java: -------------------------------------------------------------------------------- 1 | package com.solid.interfacesegregation; 2 | 3 | //This dao interface defined to support data access using file system 4 | // or database system. So we have added openConnection and openFile for it 5 | // this bad because we have accomodate all operation in single interface. 6 | public interface BadDAOInterface { 7 | public void openConnection(); 8 | public void createRecord(); 9 | public void openFile(); 10 | public void deleteRecord(); 11 | } 12 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/interfacesegregation/BadDBDaoConnection.java: -------------------------------------------------------------------------------- 1 | package com.solid.interfacesegregation; 2 | 3 | public class BadDBDaoConnection implements BadDAOInterface { 4 | @Override 5 | public void openConnection() { 6 | //Connection logic 7 | } 8 | 9 | @Override 10 | public void createRecord() { 11 | //Create record logic 12 | } 13 | 14 | @Override 15 | public void openFile() { 16 | // We are in DB Connection so no need to support open file 17 | throw new UnsupportedOperationException("Open file Not supported"); 18 | } 19 | 20 | @Override 21 | public void deleteRecord() { 22 | // This is fine 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/interfacesegregation/BadFileDaoConnection.java: -------------------------------------------------------------------------------- 1 | package com.solid.interfacesegregation; 2 | 3 | public class BadFileDaoConnection implements BadDAOInterface{ 4 | @Override 5 | public void openConnection() { 6 | //We can't open connection in file system 7 | } 8 | 9 | @Override 10 | public void createRecord() { 11 | 12 | } 13 | 14 | @Override 15 | public void openFile() { 16 | 17 | } 18 | 19 | @Override 20 | public void deleteRecord() { 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/interfacesegregation/good/DAOInterface.java: -------------------------------------------------------------------------------- 1 | package com.solid.interfacesegregation.good; 2 | 3 | //This is good we will only include the dao operation 4 | // And segregate connection part so consumer can implement required interfaces. 5 | public interface DAOInterface { 6 | public void createRecord(); 7 | public void deleteRecord(); 8 | } 9 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/interfacesegregation/good/DBDaoConnection.java: -------------------------------------------------------------------------------- 1 | package com.solid.interfacesegregation.good; 2 | 3 | //Implemented method what is actual being operated by this. 4 | //We don't had to bother about file operation as interface segregated. 5 | public class DBDaoConnection implements DAOInterface,DBInterface{ 6 | @Override 7 | public void createRecord() { 8 | 9 | } 10 | 11 | @Override 12 | public void deleteRecord() { 13 | 14 | } 15 | 16 | @Override 17 | public void openConnection() { 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/interfacesegregation/good/DBInterface.java: -------------------------------------------------------------------------------- 1 | package com.solid.interfacesegregation.good; 2 | 3 | public interface DBInterface { 4 | public void openConnection(); 5 | } 6 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/interfacesegregation/good/FileDaoConnection.java: -------------------------------------------------------------------------------- 1 | package com.solid.interfacesegregation.good; 2 | //Here dont need to bother about db part. 3 | public class FileDaoConnection implements FileInterface,DAOInterface{ 4 | @Override 5 | public void createRecord() { 6 | 7 | } 8 | 9 | @Override 10 | public void deleteRecord() { 11 | 12 | } 13 | 14 | @Override 15 | public void openFile() { 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/interfacesegregation/good/FileInterface.java: -------------------------------------------------------------------------------- 1 | package com.solid.interfacesegregation.good; 2 | 3 | public interface FileInterface { 4 | public void openFile(); 5 | } 6 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/liskov/bad/CreditCardLoan.java: -------------------------------------------------------------------------------- 1 | package com.solid.liskov.bad; 2 | 3 | public class CreditCardLoan implements LoanPayment{ 4 | @Override 5 | public void doPayment(int amount) { 6 | 7 | } 8 | 9 | @Override 10 | public void foreCloseLoan() { 11 | throw new UnsupportedOperationException("Fore closure is not allowed."); 12 | } 13 | 14 | @Override 15 | public void doRepayment(int amount) { 16 | throw new UnsupportedOperationException("Repayment is not allowed."); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/liskov/bad/HomeLoan.java: -------------------------------------------------------------------------------- 1 | package com.solid.liskov.bad; 2 | 3 | public class HomeLoan implements LoanPayment{ 4 | @Override 5 | public void doPayment(int amount) { 6 | 7 | } 8 | 9 | @Override 10 | public void foreCloseLoan() { 11 | 12 | } 13 | 14 | @Override 15 | public void doRepayment(int amount) { 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/liskov/bad/LoanClosureService.java: -------------------------------------------------------------------------------- 1 | package com.solid.liskov.bad; 2 | 3 | /** 4 | * This is loan closure service which is responsible 5 | * to close the loan before its actual due date. 6 | * Now since credit card is not supporting foreclosure 7 | * it will throw exception which is wrong in design where 8 | * we are unable to substitue subtype with super type.That is violation of 9 | * Liksov Substituation rule. 10 | * Solution to this lets segregate the method in different super types 11 | * and make supertype substituable at any given time. 12 | */ 13 | public class LoanClosureService { 14 | private LoanPayment loanPayment; 15 | 16 | public LoanClosureService(LoanPayment loanPayment) { 17 | this.loanPayment = loanPayment; 18 | } 19 | public void foreCloseLoan() { 20 | loanPayment.foreCloseLoan();; 21 | } 22 | } -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/liskov/bad/LoanPayment.java: -------------------------------------------------------------------------------- 1 | package com.solid.liskov.bad; 2 | 3 | /** 4 | * This is loan interface responsible for payment related operations on loan account 5 | * LoanPayment implemented by actual loans like Home Loan, Credit Card Loan etc. 6 | * For credit card/personal loan which is unsecured foreclosure and repayment is not allowed. 7 | * https://www.baeldung.com/java-liskov-substitution-principle#:~:text=The%20Liskov%20Substitution%20Principle,-4.1.&text=Barbara%20Liskov%2C%20defining%20it%20in,is%20a%20subtype%20of%20T. 8 | */ 9 | public interface LoanPayment { 10 | public void doPayment(int amount); 11 | public void foreCloseLoan(); 12 | public void doRepayment(int amount); 13 | } 14 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/liskov/good/CreditCardLoan.java: -------------------------------------------------------------------------------- 1 | package com.solid.liskov.good; 2 | 3 | public class CreditCardLoan implements LoanPayment { 4 | @Override 5 | public void doPayment(int amount) { 6 | 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/liskov/good/HomeLoan.java: -------------------------------------------------------------------------------- 1 | package com.solid.liskov.good; 2 | 3 | public class HomeLoan implements SecureLoan { 4 | @Override 5 | public void doPayment(int amount) { 6 | 7 | } 8 | 9 | @Override 10 | public void foreCloseLoan() { 11 | 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/liskov/good/LoanClosureService.java: -------------------------------------------------------------------------------- 1 | package com.solid.liskov.good; 2 | 3 | /** 4 | * This is good we are bothered to provide secure loan type 5 | * so this will behave perfectly fine even if we substitute between parent 6 | * and child. 7 | */ 8 | public class LoanClosureService { 9 | private SecureLoan secureLoan; 10 | 11 | public LoanClosureService(SecureLoan secureLoan) { 12 | this.secureLoan = secureLoan; 13 | } 14 | public void foreCloseLoan() { 15 | secureLoan.foreCloseLoan();; 16 | } 17 | } -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/liskov/good/LoanPayment.java: -------------------------------------------------------------------------------- 1 | package com.solid.liskov.good; 2 | 3 | public interface LoanPayment { 4 | public void doPayment(int amount); 5 | } 6 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/liskov/good/SecureLoan.java: -------------------------------------------------------------------------------- 1 | package com.solid.liskov.good; 2 | 3 | 4 | public interface SecureLoan extends LoanPayment { 5 | public void foreCloseLoan(); 6 | } 7 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/openclosed/AddOperation.java: -------------------------------------------------------------------------------- 1 | package com.solid.openclosed; 2 | 3 | public class AddOperation implements Operation{ 4 | @Override 5 | public int perform(int number1, int number2) { 6 | return number1 + number2; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/openclosed/BadCalculator.java: -------------------------------------------------------------------------------- 1 | package com.solid.openclosed; 2 | 3 | //This bad design where we are taking type 4 | // and for each type we are having cases 5 | // now if we want to introduce divison , we have to modify calculator 6 | public class BadCalculator { 7 | public int calculateNumber(int number1 , int number2 , String type){ 8 | int result=0; 9 | switch (type){ 10 | case "sum": 11 | result = number1 + number2; 12 | case "sub": 13 | result = number1 - number2; 14 | } 15 | return result; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/openclosed/Calculator.java: -------------------------------------------------------------------------------- 1 | package com.solid.openclosed; 2 | 3 | // No modifications in our calculator functionality 4 | // We can keep adding extension by create new operations 5 | public class Calculator { 6 | public int calculateNumber(int number1 , int number2 , Operation operation){ 7 | return operation.perform(number1 , number2); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/openclosed/Operation.java: -------------------------------------------------------------------------------- 1 | package com.solid.openclosed; 2 | 3 | // This is good we keep adding new operation implementation 4 | // and our calculator get extensions without modifying it main task 5 | // that is performing calculation 6 | public interface Operation { 7 | public int perform(int number1 , int number2); 8 | } 9 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/openclosed/SubstractOperation.java: -------------------------------------------------------------------------------- 1 | package com.solid.openclosed; 2 | 3 | public class SubstractOperation implements Operation{ 4 | @Override 5 | public int perform(int number1, int number2) { 6 | return number1 - number2; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/singleresponsiblity/Account.java: -------------------------------------------------------------------------------- 1 | package com.solid.singleresponsiblity; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public class Account { 6 | private int accountNumber; 7 | private String firstName; 8 | private BigDecimal totalAmount; 9 | 10 | public int getAccountNumber() { 11 | return accountNumber; 12 | } 13 | 14 | public void setAccountNumber(int accountNumber) { 15 | this.accountNumber = accountNumber; 16 | } 17 | 18 | public String getFirstName() { 19 | return firstName; 20 | } 21 | 22 | public void setFirstName(String firstName) { 23 | this.firstName = firstName; 24 | } 25 | 26 | public BigDecimal getTotalAmount() { 27 | return totalAmount; 28 | } 29 | 30 | public void setTotalAmount(BigDecimal totalAmount) { 31 | this.totalAmount = totalAmount; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/singleresponsiblity/AccountOperations.java: -------------------------------------------------------------------------------- 1 | package com.solid.singleresponsiblity; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class AccountOperations { 7 | private static Map accountMap = new HashMap<>(); 8 | public void addAccount(Account account) { 9 | accountMap.put(account.getAccountNumber() , account); 10 | } 11 | 12 | public void updateAccount(Account account) { 13 | accountMap.put(account.getAccountNumber() , account); 14 | } 15 | 16 | public Account getAccount(int accountNumber) { 17 | return accountMap.get(accountNumber); 18 | } 19 | 20 | /** This method should not be part of AccountOperations 21 | * Reason is account operations are responsible for doing 22 | * operation for account like add account, update account 23 | * get account. However deposit is something called as transaction 24 | * which eventually not responsible by account. 25 | * 26 | * Adding this method violates Single Responsibility principle 27 | * Create new class which actually does TransactionOperations. 28 | * **/ 29 | public void deposit(int amount , int accountNumber){ 30 | //Move this method to different class 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/singleresponsiblity/Main.java: -------------------------------------------------------------------------------- 1 | package com.solid.singleresponsiblity; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | Account account = new Account(); 8 | account.setAccountNumber(123); 9 | account.setFirstName("Vishrut"); 10 | account.setTotalAmount(BigDecimal.valueOf(100000)); 11 | AccountOperations accountOperations = new AccountOperations(); 12 | accountOperations.addAccount(account); 13 | 14 | TransactionOperations transactionOperations = new TransactionOperations(); 15 | transactionOperations.deposit(BigDecimal.valueOf(123),123); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /solid_principles/src/main/java/com/solid/singleresponsiblity/TransactionOperations.java: -------------------------------------------------------------------------------- 1 | package com.solid.singleresponsiblity; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public class TransactionOperations { 6 | // This is good as it does transactions and at right place. 7 | public void deposit(BigDecimal amount , int accountNumber){ 8 | //Getting account details it is job of account operations 9 | AccountOperations accountOperations = new AccountOperations(); 10 | Account account = accountOperations.getAccount(accountNumber); 11 | account.setTotalAmount(account.getTotalAmount().add(amount)); 12 | } 13 | 14 | public void withdraw(BigDecimal amount , int accountNumber){ 15 | AccountOperations accountOperations = new AccountOperations(); 16 | Account account = accountOperations.getAccount(accountNumber); 17 | account.setTotalAmount(account.getTotalAmount().subtract(amount)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /state/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /state/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '3.1.0' 4 | id 'io.spring.dependency-management' version '1.1.0' 5 | } 6 | 7 | group = 'com.dailycodebuffer' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '17' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | dependencies { 16 | implementation 'org.springframework.boot:spring-boot-starter' 17 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 18 | } 19 | 20 | tasks.named('test') { 21 | useJUnitPlatform() 22 | } 23 | -------------------------------------------------------------------------------- /state/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/state/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /state/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /state/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /state/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'state' 2 | -------------------------------------------------------------------------------- /state/src/main/java/com/dailycodebuffer/state/Context.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.state; 2 | 3 | public class Context { 4 | private State state; 5 | 6 | public Context(){ 7 | state = null; 8 | } 9 | 10 | public void setState(State state){ 11 | this.state = state; 12 | } 13 | 14 | public State getState(){ 15 | return state; 16 | } 17 | } -------------------------------------------------------------------------------- /state/src/main/java/com/dailycodebuffer/state/StartState.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.state; 2 | 3 | public class StartState implements State { 4 | 5 | public void doAction(Context context) { 6 | System.out.println("Player is in start state"); 7 | context.setState(this); 8 | } 9 | 10 | public String toString(){ 11 | return "Start State"; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /state/src/main/java/com/dailycodebuffer/state/State.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.state; 2 | 3 | public interface State { 4 | public void doAction(Context context); 5 | } -------------------------------------------------------------------------------- /state/src/main/java/com/dailycodebuffer/state/StateApplication.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.state; 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | 5 | /* 6 | References: https://www.tutorialspoint.com/design_pattern/state_pattern.htm 7 | https://refactoring.guru/design-patterns/state 8 | */ 9 | 10 | @SpringBootApplication 11 | public class StateApplication { 12 | 13 | public static void main(String[] args) { 14 | Context context = new Context(); 15 | 16 | StartState startState = new StartState(); 17 | startState.doAction(context); 18 | 19 | System.out.println(context.getState().toString()); 20 | 21 | StopState stopState = new StopState(); 22 | stopState.doAction(context); 23 | 24 | System.out.println(context.getState().toString()); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /state/src/main/java/com/dailycodebuffer/state/StopState.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.state; 2 | 3 | public class StopState implements State { 4 | 5 | public void doAction(Context context) { 6 | System.out.println("Player is in stop state"); 7 | context.setState(this); 8 | } 9 | 10 | public String toString(){ 11 | return "Stop State"; 12 | } 13 | } -------------------------------------------------------------------------------- /state/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /state/src/test/java/com/dailycodebuffer/state/StateApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.state; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class StateApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /strategy/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /strategy/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '3.1.0' 4 | id 'io.spring.dependency-management' version '1.1.0' 5 | } 6 | 7 | group = 'com.dailycodebuffer' 8 | version = '0.0.1-SNAPSHOT' 9 | 10 | java { 11 | sourceCompatibility = '17' 12 | } 13 | 14 | repositories { 15 | mavenCentral() 16 | } 17 | 18 | dependencies { 19 | implementation 'org.springframework.boot:spring-boot-starter' 20 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 21 | } 22 | 23 | tasks.named('test') { 24 | useJUnitPlatform() 25 | } 26 | -------------------------------------------------------------------------------- /strategy/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/strategy/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /strategy/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /strategy/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'strategy' 2 | -------------------------------------------------------------------------------- /strategy/src/main/java/com/dailycodebuffer/strategy/Context.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.strategy; 2 | 3 | public class Context { 4 | private Strategy strategy; 5 | 6 | public Context(Strategy strategy){ 7 | this.strategy = strategy; 8 | } 9 | 10 | public int executeStrategy(int num1, int num2){ 11 | return strategy.doOperation(num1, num2); 12 | } 13 | } -------------------------------------------------------------------------------- /strategy/src/main/java/com/dailycodebuffer/strategy/OperationAdd.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.strategy; 2 | 3 | public class OperationAdd implements Strategy{ 4 | @Override 5 | public int doOperation(int num1, int num2) { 6 | return num1 + num2; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /strategy/src/main/java/com/dailycodebuffer/strategy/OperationMultiply.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.strategy; 2 | 3 | public class OperationMultiply implements Strategy{ 4 | @Override 5 | public int doOperation(int num1, int num2) { 6 | return num1 * num2; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /strategy/src/main/java/com/dailycodebuffer/strategy/OperationSubtract.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.strategy; 2 | 3 | public class OperationSubtract implements Strategy{ 4 | @Override 5 | public int doOperation(int num1, int num2) { 6 | return num1 - num2; 7 | } 8 | } -------------------------------------------------------------------------------- /strategy/src/main/java/com/dailycodebuffer/strategy/Strategy.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.strategy; 2 | 3 | public interface Strategy { 4 | public int doOperation(int num1, int num2); 5 | } 6 | -------------------------------------------------------------------------------- /strategy/src/main/java/com/dailycodebuffer/strategy/StrategyApplication.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.strategy; 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | 5 | /* 6 | * References: https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm 7 | * https://refactoring.guru/design-patterns/strategy 8 | */ 9 | @SpringBootApplication 10 | public class StrategyApplication { 11 | 12 | public static void main(String[] args) { 13 | Context context = new Context(new OperationAdd()); 14 | System.out.println("10 + 5 = " + context.executeStrategy(10, 5)); 15 | 16 | context = new Context(new OperationSubtract()); 17 | System.out.println("10 - 5 = " + context.executeStrategy(10, 5)); 18 | 19 | context = new Context(new OperationMultiply()); 20 | System.out.println("10 * 5 = " + context.executeStrategy(10, 5)); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /strategy/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /strategy/src/test/java/com/dailycodebuffer/strategy/StrategyApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.strategy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class StrategyApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /template/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /template/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '3.1.0' 4 | id 'io.spring.dependency-management' version '1.1.0' 5 | } 6 | 7 | group = 'com.dailycodebuffer' 8 | version = '0.0.1-SNAPSHOT' 9 | 10 | java { 11 | sourceCompatibility = '17' 12 | } 13 | 14 | repositories { 15 | mavenCentral() 16 | } 17 | 18 | dependencies { 19 | implementation 'org.springframework.boot:spring-boot-starter' 20 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 21 | } 22 | 23 | tasks.named('test') { 24 | useJUnitPlatform() 25 | } 26 | -------------------------------------------------------------------------------- /template/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shabbirdwd53/design_patterns/ac010d8080f2a0b70b1d067a74255c6a5da576fb/template/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /template/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /template/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'template' 2 | -------------------------------------------------------------------------------- /template/src/main/java/com/dailycodebuffer/template/Cricket.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.template; 2 | 3 | public class Cricket extends Game { 4 | 5 | @Override 6 | void endPlay() { 7 | System.out.println("Cricket Game Finished!"); 8 | } 9 | 10 | @Override 11 | void initialize() { 12 | System.out.println("Cricket Game Initialized! Start playing."); 13 | } 14 | 15 | @Override 16 | void startPlay() { 17 | System.out.println("Cricket Game Started. Enjoy the game!"); 18 | } 19 | } -------------------------------------------------------------------------------- /template/src/main/java/com/dailycodebuffer/template/Football.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.template; 2 | 3 | public class Football extends Game { 4 | 5 | @Override 6 | void endPlay() { 7 | System.out.println("Football Game Finished!"); 8 | } 9 | 10 | @Override 11 | void initialize() { 12 | System.out.println("Football Game Initialized! Start playing."); 13 | } 14 | 15 | @Override 16 | void startPlay() { 17 | System.out.println("Football Game Started. Enjoy the game!"); 18 | } 19 | } -------------------------------------------------------------------------------- /template/src/main/java/com/dailycodebuffer/template/Game.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.template; 2 | 3 | public abstract class Game { 4 | abstract void initialize(); 5 | abstract void startPlay(); 6 | abstract void endPlay(); 7 | 8 | //template method 9 | public final void play(){ 10 | 11 | //initialize the game 12 | initialize(); 13 | 14 | //start game 15 | startPlay(); 16 | 17 | //end game 18 | endPlay(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /template/src/main/java/com/dailycodebuffer/template/TemplateApplication.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.template; 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | 5 | /* 6 | * References: https://refactoring.guru/design-patterns/template-method 7 | * https://www.tutorialspoint.com/design_pattern/template_pattern.htm 8 | */ 9 | 10 | 11 | @SpringBootApplication 12 | public class TemplateApplication { 13 | 14 | public static void main(String[] args) { 15 | 16 | Game game = new Cricket(); 17 | game.play(); 18 | System.out.println(); 19 | game = new Football(); 20 | game.play(); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /template/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /template/src/test/java/com/dailycodebuffer/template/TemplateApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.dailycodebuffer.template; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class TemplateApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | --------------------------------------------------------------------------------