From 6cd2d0353a40d132a4945c09a28ee70580408f72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Sepp=C3=A4l=C3=A4?= Date: Sat, 8 Jun 2024 19:54:44 +0300 Subject: [PATCH] docs: Content SEO updates (#2990) * update yaml frontmatter format * update abstract document * update abstract factory * use the new pattern template * acyclic visitor seo * adapter seo * ambassador seo * acl seo * aaa seo * async method invocation seo * balking seo * bridge seo * builder seo * business delegate and bytecode seo * caching seo * callback seo * chain seo * update headings * circuit breaker seo * client session + collecting parameter seo * collection pipeline seo * combinator SEO * command seo * cqrs seo * commander seo * component seo * composite seo * composite entity seo * composite view seo * context object seo * converter seo * crtp seo * currying seo * dao seo * data bus seo * data locality seo * data mapper seo * dto seo * decorator seo * delegation seo * di seo * dirty flag seo * domain model seo * double buffer seo * double checked locking seo * double dispatch seo * dynamic proxy seo * event aggregator seo * event-based asynchronous seo * eda seo * event queue seo * event sourcing seo * execute around seo * extension objects seo * facade seo * factory seo * factory kit seo * factory method seo * fanout/fanin seo * feature toggle seo * filterer seo * fluent interface seo * flux seo * flyweight seo * front controller seo * function composition seo * game loop seo * gateway seo * guarded suspension seo * half-sync/half-async seo * health check seo * hexagonal seo * identity map seo * intercepting filter seo * interpreter seo * iterator seo * layers seo * lazy loading seo * leader election seo * leader/followers seo * lockable object seo * rename and add seo for marker interface * master-worker seo * mediator seo * memento seo * metadata mapping seo * microservice aggregator seo * api gw seo * microservices log aggregration seo * mvc seo * mvi seo * mvp seo * mvvm seo * monad seo * monitor seo * monostate seo * multiton seo * mute idiom seo * naked objects & notification seo * null object seo * object mother seo * object pool seo * observer seo * optimistic locking seo * page controller seo * page object seo * parameter object seo * partial response seo * pipeline seo * poison pill seo * presentation model seo * private class data seo * producer-consumer seo * promise seo * property seo * prototype seo * proxy seo * queue-based load leveling seo * reactor seo * registry seo * repository seo * RAII seo * retry seo * role object seo * saga seo * separated interface seo * serialized entity seo * serialized lob seo * servant seo * server session seo * service layer seo * service locator seo * service to worker seo * sharding seo * single table inheritance seo * singleton seo * spatial partition seo * special case seo * specification seo * state seo * step builder seo * strangler seo * strategy seo * subclass sandbox seo * table module seo * template method seo * throttling seo * tolerant reader seo * trampoline seo * transaction script seo * twin seo * type object seo * unit of work seo * update method seo * value object seo * version number seo * virtual proxy seo * visitor seo * seo enhancements * seo improvements * SEO enhancements * SEO improvements * SEO additions * SEO improvements * more SEO improvements * rename hexagonal + SEO improvements * SEO improvements * more SEO stuff * SEO improvements * SEO optimizations * SEO enhancements * enchance SEO * improve SEO * SEO improvements * update headers --- abstract-document/README.md | 38 ++++----- abstract-factory/README.md | 42 +++++----- active-object/README.md | 42 ++++++---- acyclic-visitor/README.md | 36 +++++---- adapter/README.md | 38 +++++---- ambassador/README.md | 42 +++++----- anti-corruption-layer/README.md | 46 ++++++----- arrange-act-assert/README.md | 34 ++++---- async-method-invocation/README.md | 48 +++++++---- balking/README.md | 32 ++++---- bridge/README.md | 38 ++++----- builder/README.md | 37 +++++---- business-delegate/README.md | 46 ++++++----- bytecode/README.md | 38 +++++---- caching/README.md | 42 +++++----- callback/README.md | 34 ++++---- chain-of-responsibility/README.md | 36 +++++---- circuit-breaker/README.md | 36 +++++---- client-session/README.md | 28 ++++--- collecting-parameter/README.md | 38 +++++---- collection-pipeline/README.md | 36 +++++---- combinator/README.md | 43 +++++----- .../README.md | 36 +++++---- command/README.md | 38 +++++---- commander/README.md | 38 +++++---- component/README.md | 33 ++++---- composite-entity/README.md | 47 ++++++----- composite-view/README.md | 32 ++++---- composite/README.md | 34 ++++---- context-object/README.md | 38 ++++----- converter/README.md | 48 +++++------ .../README.md | 46 +++++------ currying/README.md | 39 ++++----- data-access-object/README.md | 36 +++++---- data-bus/README.md | 37 +++++---- data-locality/README.md | 38 +++++---- data-mapper/README.md | 34 ++++---- data-transfer-object/README.md | 32 ++++---- decorator/README.md | 40 ++++----- delegation/README.md | 30 +++---- dependency-injection/README.md | 34 ++++---- dirty-flag/README.md | 46 ++++++----- domain-model/README.md | 42 +++++----- double-buffer/README.md | 56 ++++++------- double-checked-locking/README.md | 36 +++++---- double-dispatch/README.md | 38 ++++----- dynamic-proxy/README.md | 24 +++--- event-aggregator/README.md | 52 +++++++----- event-based-asynchronous/README.md | 36 +++++---- event-driven-architecture/README.md | 38 ++++----- event-queue/README.md | 35 ++++---- event-sourcing/README.md | 40 +++++---- execute-around/README.md | 44 ++++++---- extension-objects/README.md | 32 ++++---- facade/README.md | 47 ++++++----- factory-kit/README.md | 58 ++++++------- factory-method/README.md | 38 +++++---- factory/README.md | 40 ++++----- fanout-fanin/README.md | 40 ++++----- feature-toggle/README.md | 36 +++++---- filterer/README.md | 46 ++++++----- fluent-interface/README.md | 40 ++++----- flux/README.md | 40 ++++----- flyweight/README.md | 42 +++++----- front-controller/README.md | 40 ++++----- function-composition/README.md | 47 ++++++----- game-loop/README.md | 38 ++++----- gateway/README.md | 36 +++++---- guarded-suspension/README.md | 38 +++++---- half-sync-half-async/README.md | 42 +++++----- health-check/README.md | 32 ++++---- .../README.md | 34 ++++---- .../etc/hexagonal.png | Bin .../etc/hexagonal.ucls | 0 .../etc/hexagonal.urm.puml | 0 {hexagonal => hexagonal-architecture}/pom.xml | 2 +- .../main/java/com/iluwatar/hexagonal/App.java | 0 .../administration/ConsoleAdministration.java | 0 .../ConsoleAdministrationSrv.java | 0 .../ConsoleAdministrationSrvImpl.java | 0 .../hexagonal/banking/InMemoryBank.java | 0 .../iluwatar/hexagonal/banking/MongoBank.java | 0 .../hexagonal/banking/WireTransfers.java | 0 .../database/InMemoryTicketRepository.java | 0 .../database/LotteryTicketRepository.java | 0 .../database/MongoTicketRepository.java | 0 .../domain/LotteryAdministration.java | 0 .../hexagonal/domain/LotteryConstants.java | 0 .../hexagonal/domain/LotteryNumbers.java | 0 .../hexagonal/domain/LotteryService.java | 0 .../hexagonal/domain/LotteryTicket.java | 0 .../domain/LotteryTicketCheckResult.java | 0 .../hexagonal/domain/LotteryTicketId.java | 0 .../hexagonal/domain/LotteryUtils.java | 0 .../hexagonal/domain/PlayerDetails.java | 0 .../hexagonal/eventlog/LotteryEventLog.java | 0 .../hexagonal/eventlog/MongoEventLog.java | 0 .../hexagonal/eventlog/StdOutEventLog.java | 0 .../hexagonal/module/LotteryModule.java | 0 .../module/LotteryTestingModule.java | 0 .../MongoConnectionPropertiesLoader.java | 0 .../hexagonal/sampledata/SampleData.java | 0 .../hexagonal/service/ConsoleLottery.java | 0 .../service/LotteryConsoleService.java | 0 .../service/LotteryConsoleServiceImpl.java | 0 .../java/com/iluwatar/hexagonal/AppTest.java | 0 .../hexagonal/banking/InMemoryBankTest.java | 0 .../hexagonal/banking/MongoBankTest.java | 0 .../InMemoryTicketRepositoryTest.java | 0 .../database/MongoTicketRepositoryTest.java | 0 .../hexagonal/domain/LotteryNumbersTest.java | 0 .../hexagonal/domain/LotteryTest.java | 0 .../domain/LotteryTicketCheckResultTest.java | 0 .../hexagonal/domain/LotteryTicketIdTest.java | 0 .../hexagonal/domain/LotteryTicketTest.java | 0 .../hexagonal/domain/PlayerDetailsTest.java | 0 .../hexagonal/eventlog/MongoEventLogTest.java | 0 .../hexagonal/test/LotteryTestUtils.java | 0 identity-map/README.md | 46 ++++++----- intercepting-filter/README.md | 46 ++++++----- interpreter/README.md | 44 +++++----- iterator/README.md | 42 +++++----- layered-architecture/README.md | 36 +++++---- lazy-loading/README.md | 38 ++++----- leader-election/README.md | 38 ++++----- leader-followers/README.md | 36 +++++---- lockable-object/README.md | 40 ++++----- {marker => marker-interface}/.gitignore | 0 {marker => marker-interface}/README.md | 32 ++++---- .../etc/MarkerDiagram.png | Bin .../etc/MarkerDiagram.ucls | 0 .../etc/marker.urm.puml | 0 {marker => marker-interface}/pom.xml | 2 +- .../src/main/java/App.java | 0 .../src/main/java/Guard.java | 0 .../src/main/java/Permission.java | 0 .../src/main/java/Thief.java | 0 .../src/test/java/AppTest.java | 0 .../src/test/java/GuardTest.java | 0 .../src/test/java/ThiefTest.java | 0 master-worker/README.md | 34 ++++---- mediator/README.md | 32 ++++---- memento/README.md | 45 ++++++----- metadata-mapping/README.md | 34 ++++---- microservices-aggregrator/README.md | 40 ++++----- microservices-api-gateway/README.md | 42 +++++----- microservices-log-aggregation/README.md | 46 ++++++----- model-view-controller/README.md | 42 +++++----- model-view-intent/README.md | 40 ++++----- model-view-presenter/README.md | 34 ++++---- model-view-viewmodel/README.md | 39 ++++----- monad/README.md | 60 +++++++------- monitor/README.md | 37 ++++----- monostate/README.md | 42 +++++----- multiton/README.md | 34 ++++---- mute-idiom/README.md | 48 ++++++----- naked-objects/README.md | 42 +++++----- notification/README.md | 34 ++++---- null-object/README.md | 32 ++++---- object-mother/README.md | 32 ++++---- object-pool/README.md | 34 ++++---- observer/README.md | 34 ++++---- optimistic-offline-lock/README.md | 38 +++++---- page-controller/README.md | 40 ++++----- page-object/README.md | 38 ++++----- parameter-object/README.md | 35 ++++---- partial-response/README.md | 38 +++++---- pipeline/README.md | 40 ++++----- poison-pill/README.md | 36 +++++---- pom.xml | 4 +- presentation-model/README.md | 34 ++++---- private-class-data/README.md | 28 ++++--- producer-consumer/README.md | 40 ++++----- promise/README.md | 34 ++++---- property/README.md | 76 +++++++++--------- prototype/README.md | 34 ++++---- proxy/README.md | 38 ++++----- queue-based-load-leveling/README.md | 42 +++++----- reactor/README.md | 45 ++++++----- registry/README.md | 34 ++++---- repository/README.md | 36 +++++---- .../README.md | 32 ++++---- retry/README.md | 38 +++++---- role-object/README.md | 40 ++++----- saga/README.md | 34 ++++---- separated-interface/README.md | 36 +++++---- serialized-entity/README.md | 32 ++++---- serialized-lob/README.md | 30 +++---- servant/README.md | 34 ++++---- server-session/README.md | 34 ++++---- service-layer/README.md | 44 +++++----- service-locator/README.md | 32 ++++---- service-to-worker/README.md | 34 ++++---- sharding/README.md | 29 ++++--- single-table-inheritance/README.md | 36 +++++---- singleton/README.md | 32 ++++---- spatial-partition/README.md | 36 +++++---- special-case/README.md | 39 ++++----- specification/README.md | 40 +++++---- state/README.md | 30 +++---- step-builder/README.md | 42 +++++----- strangler/README.md | 33 ++++---- strategy/README.md | 38 ++++----- subclass-sandbox/README.md | 38 +++++---- table-module/README.md | 32 ++++---- template-method/README.md | 42 +++++----- throttling/README.md | 34 ++++---- tolerant-reader/README.md | 34 ++++---- trampoline/README.md | 34 ++++---- transaction-script/README.md | 37 +++++---- twin/README.md | 32 ++++---- type-object/README.md | 54 +++++++------ unit-of-work/README.md | 36 +++++---- update-header.sh | 7 ++ update-method/README.md | 37 +++++---- value-object/README.md | 45 ++++++----- version-number/README.md | 36 +++++---- virtual-proxy/README.md | 34 ++++---- visitor/README.md | 38 ++++----- 219 files changed, 3308 insertions(+), 2819 deletions(-) rename {hexagonal => hexagonal-architecture}/README.md (82%) rename {hexagonal => hexagonal-architecture}/etc/hexagonal.png (100%) rename {hexagonal => hexagonal-architecture}/etc/hexagonal.ucls (100%) rename {hexagonal => hexagonal-architecture}/etc/hexagonal.urm.puml (100%) rename {hexagonal => hexagonal-architecture}/pom.xml (98%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/App.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java (100%) rename {hexagonal => hexagonal-architecture}/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java (100%) rename {hexagonal => hexagonal-architecture}/src/test/java/com/iluwatar/hexagonal/AppTest.java (100%) rename {hexagonal => hexagonal-architecture}/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java (100%) rename {hexagonal => hexagonal-architecture}/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java (100%) rename {hexagonal => hexagonal-architecture}/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java (100%) rename {hexagonal => hexagonal-architecture}/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java (100%) rename {hexagonal => hexagonal-architecture}/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java (100%) rename {hexagonal => hexagonal-architecture}/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java (100%) rename {hexagonal => hexagonal-architecture}/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java (100%) rename {hexagonal => hexagonal-architecture}/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java (100%) rename {hexagonal => hexagonal-architecture}/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java (100%) rename {hexagonal => hexagonal-architecture}/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java (100%) rename {hexagonal => hexagonal-architecture}/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java (100%) rename {hexagonal => hexagonal-architecture}/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java (100%) rename {marker => marker-interface}/.gitignore (100%) rename {marker => marker-interface}/README.md (71%) rename {marker => marker-interface}/etc/MarkerDiagram.png (100%) rename {marker => marker-interface}/etc/MarkerDiagram.ucls (100%) rename {marker => marker-interface}/etc/marker.urm.puml (100%) rename {marker => marker-interface}/pom.xml (98%) rename {marker => marker-interface}/src/main/java/App.java (100%) rename {marker => marker-interface}/src/main/java/Guard.java (100%) rename {marker => marker-interface}/src/main/java/Permission.java (100%) rename {marker => marker-interface}/src/main/java/Thief.java (100%) rename {marker => marker-interface}/src/test/java/AppTest.java (100%) rename {marker => marker-interface}/src/test/java/GuardTest.java (100%) rename {marker => marker-interface}/src/test/java/ThiefTest.java (100%) create mode 100755 update-header.sh diff --git a/abstract-document/README.md b/abstract-document/README.md index b96e98dab..1dd521c73 100644 --- a/abstract-document/README.md +++ b/abstract-document/README.md @@ -1,27 +1,29 @@ --- -title: Abstract Document +title: "Abstract Document Pattern in Java: Simplifying Data Handling with Flexibility" +shortTitle: Abstract Document +description: "Explore the Abstract Document design pattern in Java. Learn its intent, explanation, applicability, benefits, and see real-world examples to implement flexible and dynamic data structures." category: Structural language: en tag: - - Abstraction - - Decoupling - - Dynamic typing - - Encapsulation - - Extensibility - - Polymorphism + - Abstraction + - Decoupling + - Dynamic typing + - Encapsulation + - Extensibility + - Polymorphism --- -## Intent +## Intent of Abstract Document Design Pattern -The Abstract Document design pattern is a structural design pattern that aims to provide a consistent way to handle hierarchical and tree-like data structures by defining a common interface for various document types. It separates the core document structure from specific data formats, enabling dynamic updates and simplified maintenance. +The Abstract Document design pattern in Java is a crucial structural design pattern that provides a consistent way to handle hierarchical and tree-like data structures by defining a common interface for various document types. It separates the core document structure from specific data formats, enabling dynamic updates and simplified maintenance. -## Explanation +## Detailed Explanation of Abstract Document Pattern with Real-World Examples -The Abstract Document pattern enables handling additional, non-static properties. This pattern uses concept of traits to enable type safety and separate properties of different classes into set of interfaces. +The Abstract Document design pattern in Java allows dynamic handling of non-static properties. This pattern uses concept of traits to enable type safety and separate properties of different classes into set of interfaces. Real-world example -> Imagine a library system where books can have different formats and attributes: physical books, eBooks, and audiobooks. Each format has unique properties, such as page count for physical books, file size for eBooks, and duration for audiobooks. The Abstract Document design pattern allows the library system to manage these diverse formats flexibly. By using this pattern, the system can store and retrieve properties dynamically, without needing a rigid structure for each book type, making it easier to add new formats or attributes in the future without significant changes to the codebase. +> Consider a library system implementing the Abstract Document design pattern in Java, where books can have diverse formats and attributes: physical books, eBooks, and audiobooks. Each format has unique properties, such as page count for physical books, file size for eBooks, and duration for audiobooks. The Abstract Document design pattern allows the library system to manage these diverse formats flexibly. By using this pattern, the system can store and retrieve properties dynamically, without needing a rigid structure for each book type, making it easier to add new formats or attributes in the future without significant changes to the codebase. In plain words @@ -31,7 +33,7 @@ Wikipedia says > An object-oriented structural design pattern for organizing objects in loosely typed key-value stores and exposing the data using typed views. The purpose of the pattern is to achieve a high degree of flexibility between components in a strongly typed language where new properties can be added to the object-tree on the fly, without losing the support of type-safety. The pattern makes use of traits to separate different properties of a class into different interfaces. -**Programmatic Example** +## Programmatic Example of Abstract Document Pattern in Java Consider a car that consists of multiple parts. However, we don't know if the specific car really has all the parts, or just some of them. Our cars are dynamic and extremely flexible. @@ -177,13 +179,13 @@ The program output: 07:21:57.395 [main] INFO com.iluwatar.abstractdocument.App -- door/Lambo/300 ``` -## Class diagram +## Abstract Document Pattern Class Diagram ![Abstract Document](./etc/abstract-document.png "Abstract Document Traits and Domain") -## Applicability +## When to Use the Abstract Document Pattern in Java -This pattern is particularly useful in scenarios where you have different types of documents that share some common attributes or behaviors, but also have unique attributes or behaviors specific to their individual types. Here are some scenarios where the Abstract Document design pattern can be applicable: +The Abstract Document design pattern is especially beneficial in scenarios requiring management of different document types in Java that share some common attributes or behaviors, but also have unique attributes or behaviors specific to their individual types. Here are some scenarios where the Abstract Document design pattern can be applicable: * Content Management Systems (CMS): In a CMS, you might have various types of content such as articles, images, videos, etc. Each type of content could have shared attributes like creation date, author, and tags, while also having specific attributes like image dimensions for images or video duration for videos. @@ -209,7 +211,7 @@ This pattern is particularly useful in scenarios where you have different types The key idea behind the Abstract Document design pattern is to provide a flexible and extensible way to manage different types of documents or entities with shared and distinct attributes. By defining a common interface and implementing it across various document types, you can achieve a more organized and consistent approach to handling complex data structures. -## Consequences +## Benefits and Trade-offs of Abstract Document Pattern Benefits: @@ -227,7 +229,7 @@ Trade-offs: * Performance: Might introduce slight performance overhead compared to direct data access. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525) diff --git a/abstract-factory/README.md b/abstract-factory/README.md index 263486936..7ec0d60bc 100644 --- a/abstract-factory/README.md +++ b/abstract-factory/README.md @@ -1,28 +1,30 @@ --- -title: Abstract Factory +title: "Abstract Factory Pattern in Java: Mastering Object Creation Elegantly" +shortTitle: Abstract Factory +description: "Learn the Abstract Factory pattern in Java with real-world examples, class diagrams, and tutorials. Understand its intent, applicability, benefits, and known uses to enhance your design pattern knowledge." category: Creational language: en tag: - - Abstraction - - Decoupling - - Gang of Four - - Instantiation - - Polymorphism + - Abstraction + - Decoupling + - Gang of Four + - Instantiation + - Polymorphism --- ## Also known as * Kit -## Intent +## Intent of Abstract Factory Design Pattern -Provide an interface for creating families of related or dependent objects without specifying their concrete classes. +The Abstract Factory pattern in Java provides an interface for creating families of related or dependent objects without specifying their concrete classes, enhancing modularity and flexibility in software design. -## Explanation +## Detailed Explanation of Abstract Factory Pattern with Real-World Examples Real-world example -> Imagine a furniture company that produces various styles of furniture: modern, Victorian, and rustic. Each style includes products like chairs, tables, and sofas. To ensure consistency within each style, the company uses an Abstract Factory pattern. +> Imagine a furniture company that uses the Abstract Factory pattern in Java to produce various styles of furniture: modern, Victorian, and rustic. Each style includes products like chairs, tables, and sofas. To ensure consistency within each style, the company uses an Abstract Factory pattern. > > In this scenario, the Abstract Factory is an interface for creating families of related furniture objects (chairs, tables, sofas). Each concrete factory (ModernFurnitureFactory, VictorianFurnitureFactory, RusticFurnitureFactory) implements the Abstract Factory interface and creates a set of products that match the specific style. This way, clients can create a whole set of modern or Victorian furniture without worrying about the details of their instantiation. This maintains a consistent style and allows easy swapping of one style of furniture for another. @@ -34,9 +36,9 @@ Wikipedia says > The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes -**Programmatic Example** +## Programmatic Example of Abstract Factory in Java -To create a kingdom we need objects with a common theme. The elven kingdom needs an elven king, elven castle, and elven army whereas the orcish kingdom needs an orcish king, orcish castle, and orcish army. There is a dependency between the objects in the kingdom. +To create a kingdom using the Abstract Factory pattern in Java, we need objects with a common theme. The elven kingdom needs an elven king, elven castle, and elven army whereas the orcish kingdom needs an orcish king, orcish castle, and orcish army. There is a dependency between the objects in the kingdom. Translating the kingdom example above. First of all, we have some interfaces and implementation for the objects in the kingdom. @@ -163,13 +165,13 @@ The program output: 07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc king! ``` -## Class diagram +## Abstract Factory Pattern Class Diagram ![Abstract Factory](./etc/abstract-factory.urm.png "Abstract Factory class diagram") -## Applicability +## When to Use the Abstract Factory Pattern in Java -Use the Abstract Factory pattern when: +Use the Abstract Factory pattern in Java when: * The system should be independent of how its products are created, composed, and represented. * You need to configure the system with one of multiple families of products. @@ -180,12 +182,12 @@ Use the Abstract Factory pattern when: * You need to choose which product to use from a family at runtime. * Adding new products or families should not require changes to existing code. -## Tutorials +## Abstract Factory Pattern Java Tutorials * [Abstract Factory Design Pattern in Java (DigitalOcean)](https://www.digitalocean.com/community/tutorials/abstract-factory-design-pattern-in-java) * [Abstract Factory(Refactoring Guru)](https://refactoring.guru/design-patterns/abstract-factory) -## Consequences +## Benefits and Trade-offs of Abstract Factory Pattern Benefits: @@ -203,7 +205,7 @@ Trade-offs: * Indirectness: Client code interacts with products indirectly through factories, potentially reducing transparency. -## Known uses +## Real-World Applications of Abstract Factory Pattern in Java * Java Swing's `LookAndFeel` classes for providing different look-and-feel options. * Various implementations in the Java Abstract Window Toolkit (AWT) for creating different GUI components. @@ -211,13 +213,13 @@ Trade-offs: * [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--) * [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--) -## Related patterns +## Related Java Design Patterns * [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Abstract Factory uses Factory Methods to create products. * [Singleton](https://java-design-patterns.com/patterns/singleton/): Abstract Factory classes are often implemented as Singletons. * [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/): Similar to Abstract Factory but focuses on configuring and managing a set of related objects in a flexible way. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Design Patterns in Java](https://amzn.to/3Syw0vC) diff --git a/active-object/README.md b/active-object/README.md index 19a1fd690..c17cbebd7 100644 --- a/active-object/README.md +++ b/active-object/README.md @@ -1,20 +1,22 @@ --- -title: Active Object +title: "Active Object Pattern in Java: Achieving Efficient Asynchronous Processing" +shortTitle: Active Object +description: "Learn about the Active Object design pattern in Java. This guide covers asynchronous behavior, concurrency, and practical examples to enhance your Java applications' performance." category: Concurrency language: en tag: - - Asynchronous - - Decoupling - - Messaging - - Synchronization - - Thread management + - Asynchronous + - Decoupling + - Messaging + - Synchronization + - Thread management --- -## Intent +## Intent of Active Object Design Pattern -The Active Object design pattern provides a safe and reliable way to implement asynchronous behavior in concurrent systems. It achieves this by encapsulating tasks within objects that have their own thread and message queue. This separation keeps the main thread responsive and avoids issues like direct thread manipulation or shared state access. +The Active Object pattern provides a reliable method for asynchronous processing in Java, ensuring responsive applications and efficient thread management. It achieves this by encapsulating tasks within objects that have their own thread and message queue. This separation keeps the main thread responsive and avoids issues like direct thread manipulation or shared state access. -## Explanation +## Detailed Explanation of Active Object Pattern with Real-World Examples Real-world example @@ -39,7 +41,9 @@ Wikipedia says > * The implementation of the active object method. > * A callback or variable for the client to receive the result. -**Programmatic Example** +## Programmatic Example of Active Object in Java + +This section explains how the Active Object design pattern works in Java, highlighting its use in asynchronous task management and concurrency control. The Orcs are known for their wildness and untameable soul. It seems like they have their own thread of control based on previous behavior. To implement a creature that has its own thread of control mechanism and expose its API only and not the execution itself, we can use the Active Object pattern. @@ -162,24 +166,28 @@ Program output: 09:00:02.504 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 has started to roam in the wastelands. ``` -## Applicability +## When to Use the Active Object Pattern in Java -* When you need to perform long-running operations without blocking the main thread. +Use the Active Object pattern in Java when: + +* when you need to handle asynchronous tasks without blocking the main thread, ensuring better performance and responsiveness. * When you need to interact with external resources asynchronously. * When you want to improve the responsiveness of your application. * When you need to manage concurrent tasks in a modular and maintainable way. -## Tutorials +## Active Object Pattern Java Tutorials * [Android and Java Concurrency: The Active Object Pattern(Douglas Schmidt)](https://www.youtube.com/watch?v=Cd8t2u5Qmvc) -## Known Uses +## Real-World Applications of Active Object Pattern in Java * Real-time trading systems where transaction requests are handled asynchronously. * GUIs where long-running tasks are executed in the background without freezing the user interface. * Game programming to handle concurrent updates to game state or AI computations. -## Consequences +## Benefits and Trade-offs of Active Object Pattern + +Discover the benefits and trade-offs of using the Active Object pattern in Java, including improved thread safety and potential overhead concerns. Benefits: @@ -193,13 +201,13 @@ Trade-offs: * Introduces additional overhead due to message passing and thread management. * May not be suitable for all types of concurrency problems. -## Related patterns +## Related Java Design Patterns * [Command](https://java-design-patterns.com/patterns/command/): Encapsulates a request as an object, similarly to how the Active Object pattern encapsulates method calls. * [Promise](https://java-design-patterns.com/patterns/promise/): Provides a means to retrieve the result of an asynchronous method call, often used in conjunction with Active Object. * [Proxy](https://java-design-patterns.com/patterns/proxy/): The Active Object pattern can use a proxy to handle method invocations asynchronously. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object Software](https://amzn.to/3HYqrBE) * [Concurrent Programming in Java: Design Principles and Patterns](https://amzn.to/498SRVq) diff --git a/acyclic-visitor/README.md b/acyclic-visitor/README.md index 40f656da3..eef18bbed 100644 --- a/acyclic-visitor/README.md +++ b/acyclic-visitor/README.md @@ -1,23 +1,25 @@ --- -title: Acyclic Visitor +title: "Acyclic Visitor Pattern in Java: Streamlining Object Interactions" +shortTitle: Acyclic Visitor +description: "Learn about the Acyclic Visitor pattern in Java. This guide explains how it decouples operations from object hierarchies, providing examples and real-world applications." category: Behavioral language: en tag: - - Decoupling - - Extensibility - - Interface - - Object composition + - Decoupling + - Extensibility + - Interface + - Object composition --- -## Intent +## Intent of Acyclic Visitor Design Pattern -The Acyclic Visitor pattern decouples operations from an object hierarchy, allowing you to add new operations without modifying the object structure directly. +The Acyclic Visitor pattern in Java decouples operations from an object hierarchy, providing a flexible design for various applications. -## Explanation +## Detailed Explanation of Acyclic Visitor Pattern with Real-World Examples Real-world example -> An analogous real-world example of the Acyclic Visitor pattern is a museum guide system. Imagine a museum with various exhibits like paintings, sculptures, and historical artifacts. The museum has different types of guides (audio guide, human guide, virtual reality guide) that provide information about each exhibit. Instead of modifying the exhibits every time a new guide type is introduced, each guide implements an interface to visit different exhibit types. This way, the museum can add new types of guides without altering the existing exhibits, ensuring that the system remains extensible and maintainable without forming any dependency cycles. +> An analogous real-world example of the Acyclic Visitor pattern in Java is a museum guide system, demonstrating the practical application of this design pattern. Imagine a museum with various exhibits like paintings, sculptures, and historical artifacts. The museum has different types of guides (audio guide, human guide, virtual reality guide) that provide information about each exhibit. Instead of modifying the exhibits every time a new guide type is introduced, each guide implements an interface to visit different exhibit types. This way, the museum can add new types of guides without altering the existing exhibits, ensuring that the system remains extensible and maintainable without forming any dependency cycles. In plain words @@ -27,9 +29,9 @@ In plain words > The Acyclic Visitor pattern allows new functions to be added to existing class hierarchies without affecting those hierarchies, and without creating the dependency cycles that are inherent to the GangOfFour VisitorPattern. -**Programmatic Example** +## Programmatic Example of Acyclic Visitor in Java -We have a hierarchy of modem classes. The modems in this hierarchy need to be visited by an external algorithm based on filtering criteria (is it Unix or DOS compatible modem). +In this Java example, we have a hierarchy of modem classes illustrating the Acyclic Visitor pattern. The modems in this hierarchy need to be visited by an external algorithm based on filtering criteria (is it Unix or DOS compatible modem). Here's the `Modem` hierarchy. @@ -136,11 +138,11 @@ Program output: 09:15:11.127 [main] INFO com.iluwatar.acyclicvisitor.ConfigureForUnixVisitor -- Zoom modem used with Unix configurator. ``` -## Class diagram +## Acyclic Visitor Pattern Class Diagram ![Acyclic Visitor](./etc/acyclic-visitor.png "Acyclic Visitor") -## Applicability +## When to Use the Acyclic Visitor Pattern in Java This pattern can be used: @@ -150,11 +152,11 @@ This pattern can be used: * When the visited class hierarchy will be frequently extended with new derivatives of the Element class. * When the recompilation, relinking, retesting or redistribution of the derivatives of Element is very expensive. -## Tutorials +## Acyclic Visitor Pattern Java Tutorials * [The Acyclic Visitor Pattern (Code Crafter)](https://codecrafter.blogspot.com/2012/12/the-acyclic-visitor-pattern.html) -## Consequences +## Benefits and Trade-offs of Acyclic Visitor Pattern Benefits: @@ -167,13 +169,13 @@ Trade-offs: * Increased complexity: Can introduce additional complexity with the need for multiple visitor interfaces. * Maintenance overhead: Modifying the object hierarchy requires updating all visitors. -## Related Patterns +## Related Java Design Patterns * [Composite](https://java-design-patterns.com/patterns/composite/): Often used in conjunction with Acyclic Visitor to allow treating individual objects and compositions uniformly. * [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used alongside to add responsibilities to objects dynamically. * [Visitor](https://java-design-patterns.com/patterns/visitor/): The Acyclic Visitor pattern is a variation of the Visitor pattern that avoids cyclic dependencies. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) diff --git a/adapter/README.md b/adapter/README.md index 8db42d7bd..945de2db0 100644 --- a/adapter/README.md +++ b/adapter/README.md @@ -1,25 +1,27 @@ --- -title: Adapter +title: "Adapter Pattern in Java: Seamless Integration of Incompatible Systems" +shortTitle: Adapter +description: "Learn how the Adapter Design Pattern works in Java with detailed examples and use cases. Understand how it enables compatibility between incompatible interfaces." category: Structural language: en tag: - - Compatibility - - Decoupling - - Gang of Four - - Interface - - Object composition - - Wrapping + - Compatibility + - Decoupling + - Gang of Four + - Interface + - Object composition + - Wrapping --- ## Also known as * Wrapper -## Intent +## Intent of Adapter Design Pattern -The Adapter pattern converts the interface of a class into another interface that clients expect, enabling compatibility. +The Adapter Design Pattern in Java converts the interface of a class into another interface that clients expect, enabling compatibility. -## Explanation +## Detailed Explanation of Adapter Pattern with Real-World Examples Real-world example @@ -33,7 +35,9 @@ Wikipedia says > In software engineering, the adapter pattern is a software design pattern that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code. -**Programmatic Example** +## Programmatic Example of Adapter Pattern in Java + +The Adapter Pattern example in Java shows how a class with an incompatible interface can be adapted to work with another class. Consider a wannabe captain that can only use rowing boats but can't sail at all. @@ -106,29 +110,29 @@ The program outputs: 10:25:08.074 [main] INFO com.iluwatar.adapter.FishingBoat -- The fishing boat is sailing ``` -## Applicability +## When to Use the Adapter Pattern in Java -Use the Adapter pattern when +Use the Adapter pattern in Java when * You want to use an existing class, and its interface does not match the one you need * You want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily have compatible interfaces * You need to use several existing subclasses, but it's impractical to adapt their interface by subclassing everyone. An object adapter can adapt the interface of its parent class. * Most of the applications using third-party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code. -## Tutorials +## Adapter Pattern Java Tutorials * [Using the Adapter Design Pattern in Java (Dzone)](https://dzone.com/articles/adapter-design-pattern-in-java) * [Adapter in Java (Refactoring Guru)](https://refactoring.guru/design-patterns/adapter/java/example) * [The Adapter Pattern in Java (Baeldung)](https://www.baeldung.com/java-adapter-pattern) * [Adapter Design Pattern (GeeksForGeeks)](https://www.geeksforgeeks.org/adapter-pattern/) -## Consequences +## Benefits and Trade-offs of Adapter Pattern Class and object adapters offer different benefits and drawbacks. A class adapter adapts the Adaptee to the Target by binding to a specific Adaptee class, which means it cannot adapt a class and all its subclasses. This type of adapter allows the Adapter to override some of the Adaptee’s behavior because the Adapter is a subclass of the Adaptee. Additionally, it introduces only one object without needing extra pointer indirection to reach the Adaptee. On the other hand, an object adapter allows a single Adapter to work with multiple Adaptees, including the Adaptee and all its subclasses. This type of adapter can add functionality to all Adaptees simultaneously. However, it makes overriding the Adaptee’s behavior more difficult, as it requires subclassing the Adaptee and having the Adapter refer to this subclass instead of the Adaptee itself. -## Real-world examples +## Real-World Applications of Adapter Pattern in Java * `java.io.InputStreamReader` and `java.io.OutputStreamWriter` in the Java IO library. * GUI component libraries that allow for plug-ins or adapters to convert between different GUI component interfaces. @@ -137,7 +141,7 @@ On the other hand, an object adapter allows a single Adapter to work with multip * [java.util.Collections#enumeration()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#enumeration-java.util.Collection-) * [javax.xml.bind.annotation.adapters.XMLAdapter](http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html#marshal-BoundType-) -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/ambassador/README.md b/ambassador/README.md index 4b33cbf27..6f87afae1 100644 --- a/ambassador/README.md +++ b/ambassador/README.md @@ -1,25 +1,23 @@ --- -title: Ambassador +title: "Ambassador Pattern in Java: Simplifying Remote Resource Management" +shortTitle: Ambassador +description: "Explore the Ambassador Pattern in Java, its benefits, use cases, and practical examples. Learn how to decouple and offload common functionalities to improve system performance and maintainability." category: Integration language: en tag: - - API design - - Decoupling - - Fault tolerance - - Proxy - - Resilience - - Scalability + - API design + - Decoupling + - Fault tolerance + - Proxy + - Resilience + - Scalability --- -## Intent +## Intent of Ambassador Design Pattern -Provide a helper service instance on a client and offload common functionality away from a shared resource. +The Ambassador Pattern in Java helps offload common functionalities such as monitoring, logging, and routing from a shared resource to a helper service instance, enhancing performance and maintainability in distributed systems. -## Also known as - -* Sidecar - -## Explanation +## Detailed Explanation of Ambassador Pattern with Real-World Examples Real-world example @@ -35,7 +33,9 @@ Microsoft documentation states > An ambassador service can be thought of as an out-of-process proxy which is co-located with the client. This pattern can be useful for offloading common client connectivity tasks such as monitoring, logging, routing, security (such as TLS), and resiliency patterns in a language agnostic way. It is often used with legacy applications, or other applications that are difficult to modify, in order to extend their networking capabilities. It can also enable a specialized team to implement those features. -**Programmatic Example** +## Programmatic Example of Ambassador Pattern in Java + +In this example of the Ambassador Pattern in Java, we demonstrate how to implement latency checks, logging, and retry mechanisms to improve system reliability. A remote service has many clients accessing a function it provides. The service is a legacy application and is impossible to update. Large numbers of requests from users are causing connectivity issues. New rules for request frequency should be implemented along with latency checks and client-side logging. @@ -175,9 +175,9 @@ Failed to reach remote:(3) Service result:-1 ``` -## Applicability +## When to Use the Ambassador Pattern in Java -* Cloud Native and Microservices Architectures: Especially useful in distributed systems where it's crucial to monitor, log, and secure inter-service communication. +* The Ambassador Pattern is particularly beneficial for Cloud Native and Microservices Architectures in Java. It helps in monitoring, logging, and securing inter-service communication, making it ideal for distributed systems. * Legacy System Integration: Facilitates communication with newer services by handling necessary but non-core functionalities. * Performance Enhancement: Can be used to cache results or compress data to improve communication efficiency. @@ -189,7 +189,7 @@ Typical use cases include: * Offload remote service tasks * Facilitate network connection -## Consequences +## Benefits and Trade-offs of Ambassador Pattern Benefits: @@ -204,7 +204,7 @@ Trade-offs: * Potential Performance Overhead: The additional network hop can introduce latency and overhead, particularly if not optimized. * Deployment Overhead: Requires additional resources and management for deploying and scaling ambassador services. -## Known uses +## Real-World Applications of Ambassador Pattern in Java * Service Mesh Implementations: In a service mesh architecture, like Istio or Linkerd, the Ambassador pattern is often employed as a sidecar proxy that handles inter-service communications. This includes tasks such as service discovery, routing, load balancing, telemetry (metrics and tracing), and security (authentication and authorization). * API Gateways: API gateways can use the Ambassador pattern to encapsulate common functionalities like rate limiting, caching, request shaping, and authentication. This allows backend services to focus on their core business logic without being burdened by these cross-cutting concerns. @@ -216,14 +216,14 @@ Trade-offs: * Network Optimization: For services deployed across different geographical locations or cloud regions, Ambassadors can optimize communication by compressing data, batching requests, or even implementing smart routing to reduce latency and costs. * [Kubernetes-native API gateway for microservices](https://github.com/datawire/ambassador) -## Related patterns +## Related Java Design Patterns * [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/): Often used in conjunction to manage fault tolerance by stopping calls to an unresponsive service. * [Decorator](https://java-design-patterns.com/patterns/decorator/): The decorator pattern is used to add functionality to an object dynamically, while the ambassador pattern is used to offload functionality to a separate object. * [Proxy](https://java-design-patterns.com/patterns/proxy/): Shares similarities with the proxy pattern, but the ambassador pattern specifically focuses on offloading ancillary functionalities. * Sidecar: A similar pattern used in the context of containerized applications, where a sidecar container provides additional functionality to the main application container. -## Credits +## References and Credits * [Building Microservices: Designing Fine-Grained Systems](https://amzn.to/43aGpSR) * [Cloud Native Patterns: Designing Change-tolerant Software](https://amzn.to/3wUAl4O) diff --git a/anti-corruption-layer/README.md b/anti-corruption-layer/README.md index 19eefd980..fdc3edd7a 100644 --- a/anti-corruption-layer/README.md +++ b/anti-corruption-layer/README.md @@ -1,17 +1,19 @@ --- -title: Anti-Corruption Layer +title: "Anti-Corruption Layer Pattern in Java: Ensuring System Integrity Amidst Legacy Systems" +shortTitle: Anti-Corruption Layer +description: "Learn how the Anti-Corruption Layer design pattern helps in decoupling subsystems, preventing data corruption, and facilitating seamless integration in Java applications." category: Integration language: en tag: - - Architecture - - Decoupling - - Integration - - Isolation - - Layered architecture - - Migration - - Modernization - - Refactoring - - Wrapping + - Architecture + - Decoupling + - Integration + - Isolation + - Layered architecture + - Migration + - Modernization + - Refactoring + - Wrapping --- ## Also known as @@ -20,14 +22,16 @@ tag: * Interface layer * Translation layer -## Intent +## Intent of Anti-Corruption Layer Design Pattern -Implement a façade or adapter layer between different subsystems that don't share the same semantics. It translates between different data formats and systems, ensuring that the integration between systems does not lead to corruption of business logic or data integrity. +The Anti-Corruption Layer (ACL) is a crucial design pattern in Java development, particularly for system integration and maintaining data integrity. Implement a façade or adapter layer between different subsystems that don't share the same semantics. It translates between different data formats and systems, ensuring that the integration between systems does not lead to corruption of business logic or data integrity. -## Explanation +## Detailed Explanation of Anti-Corruption Layer Pattern with Real-World Examples Real-world example +> This example demonstrates how the Anti-Corruption Layer ensures seamless integration between legacy systems and modern platforms, crucial for maintaining business logic integrity during system migration. +> > Imagine a large retail company transitioning its inventory management system from an old legacy software to a new modern platform. The legacy system has been in use for decades and contains complex business rules and data formats that are incompatible with the new system. Instead of directly connecting the new system to the legacy one, the company implements an Anti-Corruption Layer (ACL). > > The ACL acts as a mediator, translating and adapting data between the two systems. When the new system requests inventory data, the ACL translates the request into a format the legacy system understands, retrieves the data, and then translates it back into a format suitable for the new system. This approach ensures that the new system remains unaffected by the intricacies of the legacy system, preventing corruption of data and business logic while facilitating a smooth transition. @@ -40,9 +44,9 @@ In plain words > Implement a façade or adapter layer between different subsystems that don't share the same semantics. This layer translates requests that one subsystem makes to the other subsystem. Use this pattern to ensure that an application's design is not limited by dependencies on outside subsystems. This pattern was first described by Eric Evans in Domain-Driven Design. -**Programmatic Example** +## Programmatic Example of Anti-Corruption Layer Pattern in Java -The example shows why the anti-corruption layer is needed. +The ACL design pattern in Java provides an intermediary layer that translates data formats, ensuring that integration between different systems does not lead to data corruption. Here are 2 shop-ordering systems: `Legacy` and `Modern`. @@ -129,7 +133,7 @@ public class LegacyShop { } ``` -## Applicability +## When to Use the Anti-Corruption Layer Pattern in Java Use this pattern when: @@ -139,18 +143,18 @@ Use this pattern when: * In scenarios where different subsystems within a larger system use different data formats or structures * When there is a need to ensure loose coupling between different subsystems or external services to facilitate easier maintenance and scalability -## Tutorials +## Anti-Corruption Layer Pattern Java Tutorials * [Anti-Corruption Layer (Microsoft)](https://learn.microsoft.com/en-us/azure/architecture/patterns/anti-corruption-layer) * [Anti-Corruption Layer Pattern (Amazon)](https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/acl.html) -## Known Uses +## Real-World Applications of Anti-Corruption Layer Pattern in Java * Microservices architectures where individual services must communicate without being tightly coupled to each other’s data schemas * Enterprise systems integration, especially when integrating modern systems with legacy systems * In bounded contexts within Domain-Driven Design (DDD) to maintain the integrity of a domain model when interacting with external systems or subsystems -## Consequences +## Benefits and Trade-offs of Anti-Corruption Layer Pattern Benefits: @@ -164,13 +168,13 @@ Trade-offs: * Requires extra effort in design and implementation to ensure the layer is effective without becoming a bottleneck * Can lead to duplication of models if not carefully managed -## Related Patterns +## Related Java Design Patterns * [Adapter](https://java-design-patterns.com/patterns/adapter/): The Anti-Corruption Layer can be implemented using the Adapter pattern to translate between different data formats or structures * [Facade](https://java-design-patterns.com/patterns/facade/): The Anti-Corruption Layer can be seen as a specialized form of the Facade pattern that is used to isolate different subsystems * [Gateway](https://java-design-patterns.com/patterns/gateway/): The Anti-Corruption Layer can be used as a Gateway to external systems to provide a unified interface -## Credits +## References and Credits * [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3vptcJz) * [Implementing Domain-Driven Design](https://amzn.to/3ISOSRA) diff --git a/arrange-act-assert/README.md b/arrange-act-assert/README.md index 72e317423..a4b7ec8de 100644 --- a/arrange-act-assert/README.md +++ b/arrange-act-assert/README.md @@ -1,24 +1,26 @@ --- -title: Arrange/Act/Assert +title: "Arrange/Act/Assert Pattern in Java: Enhance Testing Clarity and Simplicity" +shortTitle: Arrange/Act/Assert +description: "Learn how to use the Arrange/Act/Assert pattern to structure your unit tests in Java. Improve readability and maintainability of your code with clear testing phases." category: Testing language: en tag: - - Code simplification - - Isolation - - Testing + - Code simplification + - Isolation + - Testing --- ## Also known as * Given/When/Then -## Intent +## Intent of Arrange/Act/Assert Design Pattern -To structure unit tests clearly by dividing them into three distinct sections: setup (Arrange), execution (Act), and verification (Assert). +The Arrange/Act/Assert pattern is essential in unit testing in Java. This testing method structures unit tests clearly by dividing them into three distinct sections: setup (Arrange), execution (Act), and verification (Assert). -## Explanation +## Detailed Explanation of Arrange/Act/Assert Pattern with Real-World Examples -Real world example +Real-world example > Imagine you are organizing a small event. To ensure everything runs smoothly, you follow a pattern similar to Arrange/Act/Assert: > @@ -36,9 +38,9 @@ WikiWikiWeb says > Arrange/Act/Assert is a pattern for arranging and formatting code in UnitTest methods. -**Programmatic Example** +## Programmatic Example of Arrange/Act/Assert Pattern in Java -We need to write comprehensive and clear unit test suite for a class. +We need to write comprehensive and clear unit test suite for a class. Using the Arrange/Act/Assert pattern in Java testing ensures clarity. Let's first introduce our `Cash` class to be unit tested. @@ -121,19 +123,19 @@ class CashAAATest { } ``` -## Applicability +## When to Use the Arrange/Act/Assert Pattern in Java Use Arrange/Act/Assert pattern when * Unit testing, especially within the context of TDD and BDD * Anywhere clarity and structure are needed in test cases -## Known uses +## Real-World Applications of Arrange/Act/Assert Pattern in Java -* Widely adopted in software projects using TDD and BDD methodologies. +* This pattern is particularly useful when practicing TDD and/or BDD methodologies in Java. * Utilized in various programming languages and testing frameworks, such as JUnit (Java), NUnit (.NET), and xUnit frameworks. -## Consequences +## Benefits and Trade-offs of Arrange/Act/Assert Pattern Benefits: @@ -146,11 +148,11 @@ Trade-offs: * May introduce redundancy in tests, as similar arrangements may be repeated across tests. * Some complex tests might not fit neatly into this structure, requiring additional context or setup outside these three phases. -## Related patterns +## Related Java Design Patterns * [Page Object](https://java-design-patterns.com/patterns/page-object/): A pattern for organizing UI tests that can be used in conjunction with Arrange/Act/Assert. -## Credits +## References and Credits * [The Art of Unit Testing: with examples in C#](https://amzn.to/49IbdwO) * [Test Driven Development: By Example](https://amzn.to/3wEwKbF) diff --git a/async-method-invocation/README.md b/async-method-invocation/README.md index 5c4d407a7..9b0e4e43e 100644 --- a/async-method-invocation/README.md +++ b/async-method-invocation/README.md @@ -1,27 +1,31 @@ --- -title: Async Method Invocation +title: "Async Method Invocation Pattern in Java: Elevate Performance with Asynchronous Programming" +shortTitle: Async Method Invocation +description: "Learn about the Async Method Invocation pattern in Java for asynchronous method calls, enhancing concurrency, scalability, and responsiveness in your applications. Explore real-world examples and code implementations." category: Concurrency language: en tag: - - Asynchronous - - Decoupling - - Reactive - - Scalability - - Thread management + - Asynchronous + - Decoupling + - Reactive + - Scalability + - Thread management --- -## Intent - -Asynchronous method invocation is a pattern where the calling thread is not blocked while waiting results of tasks. The pattern provides parallel processing of multiple independent tasks and retrieving the results via callbacks or waiting until everything is done. - ## Also known as * Asynchronous Procedure Call -## Explanation +## Intent of Async Method Invocation Design Pattern + +The Async Method Invocation pattern is designed to enhance concurrency by allowing methods to be called asynchronously. This pattern helps in executing parallel tasks, reducing wait times, and improving system throughput. + +## Detailed Explanation of Async Method Invocation Pattern with Real-World Examples Real-world example +> Asynchronous method invocation enables non-blocking operations, allowing multiple processes to run concurrently. This pattern is particularly useful in applications requiring high scalability and performance, such as web servers and microservices. +> > In the context of space rockets, an analogous example of the Async Method Invocation pattern can be seen in the communication between the mission control center and the onboard systems of the rocket. When mission control sends a command to the rocket to adjust its trajectory or perform a system check, they do not wait idly for the rocket to complete the task and report back. Instead, mission control continues to monitor other aspects of the mission and manage different tasks. The rocket executes the command asynchronously and sends a status update or result back to mission control once the operation is complete. This allows mission control to efficiently manage multiple concurrent operations without being blocked by any single task, similar to how asynchronous method invocation works in software systems. In plain words @@ -32,7 +36,9 @@ Wikipedia says > In multithreaded computer programming, asynchronous method invocation (AMI), also known as asynchronous method calls or the asynchronous pattern is a design pattern in which the call site is not blocked while waiting for the called code to finish. Instead, the calling thread is notified when the reply arrives. Polling for a reply is an undesired option. -**Programmatic Example** +## Programmatic Example of Async Method Invocation Pattern in Java + +Consider a scenario where multiple tasks need to be executed simultaneously. Using the Async Method Invocation pattern, you can initiate these tasks without waiting for each to complete, thus optimizing resource usage and reducing latency. In this example, we are launching space rockets and deploying lunar rovers. @@ -153,7 +159,9 @@ Here's the program console output. 21:47:08.618[main]INFO com.iluwatar.async.method.invocation.App-Space rocket<50>launch complete ``` -## Applicability +## When to Use the Async Method Invocation Pattern in Java + +This pattern is ideal for applications needing to manage multiple parallel tasks efficiently. It is commonly used in scenarios such as handling background processes, improving user interface responsiveness, and managing asynchronous data processing. Use the async method invocation pattern when @@ -162,7 +170,9 @@ Use the async method invocation pattern when * In GUI applications to prevent freezing or unresponsiveness during long-running tasks. * In web applications for non-blocking IO operations. -## Known Uses +## Real-World Applications of Async Method Invocation Pattern in Java + +Many modern applications leverage the Async Method Invocation pattern, including web servers handling concurrent requests, microservices architectures, and systems requiring intensive background processing. * Web servers handling HTTP requests asynchronously to improve throughput and reduce latency. * Desktop and mobile applications using background threads to perform time-consuming operations without blocking the user interface. @@ -172,7 +182,9 @@ Use the async method invocation pattern when * [ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html) * [Task-based Asynchronous Pattern](https://msdn.microsoft.com/en-us/library/hh873175.aspx) -## Consequences +## Benefits and Trade-offs of Async Method Invocation Pattern + +While this pattern offers significant performance benefits, it also introduces complexity in error handling and resource management. Proper implementation is essential to avoid potential pitfalls such as race conditions and deadlocks. Benefits: @@ -186,13 +198,15 @@ Trade-offs: * Resource Management: Requires careful management of threads or execution contexts, which can introduce overhead and potential resource exhaustion issues. * Error Handling: Asynchronous operations can make error handling more complex, as exceptions may occur in different threads or at different times. -Related Patterns: +## Related Java Design Patterns + +The Async Method Invocation pattern often works well with other design patterns like the Command Pattern for encapsulating requests, the Observer Pattern for event handling, and the Promise Pattern for managing asynchronous results. * [Command](https://java-design-patterns.com/patterns/command/): Asynchronous method invocation can be used to implement the Command pattern, where commands are executed asynchronously. * [Observer](https://java-design-patterns.com/patterns/observer/): Asynchronous method invocation can be used to notify observers asynchronously when a subject's state changes. * [Promise](https://java-design-patterns.com/patterns/promise/): The AsyncResult interface can be considered a form of Promise, representing a value that may not be available yet. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3Ti1N4f) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/balking/README.md b/balking/README.md index 7eb2db7a2..f659d278b 100644 --- a/balking/README.md +++ b/balking/README.md @@ -1,19 +1,21 @@ --- -title: Balking +title: "Balking Pattern in Java: Smart Control Over Java Execution" +shortTitle: Balking +description: "Learn the Balking design pattern in Java, a concurrency pattern that prevents code execution in inappropriate states. Discover examples, use cases, and benefits." category: Concurrency language: en tag: - - Concurrency - - Decoupling - - Fault tolerance - - Synchronization + - Concurrency + - Decoupling + - Fault tolerance + - Synchronization --- -## Intent +## Intent of Balking Design Pattern -Balking Pattern is used to prevent an object from executing a certain code if it is in an incomplete or inappropriate state. If the state is not suitable for the action, the method call is ignored (or "balked"). +The Balking Pattern in Java is a concurrency design pattern that prevents an object from executing certain code if it is in an incomplete or inappropriate state. This pattern is crucial for managing state and concurrency in multithreaded Java applications. -## Explanation +## Detailed Explanation of Balking Pattern with Real-World Examples Real-world example @@ -27,7 +29,9 @@ Wikipedia says > The balking pattern is a software design pattern that only executes an action on an object when the object is in a particular state. For example, if an object reads ZIP files and a calling method invokes a get method on the object when the ZIP file is not open, the object would "balk" at the request. -**Programmatic Example** +## Programmatic Example of Balking Pattern in Java + +This example demonstrates the Balking Pattern in a multithreaded Java application, highlighting state management and concurrency control. The Balking Pattern is exemplified by a washing machine's start button that initiates washing only if the machine is idle. This ensures state management and prevents concurrent issues. There's a start-button in a washing machine to initiate the laundry washing. When the washing machine is inactive the button works as expected, but if it's already washing the button does nothing. @@ -114,7 +118,7 @@ Here is the console output of the program. 14:02:52.324 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - 14: Washing completed. ``` -## Applicability +## When to Use the Balking Pattern in Java Use the Balking pattern when @@ -122,12 +126,12 @@ Use the Balking pattern when * Objects are generally only in a state that is prone to balking temporarily but for an unknown amount of time * In multithreaded applications where certain actions should only proceed when specific conditions are met, and those conditions are expected to change over time due to external factors or concurrent operations. -## Known Uses: +## Real-World Applications of Balking Pattern in Java * Resource pooling, where resources are only allocated if they are in a valid state for allocation. * Thread management, where threads only proceed with tasks if certain conditions (like task availability or resource locks) are met. -## Consequences: +## Benefits and Trade-offs of Balking Pattern Benefits: @@ -140,13 +144,13 @@ Trade-offs: * Can introduce complexity by obscuring the conditions under which actions are taken or ignored, potentially making the system harder to debug and understand. * May lead to missed opportunities or actions if the state changes are not properly monitored or if the balking condition is too restrictive. -## Related patterns +## Related Java Design Patterns * [Double-Checked Locking](https://java-design-patterns.com/patterns/double-checked-locking/): Ensures that initialization occurs only when necessary and avoids unnecessary locking, which is related to Balking in terms of conditionally executing logic based on the object's state. * [Guarded Suspension](https://java-design-patterns.com/patterns/guarded-suspension/): Similar in ensuring actions are only performed when an object is in a certain state, but typically involves waiting until the state is valid. * [State](https://java-design-patterns.com/patterns/state/): The State pattern can be used in conjunction with Balking to manage the states and transitions of the object. -## Credits +## References and Credits * [Concurrent Programming in Java : Design Principles and Patterns](https://amzn.to/4dIBqxL) * [Java Concurrency in Practice](https://amzn.to/4aRMruW) diff --git a/bridge/README.md b/bridge/README.md index 90d6b2e5b..9c45078d2 100644 --- a/bridge/README.md +++ b/bridge/README.md @@ -1,28 +1,30 @@ --- -title: Bridge +title: "Bridge Pattern in Java: Decouple Abstraction from Implementation" +shortTitle: Bridge +description: "Learn about the Bridge design pattern in Java. Decouple abstraction from implementation to enhance flexibility and extensibility. Explore real-world examples, class diagrams, and use cases." category: Structural language: en tag: - - Abstraction - - Decoupling - - Extensibility - - Gang of Four - - Object composition + - Abstraction + - Decoupling + - Extensibility + - Gang of Four + - Object composition --- ## Also known as * Handle/Body -## Intent +## Intent of Bridge Design Pattern -Decouple an abstraction from its implementation so that the two can vary independently. +The Bridge design pattern is a structural pattern in Java that decouples an abstraction from its implementation, allowing both to vary independently. This pattern is essential for developing flexible and extensible software systems. -## Explanation +## Detailed Explanation of Bridge Pattern with Real-World Examples Real-world example -> A real-world example of the Bridge design pattern can be found in the remote control and television relationship. +> In Java, the Bridge pattern is commonly used in GUI frameworks, database drivers, and device drivers. For instance, a universal remote control (abstraction) can operate various TV brands (implementations) through a consistent interface. > > Imagine a universal remote control (abstraction) that can operate different brands and types of televisions (implementations). The remote control provides a consistent interface for operations like turning on/off, changing channels, and adjusting the volume. Each television brand or type has its own specific implementation of these operations. By using the Bridge pattern, the remote control interface is decoupled from the television implementations, allowing the remote control to work with any television regardless of its brand or internal workings. This separation allows new television models to be added without changing the remote control's code, and different remote controls can be developed to work with the same set of televisions. @@ -34,7 +36,7 @@ Wikipedia says > The bridge pattern is a design pattern used in software engineering that is meant to "decouple an abstraction from its implementation so that the two can vary independently" -**Programmatic Example** +## Programmatic Example of Bridge Pattern in Java Imagine you have a weapon that can have various enchantments, and you need to combine different weapons with different enchantments. How would you handle this? Would you create multiple copies of each weapon, each with a different enchantment, or would you create separate enchantments and apply them to the weapon as needed? The Bridge pattern enables you to do the latter. @@ -201,11 +203,11 @@ The hammer is unwielded. The item's glow fades. ``` -## Class diagram +## Bridge Pattern Class Diagram ![Bridge](./etc/bridge.urm.png "Bridge class diagram") -## Applicability +## When to Use the Bridge Pattern in Java Consider using the Bridge pattern when: @@ -215,17 +217,17 @@ Consider using the Bridge pattern when: * You encounter a large number of classes in your hierarchy, indicating the need to split an object into two parts, a concept referred to as "nested generalizations" by Rumbaugh. * You want to share an implementation among multiple objects, potentially using reference counting, while keeping this detail hidden from the client, as exemplified by Coplien's String class, where multiple objects can share the same string representation. -## Tutorials +## Bridge Pattern Java Tutorials * [Bridge Pattern Tutorial (DigitalOcean)](https://www.digitalocean.com/community/tutorials/bridge-design-pattern-java) -## Known uses +## Real-World Applications of Bridge Pattern in Java * GUI Frameworks where the abstraction is the window, and the implementation could be the underlying OS windowing system. * Database Drivers where the abstraction is a generic database interface, and the implementations are database-specific drivers. * Device Drivers where the abstraction is the device-independent code, and the implementation is the device-dependent code. -## Consequences +## Benefits and Trade-offs of Bridge Pattern Benefits: @@ -238,14 +240,14 @@ Trade-offs: * Increased Complexity: The pattern can complicate the system architecture and code, especially for clients unfamiliar with the pattern. * Runtime Overhead: The extra layer of abstraction can introduce a performance penalty, although it is often negligible in practice. -## Related Patterns +## Related Java Design Patterns * [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): The Abstract Factory pattern can be used along with the Bridge pattern to create platforms that are independent of the concrete classes used to create their objects. * [Adapter](https://java-design-patterns.com/patterns/adapter/): The Adapter pattern is used to provide a different interface to an object, while the Bridge pattern is used to separate an object's interface from its implementation. * [Composite](https://java-design-patterns.com/patterns/composite/): The Bridge pattern is often used with the Composite pattern to model the implementation details of a component. * [Strategy](https://java-design-patterns.com/patterns/strategy/): The Strategy pattern is like the Bridge pattern, but with a different intent. Both patterns are based on composition: Strategy uses composition to change the behavior of a class, while Bridge uses composition to separate an abstraction from its implementation. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) diff --git a/builder/README.md b/builder/README.md index bbeee408c..6a36c334c 100644 --- a/builder/README.md +++ b/builder/README.md @@ -1,21 +1,25 @@ --- -title: Builder +title: "Builder Pattern in Java: Crafting Custom Objects with Clarity" +shortTitle: Builder +description: "Discover the Builder design pattern in Java, a powerful creational pattern that simplifies object construction. Learn how to separate the construction of a complex object from its representation with practical examples and use cases." category: Creational language: en tag: - - Gang of Four - - Instantiation - - Object composition + - Gang of Four + - Instantiation + - Object composition --- -## Intent +## Intent of Builder Design Pattern -Separate the construction of a complex object from its representation so that the same construction process can create different representations. +The Builder design pattern in Java, a fundamental creational pattern, allows for the step-by-step construction of complex objects. It separates the construction of a complex object from its representation so that the same construction process can create different representations. -## Explanation +## Detailed Explanation of Builder Pattern with Real-World Examples Real-world example +> The Java Builder pattern is particularly useful in scenarios where object creation involves numerous parameters. +> > Imagine you are building a customizable sandwich at a deli. The Builder design pattern in this context would involve a SandwichBuilder that allows you to specify each component of the sandwich, such as the type of bread, meat, cheese, vegetables, and condiments. Instead of having to know how to construct the sandwich from scratch, you use the SandwichBuilder to add each desired component step-by-step, ensuring you get exactly the sandwich you want. This separation of construction from the final product representation ensures that the same construction process can yield different types of sandwiches based on the specified components. In plain words @@ -36,7 +40,9 @@ public Hero(Profession profession,String name,HairType hairType,HairColor hairCo As you can see, the number of constructor parameters can quickly become overwhelming, making it difficult to understand their arrangement. Additionally, this list of parameters might continue to grow if you decide to add more options in the future. This is known as the telescoping constructor antipattern. -**Programmatic Example** +## Programmatic Example of Builder Pattern in Java + +In this Java Builder pattern example, we construct different types of `Hero` objects with varying attributes. Imagine a character generator for a role-playing game. The simplest option is to let the computer generate the character for you. However, if you prefer to manually select character details such as profession, gender, hair color, etc., the character creation becomes a step-by-step process that concludes once all selections are made. @@ -140,25 +146,26 @@ Program output: 16:28:06.060 [main] INFO com.iluwatar.builder.App -- This is a thief named Desmond with bald head and wielding a bow. ``` -## Class diagram +## Builder Pattern Class Diagram ![Builder](./etc/builder.urm.png "Builder class diagram") -## Applicability +## When to Use the Builder Pattern in Java Use the Builder pattern when +* The Builder pattern is ideal for Java applications requiring complex object creation. * The algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled * The construction process must allow different representations for the object that's constructed * It's particularly useful when a product requires a lot of steps to be created and when these steps need to be executed in a specific sequence -## Tutorials +## Builder Pattern Java Tutorials * [Builder Design Pattern in Java (DigitalOcean)](https://www.journaldev.com/1425/builder-design-pattern-in-java) * [Builder (Refactoring Guru)](https://refactoring.guru/design-patterns/builder) * [Exploring Joshua Bloch’s Builder design pattern in Java (Java Magazine)](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) -## Known Uses +## Real-World Applications of Builder Pattern in Java * StringBuilder in Java for constructing strings. * java.lang.StringBuffer used to create mutable string objects. @@ -169,7 +176,7 @@ Use the Builder pattern when * [Apache Camel builders](https://github.com/apache/camel/tree/0e195428ee04531be27a0b659005e3aa8d159d23/camel-core/src/main/java/org/apache/camel/builder) * [Apache Commons Option.Builder](https://commons.apache.org/proper/commons-cli/apidocs/org/apache/commons/cli/Option.Builder.html) -## Consequences +## Benefits and Trade-offs of Builder Pattern Benefits: @@ -183,13 +190,13 @@ Trade-offs: * The overall complexity of the code can increase since the pattern requires creating multiple new classes * May increase memory usage due to the necessity of creating multiple builder objects -## Related patterns +## Related Java Design Patterns * [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Can be used in conjunction with Builder to build parts of a complex object. * [Prototype](https://java-design-patterns.com/patterns/prototype/): Builders often create objects from a prototype. * [Step Builder](https://java-design-patterns.com/patterns/step-builder/): It is a variation of the Builder pattern that generates a complex object using a step-by-step approach. The Step Builder pattern is a good choice when you need to build an object with a large number of optional parameters, and you want to avoid the telescoping constructor antipattern. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/business-delegate/README.md b/business-delegate/README.md index c9be5ceff..3a3203b23 100644 --- a/business-delegate/README.md +++ b/business-delegate/README.md @@ -1,27 +1,31 @@ --- -title: Business Delegate +title: "Business Delegate Pattern in Java: Simplifying Business Service Interaction" +shortTitle: Business Delegate +description: "Learn about the Business Delegate pattern in Java. This design pattern adds an abstraction layer between presentation and business tiers, ensuring loose coupling and easier service interaction. Includes examples and class diagrams." category: Structural language: en tag: - - Business - - Decoupling - - Delegation - - Enterprise patterns - - Layered architecture + - Business + - Decoupling + - Delegation + - Enterprise patterns + - Layered architecture --- -## Intent - -The Business Delegate pattern adds an abstraction layer between presentation and business tiers. By using the pattern we gain loose coupling between the tiers and encapsulate knowledge about how to locate, connect to, and interact with the business objects that make up the application. - ## Also known as * Service Representative -## Explanation +## Intent of Business Delegate Design Pattern + +The Business Delegate pattern is a structural design pattern in Java that adds an abstraction layer between the presentation and business tiers. By using the pattern we gain loose coupling between the tiers and encapsulate knowledge about how to locate, connect to, and interact with the business objects that make up the application. + +## Detailed Explanation of Business Delegate Pattern with Real-World Examples Real-world example +> In an Enterprise application using Java EE, the Business Delegate pattern helps manage interactions between different business services. +> > Imagine a restaurant where the waitstaff serves as intermediaries between the customers and the kitchen. When a customer places an order, the waiter takes the order to the kitchen, relays any specific requests, and later brings the prepared food back to the customer. The waitstaff abstracts the complexity of the kitchen operations from the customers, allowing the chefs to focus solely on cooking without needing to interact directly with customers. This setup allows both the customer service (presentation tier) and the kitchen (business service) to operate independently and efficiently. The waitstaff acts as the Business Delegate, managing communication and ensuring smooth interactions between the two distinct areas. In Plain Words @@ -32,7 +36,9 @@ Wikipedia says > Business Delegate is a Java EE design pattern. This pattern is directing to reduce the coupling in between business services and the connected presentation tier, and to hide the implementation details of services (including lookup and accessibility of EJB architecture). Business Delegates acts as an adaptor to invoke business objects from the presentation tier. -**Programmatic Example** +## Programmatic Example of Business Delegate Pattern in Java + +The following Java code demonstrates how to implement the Business Delegate pattern. This pattern is particularly useful in applications requiring loose coupling and efficient service interaction. A mobile phone application promises to stream any movie in existence to your device. It captures the user's search string and passes this on to the Business Delegate. The Business Delegate selects the most suitable video streaming service and plays the video from there. @@ -139,29 +145,29 @@ Here is the console output. 21:15:33.794 [main] INFO com.iluwatar.business.delegate.YouTubeService - YouTubeService is now processing ``` -## Class diagram +## Business Delegate Pattern Class Diagram ![Business Delegate](./etc/business-delegate.urm.png "Business Delegate") -## Applicability +## When to Use the Business Delegate Pattern in Java Use the Business Delegate pattern when -* You want loose coupling between presentation and business tiers +* You need loose coupling between presentation and business tiers or need to abstract service lookups. * You want to orchestrate calls to multiple business services * You want to encapsulate service lookups and service calls * There is a need to abstract and encapsulate the communication between the client tier and business services -## Tutorials +## Business Delegate Pattern Java Tutorials * [Design Patterns - Business Delegate Pattern (TutorialsPoint)](https://www.tutorialspoint.com/design_pattern/business_delegate_pattern.htm) -## Known Uses +## Real-World Applications of Business Delegate Pattern in Java * Enterprise applications using Java EE (Java Platform, Enterprise Edition) * Applications requiring remote access to business services -## Consequences +## Benefits and Trade-offs of Business Delegate Pattern Benefits: @@ -174,13 +180,13 @@ Trade-offs: * Complexity: Introduces additional layers and abstractions, which may increase complexity. * Performance Overhead: The additional indirection may incur a slight performance penalty. -## Related patterns +## Related Java Design Patterns * [Service Locator](https://java-design-patterns.com/patterns/service-locator/): Business Delegate uses Service Locator to locate business services. * [Session Facade](https://java-design-patterns.com/patterns/session-facade/): Business Delegate may use Session Facade to provide a unified interface to a set of business services. * [Composite Entity](https://java-design-patterns.com/patterns/composite-entity/): Business Delegate may use Composite Entity to manage the state of business services. -## Credits +## References and Credits * [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap) * [J2EE Design Patterns](https://amzn.to/4dpzgmx) diff --git a/bytecode/README.md b/bytecode/README.md index 3e53c2127..889354cf3 100644 --- a/bytecode/README.md +++ b/bytecode/README.md @@ -1,21 +1,23 @@ --- -title: Bytecode +title: "Bytecode Pattern in Java: Interpreting Instructions with Custom Virtual Machines" +shortTitle: Bytecode +description: "Explore the Bytecode design pattern in Java, including its implementation, real-world examples, and use cases for efficient virtual machine instruction handling." category: Behavioral language: en tag: - - Abstraction - - Code simplification - - Encapsulation - - Game programming - - Performance - - Runtime + - Abstraction + - Code simplification + - Encapsulation + - Game programming + - Performance + - Runtime --- -## Intent +## Intent of Bytecode Design Pattern -Allows encoding behavior as instructions for a virtual machine. +The Bytecode design pattern in Java allows encoding behavior as instructions for a virtual machine, making it a powerful tool in game development and other applications. -## Explanation +## Detailed Explanation of Bytecode Pattern with Real-World Examples Real-world example @@ -29,7 +31,9 @@ In plain words > An instruction set defines the low-level operations that can be performed. A series of instructions is encoded as a sequence of bytes. A virtual machine executes these instructions one at a time, using a stack for intermediate values. By combining instructions, complex high-level behavior can be defined. -**Programmatic Example** +## Programmatic Example of Bytecode Pattern in Java + +In this programmatic example, we show how the Bytecode pattern in Java can simplify the execution of complex virtual machine instructions through a well-defined set of operations. This real-world example demonstrates how the Bytecode design pattern in Java can streamline game programming by allowing wizards' behavior to be easily adjusted through bytecode instructions. A team is working on a new game where wizards battle against each other. The wizard behavior needs to be carefully adjusted and iterated hundreds of times through playtesting. It's not optimal to ask the programmer to make changes each time the game designer wants to vary the behavior, so the wizard behavior is implemented as a data-driven virtual machine. @@ -220,7 +224,9 @@ Here is the console output. 16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed SET_HEALTH, Stack contains [] ``` -## Applicability +Utilizing the Bytecode design pattern in Java can significantly enhance the flexibility and maintainability of your virtual machine-based applications. + +## When to Use the Bytecode Pattern in Java Use the Bytecode pattern when you have a lot of behavior you need to define and your game’s implementation language isn’t a good fit because: @@ -228,13 +234,13 @@ Use the Bytecode pattern when you have a lot of behavior you need to define and * Iterating on it takes too long due to slow compile times or other tooling issues. * It has too much trust. If you want to ensure the behavior being defined can’t break the game, you need to sandbox it from the rest of the codebase. -## Known Uses +## Real-World Applications of Bytecode Pattern in Java * Java Virtual Machine (JVM) uses bytecode to allow Java programs to run on any device that has JVM installed * Python compiles its scripts to bytecode which is then interpreted by Python Virtual Machine * The .NET Framework uses a form of bytecode called Microsoft Intermediate Language (MSIL) -## Consequences +## Benefits and Trade-offs of Bytecode Pattern Benefits: @@ -247,13 +253,13 @@ Trade-offs: * Overhead: Running bytecode typically involves more overhead than running native code, potentially affecting performance. * Complexity: Implementing and maintaining a VM adds complexity to the system. -## Related patterns +## Related Java Design Patterns * [Interpreter](https://java-design-patterns.com/patterns/interpreter/) is often used within the implementation of VMs to interpret bytecode instructions * [Command](https://java-design-patterns.com/patterns/command/): Bytecode instructions can be seen as commands executed by the VM. * [Factory Method](https://java-design-patterns.com/patterns/factory-method/): VMs may use factory methods to instantiate operations or instructions defined in the bytecode. -## Credits +## References and Credits * [Game Programming Patterns](https://amzn.to/3K96fOn) * [Programming Language Pragmatics](https://amzn.to/49Tusnn) diff --git a/caching/README.md b/caching/README.md index efc4c1f7e..b923da87b 100644 --- a/caching/README.md +++ b/caching/README.md @@ -1,28 +1,30 @@ --- -title: Caching +title: "Caching Pattern in Java: Accelerating Data Access Speeds" +shortTitle: Caching +description: "Learn how to optimize performance with the Java Caching Design Pattern. Explore various caching strategies, real-world examples, and implementation techniques for efficient resource management." category: Performance optimization language: en tag: - - Caching - - Data access - - Performance - - Resource management + - Caching + - Data access + - Performance + - Resource management --- -## Intent - -The caching pattern avoids expensive re-acquisition of resources by not releasing them immediately after use. The resources retain their identity, are kept in some fast-access storage, and are re-used to avoid having to acquire them again. - ## Also known as * Cache * Temporary Storage -## Explanation +## Intent of Caching Design Pattern + +The Java Caching Design Pattern is crucial for performance optimization and resource management. It involves various caching strategies such as write-through, read-through, and LRU cache to ensure efficient data access. The caching pattern avoids expensive re-acquisition of resources by not releasing them immediately after use. The resources retain their identity, are kept in some fast-access storage, and are re-used to avoid having to acquire them again. + +## Detailed Explanation of Caching Pattern with Real-World Examples Real-world example -> A real-world example of the Caching design pattern can be seen in a library's catalog system. When patrons frequently search for popular books, the system can cache the results of these searches. Instead of querying the database every time a user searches for a popular book, the system quickly retrieves the results from the cache. This reduces the load on the database and provides faster response times for users, enhancing their overall experience. However, the system must also ensure that the cache is updated when new books are added or existing ones are checked out, to maintain accurate information. +> A real-world example of the Caching Design Pattern in Java is a library's catalog system. By caching frequently searched book results, the system reduces database load and enhances performance. When patrons frequently search for popular books, the system can cache the results of these searches. Instead of querying the database every time a user searches for a popular book, the system quickly retrieves the results from the cache. This reduces the load on the database and provides faster response times for users, enhancing their overall experience. However, the system must also ensure that the cache is updated when new books are added or existing ones are checked out, to maintain accurate information. In plain words @@ -32,7 +34,9 @@ Wikipedia says > In computing, a cache is a hardware or software component that stores data so that future requests for that data can be served faster; the data stored in a cache might be the result of an earlier computation or a copy of data stored elsewhere. A cache hit occurs when the requested data can be found in a cache, while a cache miss occurs when it cannot. Cache hits are served by reading data from the cache, which is faster than recomputing a result or reading from a slower data store; thus, the more requests that can be served from the cache, the faster the system performs. -**Programmatic Example** +## Programmatic Example of Caching Pattern in Java + +In this programmatic example, we demonstrate different Java caching strategies, including write-through, write-around, and write-behind, using a user account management system. A team is working on a website that provides new homes for abandoned cats. People can post their cats on the website after registering, but all the new posts require approval from one of the site moderators. The user accounts of the site moderators contain a specific flag and the data is stored in a MongoDB database. Checking for the moderator flag each time a post is viewed becomes expensive, and it's a good idea to utilize caching here. @@ -66,7 +70,7 @@ public interface DbManager { } ``` -In the example, we are demonstrating various different caching policies +In the example, we are demonstrating various different caching policies. The following caching strategies are implemented in Java: Write-through, Write-around, Write-behind, and Cache-aside. Each strategy offers unique benefits for improving performance and reducing load on the database. * Write-through writes data to the cache and DB in a single transaction * Write-around writes data immediately into the DB instead of the cache @@ -419,7 +423,9 @@ UserAccount(userId=003, userName=Adam, additionalInfo=He likes food.) 17:00:56.314 [Thread-0] INFO com.iluwatar.caching.CacheStore -- # flushCache... ``` -## Applicability +Implementing the Java Caching Design Pattern using various strategies like LRU cache and write-through caching significantly enhances application performance and scalability. + +## When to Use the Caching Pattern in Java Use the Caching pattern when @@ -427,14 +433,14 @@ Use the Caching pattern when * In scenarios where the cost of recomputing or re-fetching data is significantly higher than storing and retrieving it from cache * For read-heavy applications with relatively static data or data that changes infrequently -## Known Uses +## Real-World Applications of Caching Pattern in Java * Web page caching to reduce server load and improve response time * Database query caching to avoid repeated expensive SQL queries * Caching results of CPU-intensive computations * Content Delivery Networks (CDNs) for caching static resources like images, CSS, and JavaScript files closer to the end users -## Consequences +## Benefits and Trade-offs of Caching Pattern Benefits: @@ -448,14 +454,14 @@ Trade-Offs: * Resource Utilization: Requires additional memory or storage resources to maintain the cache * Stale Data: There's a risk of serving outdated data if the cache is not properly invalidated or updated when the underlying data changes -## Related patterns +## Related Java Design Patterns * [Proxy](https://java-design-patterns.com/patterns/proxy/): Caching can be implemented using the Proxy pattern, where the proxy object intercepts requests and returns cached data if available * [Observer](https://java-design-patterns.com/patterns/observer/): Can be used to notify the cache when the underlying data changes, so that it can be updated or invalidated accordingly * [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used to add caching behavior to an existing object without modifying its code * [Strategy](https://java-design-patterns.com/patterns/strategy/): Different caching strategies can be implemented using the Strategy pattern, allowing the application to switch between them at runtime -## Credits +## References and Credits * [Effective Java](https://amzn.to/4cGk2Jz) * [High Performance Browser Networking](https://amzn.to/3TiNNY4) diff --git a/callback/README.md b/callback/README.md index b383ecebc..1c90cdcea 100644 --- a/callback/README.md +++ b/callback/README.md @@ -1,25 +1,27 @@ --- -title: Callback +title: "Callback Pattern in Java: Mastering Asynchronous Communication" +shortTitle: Callback +description: "Learn about the Java Callback Design Pattern, including its intent, usage scenarios, benefits, trade-offs, and real-world examples. Understand how to implement and effectively use callbacks in your Java applications." category: Functional language: en tag: - - Asynchronous - - Decoupling - - Idiom - - Reactive + - Asynchronous + - Decoupling + - Idiom + - Reactive --- -## Intent - -Callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. - ## Also known as * Call-After * Event-Subscription * Listener -## Explanation +## Intent of Callback Design Pattern + +The Java Callback Design Pattern is a piece of executable code passed as an argument to other code, which is expected to call back (execute) the argument at a convenient time. + +## Detailed Explanation of Callback Pattern with Real-World Examples Real-world example @@ -35,7 +37,7 @@ Wikipedia says > In computer programming, a callback, also known as a "call-after" function, is any executable code that is passed as an argument to other code; that other code is expected to call back (execute) the argument at a given time. -**Programmatic Example** +## Programmatic Example of Callback Pattern in Java We need to be notified after the executing task has finished. We pass a callback method for the executor and wait for it to call back on us. @@ -87,7 +89,7 @@ Program output: 17:12:11.682 [main] INFO com.iluwatar.callback.App -- I'm done now. ``` -## Applicability +## When to Use the Callback Pattern in Java Use the Callback pattern when @@ -95,14 +97,14 @@ Use the Callback pattern when * Implementing notification mechanisms where certain events need to trigger actions in other components. * Decoupling modules or components that need to interact without having a direct dependency on each other -## Known uses +## Real-World Applications of Callback Pattern in Java * GUI frameworks often use callbacks for event handling, such as user interactions (clicks, key presses) * Node.js heavily relies on callbacks for non-blocking I/O operations * Frameworks that deal with asynchronous operations, like Promises in JavaScript, use callbacks to handle the resolution or rejection of asynchronous tasks * [CyclicBarrier](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html#CyclicBarrier%28int,%20java.lang.Runnable%29) constructor can accept a callback that will be triggered every time a barrier is tripped. -## Consequences +## Benefits and Trade-offs of Callback Pattern Benefits: @@ -116,13 +118,13 @@ Trade-offs: * Inversion of control can lead to harder-to-follow code flow, making debugging more challenging * Potential issues with error handling, especially in languages or environments where exceptions are used, as errors might need to be propagated through callbacks -## Related patterns +## Related Java Design Patterns * [Command](https://java-design-patterns.com/patterns/command/): Callbacks can be implemented as Command objects in scenarios where more flexibility or statefulness is required in the callback operation * [Observer](https://java-design-patterns.com/patterns/observer/): Callbacks can be seen as a more dynamic and lightweight form of the Observer pattern, with the ability to subscribe and unsubscribe callback functions dynamically * [Promise](https://java-design-patterns.com/patterns/promise/): In some languages or frameworks, Promises or Futures can be used to handle asynchronous operations more cleanly, often using callbacks for success or failure cases -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/chain-of-responsibility/README.md b/chain-of-responsibility/README.md index 625d98d38..f8c926973 100644 --- a/chain-of-responsibility/README.md +++ b/chain-of-responsibility/README.md @@ -1,12 +1,14 @@ --- -title: Chain of Responsibility +title: "Chain of Responsibility Pattern in Java: Building Robust Request Handling Mechanisms" +shortTitle: Chain of Responsibility +description: "Learn the Chain of Responsibility design pattern in Java with real-world examples, code snippets, and class diagrams. Enhance your coding skills with our detailed explanations." category: Behavioral language: en tag: - - Decoupling - - Event-driven - - Gang of Four - - Messaging + - Decoupling + - Event-driven + - Gang of Four + - Messaging --- ## Also known as @@ -15,15 +17,15 @@ tag: * Chain of Objects * Responsibility Chain -## Intent +## Intent of Chain of Responsibility Design Pattern -Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. +The Chain of Responsibility pattern in Java is a behavioral design pattern that decouples the sender of a request from its receivers by giving more than one object a chance to handle the request. The receiving objects are chained and the request is passed along the chain until an object handles it. -## Explanation +## Detailed Explanation of Chain of Responsibility Pattern with Real-World Examples Real-world example -> An analogous real-world example of the Chain of Responsibility pattern is a technical support call center. When a customer calls in with an issue, the call is first received by a front-line support representative. If the issue is simple, the representative handles it directly. If the issue is more complex, the representative forwards the call to a second-level support technician. This process continues, with the call being escalated through multiple levels of support until it reaches a specialist who can resolve the problem. Each level of support represents a handler in the chain, and the call is passed along the chain until it finds an appropriate handler, thereby decoupling the request from the specific receiver. +> A real-world example of the Chain of Responsibility pattern in Java is a technical support call center. When implementing this Java design pattern, each level of support represents a handler in the chain. When a customer calls in with an issue, the call is first received by a front-line support representative. If the issue is simple, the representative handles it directly. If the issue is more complex, the representative forwards the call to a second-level support technician. This process continues, with the call being escalated through multiple levels of support until it reaches a specialist who can resolve the problem. Each level of support represents a handler in the chain, and the call is passed along the chain until it finds an appropriate handler, thereby decoupling the request from the specific receiver. In plain words @@ -33,7 +35,9 @@ Wikipedia says > In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. -**Programmatic Example** +## Programmatic Example of Chain of Responsibility Pattern + +In this Java example, the Orc King gives orders which are processed by a chain of command representing the Chain of Responsibility pattern. Learn how to implement this design pattern in Java with the following code snippet. The Orc King gives loud orders to his army. The closest one to react is the commander, then an officer, and then a soldier. The commander, officer, and soldier form a chain of responsibility. @@ -155,11 +159,11 @@ Orc officer handling request "torture prisoner" Orc soldier handling request "collect tax" ``` -## Class diagram +## Chain of Responsibility Pattern Class Diagram ![Chain of Responsibility](./etc/chain-of-responsibility.urm.png "Chain of Responsibility class diagram") -## Applicability +## When to Use the Chain of Responsibility Pattern in Java Use Chain of Responsibility when @@ -167,7 +171,7 @@ Use Chain of Responsibility when * You want to issue a request to one of several objects without specifying the receiver explicitly. * The set of objects that can handle a request should be specified dynamically. -## Known uses +## Real-World Applications of Chain of Responsibility Pattern in Java * Event bubbling in GUI frameworks where an event might be handled at multiple levels of a UI component hierarchy * Middleware frameworks where a request passes through a chain of processing objects @@ -176,7 +180,7 @@ Use Chain of Responsibility when * [Apache Commons Chain](https://commons.apache.org/proper/commons-chain/index.html) * [javax.servlet.Filter#doFilter()](http://docs.oracle.com/javaee/7/api/javax/servlet/Filter.html#doFilter-javax.servlet.ServletRequest-javax.servlet.ServletResponse-javax.servlet.FilterChain-) -## Consequences +## Benefits and Trade-offs of Chain of Responsibility Pattern Benefits: @@ -190,13 +194,13 @@ Trade-Offs: * The request might end up unhandled if the chain doesn't include a catch-all handler. * Performance concerns might arise due to potentially going through several handlers before finding the right one, or not finding it at all. -## Related Patterns +## Related Java Design Patterns * [Command](https://java-design-patterns.com/patterns/command/): can be used to encapsulate a request as an object, which might be passed along the chain. * [Composite](https://java-design-patterns.com/patterns/composite/): the Chain of Responsibility is often applied in conjunction with the Composite pattern. * [Decorator](https://java-design-patterns.com/patterns/decorator/): decorators can be chained in a similar manner as responsibilities in the Chain of Responsibility pattern. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) diff --git a/circuit-breaker/README.md b/circuit-breaker/README.md index f5e6b4251..b8e0ff248 100644 --- a/circuit-breaker/README.md +++ b/circuit-breaker/README.md @@ -1,27 +1,29 @@ --- -title: Circuit Breaker +title: "Circuit Breaker Pattern in Java: Enhancing System Resilience" +shortTitle: Circuit Breaker +description: "Learn about the Circuit Breaker pattern in Java design, which ensures fault tolerance and prevents cascading failures in distributed systems and microservices architectures." category: Resilience language: en tag: - - Cloud distributed - - Fault tolerance - - Microservices - - Retry + - Cloud distributed + - Fault tolerance + - Microservices + - Retry --- ## Also known as * Fault Tolerance Switch -## Intent +## Intent of Circuit Breaker Design Pattern -To prevent a system from repeatedly trying to execute an operation likely to fail, allowing it to recover from faults and prevent cascading failures. +The Circuit Breaker pattern is a critical Java design pattern that helps ensure fault tolerance and resilience in microservices and distributed systems. Using Circuit Breaker, it is possible to prevent a system from repeatedly trying to execute an operation likely to fail, allowing it to recover from faults and prevent cascading failures. -## Explanation +## Detailed Explanation of Circuit Breaker Pattern with Real-World Examples Real-world example -> Consider a real-world example of an e-commerce website that depends on multiple external payment gateways to process transactions. If one of the payment gateways becomes unresponsive or slow, the Circuit Breaker pattern can be used to detect the failure and prevent the system from repeatedly attempting to use the problematic gateway. Instead, it can quickly switch to alternative payment gateways or display an error message to the user, ensuring that the rest of the website remains functional and responsive. This avoids resource exhaustion and provides a better user experience by allowing transactions to be processed through other available services. +> Consider a real-world example of an e-commerce website that depends on multiple external payment gateways to process transactions. If one of the payment gateways becomes unresponsive or slow, the Circuit Breaker pattern can be used to detect the failure and prevent the system from repeatedly attempting to use the problematic gateway. Instead, it can quickly switch to alternative payment gateways or display an error message to the user, ensuring that the rest of the website remains functional and responsive. This avoids resource exhaustion and provides a better user experience by allowing transactions to be processed through other available services. This way, the Circuit Breaker pattern handles external API failures, ensuring the system remains functional. In plain words @@ -31,7 +33,9 @@ Wikipedia says > Circuit breaker is a design pattern used in modern software development. It is used to detect failures and encapsulates the logic of preventing a failure from constantly recurring, during maintenance, temporary external system failure or unexpected system difficulties. -## Programmatic Example +## Programmatic Example of Circuit Breaker Pattern in Java + +This Java example demonstrates how the Circuit Breaker pattern can manage remote service failures and maintain system stability. Imagine a web application that uses both local files/images and remote services to fetch data. Remote services can become slow or unresponsive, which may cause the application to hang due to thread starvation. The Circuit Breaker pattern can help detect such failures and allow the application to degrade gracefully. @@ -172,13 +176,15 @@ Program output: This example demonstrates how the Circuit Breaker pattern can help maintain application stability and resilience by managing remote service failures. -## Applicability +## When to Use the Circuit Breaker Pattern in Java + +The Circuit Breaker pattern is applicable: * In distributed systems where individual service failures can lead to cascading system-wide failures * For applications that interact with third-party services or databases that might become unresponsive or slow * In microservices architectures where the failure of one service can affect the availability of others -## Known Uses +## Real-World Applications of Circuit Breaker Pattern in Java * Cloud-based services to gracefully handle the failure of external services * E-commerce platforms to manage high volumes of transactions and dependency on external APIs @@ -186,12 +192,12 @@ This example demonstrates how the Circuit Breaker pattern can help maintain appl * [Spring Circuit Breaker module](https://spring.io/guides/gs/circuit-breaker) * [Netflix Hystrix API](https://github.com/Netflix/Hystrix) -## Consequences +## Benefits and Trade-offs of Circuit Breaker Pattern Benefits: * Prevents the system from performing futile operations that are likely to fail, thus saving resources -* Helps in maintaining the stability and performance of the application during partial system failures +* Helps in maintaining the system stability and performance of the application during partial system failures * Facilitates faster system recovery by avoiding the overwhelming of failing services with repeated requests Trade-Offs: @@ -205,7 +211,7 @@ Trade-Offs: - Bulkhead: Can be used to isolate different parts of the system to prevent failures from spreading across the system - [Retry Pattern](https://github.com/iluwatar/java-design-patterns/tree/master/retry): Can be used in conjunction with the Circuit Breaker pattern to retry failed operations before opening the circuit -## Credits +## References and Credits * [Building Microservices: Designing Fine-Grained Systems](https://amzn.to/43Dx86g) * [Microservices Patterns: With examples in Java](https://amzn.to/3xaZwk0) diff --git a/client-session/README.md b/client-session/README.md index 2472fd32a..c49e53c71 100644 --- a/client-session/README.md +++ b/client-session/README.md @@ -1,23 +1,25 @@ --- -title: Client Session +title: "Client-Session Pattern in Java: Streamlining Client Data Across Sessions" +shortTitle: Client Session +description: "Explore the Client Session design pattern in Java. Learn how to manage user state and data across multiple requests for seamless, personalized web application experiences." category: Behavioral language: en tags: - - Client-server - - Session management - - State tracking - - Web development + - Client-server + - Session management + - State tracking + - Web development --- ## Also known as * User Session -## Intent +## Intent of Client Session Design Pattern -The Client Session design pattern aims to maintain a user's state and data across multiple requests within a web application, ensuring a continuous and personalized user experience. +The Client Session design pattern is essential for web development involving client-server interactions. It aims to maintain a user's state and data across multiple requests within a web application, ensuring a continuous and personalized user experience. This pattern helps in creating a seamless user experience by managing user state and data effectively across different sessions, crucial for modern web applications. -## Explanation +## Detailed Explanation of Client Session Pattern with Real-World Examples Real-world example @@ -31,7 +33,7 @@ Wikipedia says > The client-server model on Wikipedia describes a system where client devices request services and resources from centralized servers. This model is crucial in web applications where client sessions are used to manage user-specific data across multiple requests. For example, when a bank customer accesses online banking services, their login credentials and session state are managed by the web server to maintain continuity of their interactions. -**Programmatic Example** +## Programmatic Example of Client Session Pattern in Java The Client Session design pattern is a behavioral design pattern that maintains a user's state and data across multiple requests within a web application, ensuring a continuous and personalized user experience. This pattern is commonly used in web applications where user-specific data needs to be managed across multiple requests. @@ -100,7 +102,7 @@ Running the program produces the following console output: 19:28:49.154 [main] INFO com.iluwatar.client.session.Server -- Processing Request with client: Session2 data: Data2 ``` -## Applicability +## When to Use the Client Session Pattern in Java Use the client state pattern when: @@ -108,13 +110,13 @@ Use the client state pattern when: * Applications needing to track user activities and preferences over multiple requests or visits. * Systems where server resources need to be optimized by offloading state management to the client side. -## Known Uses +## Real-World Applications of Client Session Pattern in Java * E-commerce websites to track shopping cart contents across sessions. * Online platforms that offer personalized content based on user preferences and history. * Web applications requiring user login to access personalized or secured content. -## Consequences +## Benefits and Trade-offs of Client Session Pattern Benefits: @@ -134,7 +136,7 @@ Trade-offs: * [Singleton](https://java-design-patterns.com/patterns/singleton/): Ensuring a single instance of a user's session throughout the application. * [State](https://java-design-patterns.com/patterns/state/): Managing state transitions in a session, such as authenticated, guest, or expired states. -## Credits +## References and Credits * [Professional Java for Web Applications](https://amzn.to/4aazY59) * [Securing Web Applications with Spring Security](https://amzn.to/3PCCEA1) diff --git a/collecting-parameter/README.md b/collecting-parameter/README.md index 2f01d2caa..55609aebd 100644 --- a/collecting-parameter/README.md +++ b/collecting-parameter/README.md @@ -1,12 +1,14 @@ --- -title: Collecting Parameter +title: "Collecting Parameter Pattern in Java: Mastering Efficient Parameter Handling" +shortTitle: Collecting Parameter +description: "Discover how the Collecting Parameter design pattern simplifies Java method calls by aggregating multiple parameters into a single collection object. Enhance code readability and maintainability with practical examples and real-world applications." category: Behavioral language: en tag: - - Accumulation - - Data processing - - Data transfer - - Generic + - Accumulation + - Data processing + - Data transfer + - Generic --- ## Also known as @@ -14,14 +16,16 @@ tag: * Collector * Accumulator -## Intent +## Intent of Collecting Parameter Design Pattern -Aims to simplify methods that collect information by passing a single collection object through various method calls, allowing them to add results to this collection rather than each method creating its own collection. +The Collecting Parameter pattern in Java design patterns aims to simplify method calls by aggregating multiple parameters into a single collection object. This pattern is particularly effective for methods that collect information by passing a single collection object through various method calls. Each method can then add results to this collection, instead of creating its own collection. This approach enhances code readability and maintainability, optimizing the process of information collection in Java programming. -## Explanation +## Detailed Explanation of Collecting Parameter Pattern with Real-World Examples Real-world example +> In software development, the Collecting Parameter pattern provides significant benefits by optimizing method calls and improving code maintainability. +> > Imagine a scenario in a restaurant where a waiter needs to take an order from a customer. Instead of noting down each item separately (e.g., appetizer, main course, dessert, drink), the waiter uses an order form that collects all the items into a single document. This order form simplifies the communication between the waiter and the kitchen staff by aggregating all the details into one place. Similarly, in software, the Collecting Parameter pattern aggregates multiple parameters into a single object, streamlining method calls and improving code readability and maintainability. In plain words @@ -32,7 +36,7 @@ Wikipedia says > In the Collecting Parameter idiom a collection (list, map, etc.) is passed repeatedly as a parameter to a method which adds items to the collection. -**Programmatic Example** +## Programmatic Example of Collecting Parameter Pattern in Java Within a large corporate building, there exists a global printer queue that is a collection of all the printing jobs that are currently pending. Various floors contain different models of printers, each having a different printing policy. We must construct a program that can continually add appropriate printing jobs to a collection, which is called the collecting parameter. @@ -106,24 +110,28 @@ This `App` class is the main entry point of the application. It uses the Collect The `result` list, which is the collecting parameter, accumulates the valid print jobs as it is passed from method to method. This is the essence of the Collecting Parameter design pattern. -## Applicability +Utilizing the Collecting Parameter pattern in Java design patterns leads to more efficient method calls and improved overall code structure. + +## When to Use the Collecting Parameter Pattern in Java + +This pattern is useful for managing parameters in Java coding practices, ensuring efficient code refactoring and enhanced readability. * Use when a method needs to accept a large number of parameters, making the method signature unwieldy. * Use when the same group of parameters is passed to multiple methods, reducing redundancy and potential errors. * Use to improve the readability and maintainability of the code. -## Tutorials +## Collecting Parameter Pattern Java Tutorials * [Refactoring To Patterns (Joshua Kerivsky)](http://www.tarrani.net/RefactoringToPatterns.pdf) * [Smalltalk Best Practice Patterns (Kent Beck)](https://ptgmedia.pearsoncmg.com/images/9780134769042/samplepages/013476904X.pdf) -## Known uses +## Real-World Applications of Collecting Parameter Pattern in Java * Use when a method needs to accept a large number of parameters, making the method signature unwieldy. * Use when the same group of parameters is passed to multiple methods, reducing redundancy and potential errors. * Use to improve the readability and maintainability of the code. -## Consequences +## Benefits and Trade-offs of Collecting Parameter Pattern Benefits: @@ -136,13 +144,13 @@ Trade-offs: * Introduces an additional class, which may increase complexity if not managed properly. * Can lead to over-generalization if the parameter object becomes too large or unwieldy. -## Related patterns +## Related Java Design Patterns * [Command](https://java-design-patterns.com/patterns/command/): Commands may utilize Collecting Parameter to aggregate results from multiple operations executed by the command objects. * [Composite](https://java-design-patterns.com/patterns/composite/): Can be used in tandem with Collecting Parameter when dealing with hierarchical structures, allowing results to be collected across a composite structure. * [Visitor](https://java-design-patterns.com/patterns/visitor/): Often used together, where Visitor handles traversal and operations on a structure, and Collecting Parameter accumulates the results. -## Credits +## References and Credits * [Clean Code: A Handbook of Agile Software Craftsmanship](https://amzn.to/4aApLP0) * [Refactoring: Improving the Design of Existing Code](https://amzn.to/3TVEgaB) diff --git a/collection-pipeline/README.md b/collection-pipeline/README.md index f60f06e01..8f8764be2 100644 --- a/collection-pipeline/README.md +++ b/collection-pipeline/README.md @@ -1,19 +1,21 @@ --- -title: Collection Pipeline +title: "Collection Pipeline Pattern in Java: Streamlining Data Manipulation" +shortTitle: Collection Pipeline +description: "Learn how the Collection Pipeline design pattern in Java enhances data processing by chaining operations in a sequence. This pattern promotes a declarative approach, improving code readability, maintainability, and performance." category: Functional language: en tag: - - Functional decomposition - - Data processing - - Data transformation - - Reactive + - Functional decomposition + - Data processing + - Data transformation + - Reactive --- -## Intent +## Intent of Collection Pipeline Design Pattern -The Collection Pipeline design pattern is intended to process collections of data by chaining together operations in a sequence where the output of one operation is the input for the next. It promotes a declarative approach to handling collections, focusing on what should be done rather than how. +The Collection Pipeline design pattern in Java processes collections of data by chaining operations in a sequence. Utilizing the Java Stream API, it transforms data declaratively, focusing on what should be done rather than how. -## Explanation +## Detailed Explanation of Collection Pipeline Pattern with Real-World Examples Real-world example @@ -21,13 +23,13 @@ Real-world example In plain words -> The Collection Pipeline pattern involves processing data by passing it through a series of operations, each transforming the data in sequence, much like an assembly line in a factory. +> The Collection Pipeline pattern in Java involves processing data through a series of operations using the Stream API. Each operation transforms the data in sequence, akin to an assembly line in a factory, promoting functional programming principles. Wikipedia says > In software engineering, a pipeline consists of a chain of processing elements (processes, threads, coroutines, functions, etc.), arranged so that the output of each element is the input of the next; the name is by analogy to a physical pipeline. Usually some amount of buffering is provided between consecutive elements. The information that flows in these pipelines is often a stream of records, bytes, or bits, and the elements of a pipeline may be called filters; this is also called the pipe(s) and filters design pattern. Connecting elements into a pipeline is analogous to function composition. -**Programmatic Example** +## Programmatic Example of Collection Pipeline Pattern in Java The Collection Pipeline is a programming pattern where you organize some computation as a sequence of operations which compose by taking a collection as output of one operation and feeding it into the next. @@ -74,20 +76,24 @@ public static List getSedanCarsOwnedSortedByDate(List persons){ In each of these methods, the Collection Pipeline pattern is used to perform a series of operations on the collection of cars in a declarative manner, which improves readability and maintainability. -## Applicability +## When to Use the Collection Pipeline Pattern in Java + +The Collection Pipeline pattern is ideal for Java developers handling bulk data operations, including filtering, mapping, sorting, and reducing collections, particularly with Java 8+ Stream API. + +Use the Collection Pipeline pattern: * When you need to perform a series of transformations on a collection of data. * When you want to improve readability and maintainability of complex data processing code. * When working with large datasets where intermediate results should not be stored in memory. -## Known Uses +## Real-World Applications of Collection Pipeline Pattern in Java * LINQ in .NET * Stream API in Java 8+ * Collections in modern functional languages (e.g., Haskell, Scala) * Database query builders and ORM frameworks -## Consequences +## Benefits and Trade-offs of Collection Pipeline Pattern Benefits: @@ -102,13 +108,13 @@ Trade-offs: * Debugging Difficulty: Debugging a chain of operations might be more challenging due to the lack of intermediate variables. * Limited to Collections: Primarily focused on collections, and its utility might be limited outside of collection processing. -## Related Patterns +## Related Java Design Patterns * [Builder](https://java-design-patterns.com/patterns/builder/): Similar fluent interface style but used for object construction. * [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Conceptually similar in chaining handlers, but applied to object requests rather than data collection processing. * [Strategy](https://java-design-patterns.com/patterns/strategy/): Can be used within a pipeline stage to encapsulate different algorithms that can be selected at runtime. -## Credits +## References and Credits * [Functional Programming in Scala](https://amzn.to/4cEo6K2) * [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://amzn.to/3THp4wy) diff --git a/combinator/README.md b/combinator/README.md index 0882504ce..0ebe7deea 100644 --- a/combinator/README.md +++ b/combinator/README.md @@ -1,13 +1,15 @@ --- -title: Combinator +title: "Combinator Pattern in Java: Crafting Flexible Code Compositions" +shortTitle: Combinator +description: "Learn how to use the Combinator pattern in Java with real-world examples and comprehensive explanations. Enhance your Java design skills with this detailed guide." category: Functional language: en tag: - - Abstraction - - Code simplification - - Functional decomposition - - Idiom - - Reactive + - Abstraction + - Code simplification + - Functional decomposition + - Idiom + - Reactive --- ## Also known as @@ -15,11 +17,11 @@ tag: * Function Composition * Functional Combinator -## Intent +## Intent of Combinator Design Pattern -Combine multiple smaller functions or operations into a single, more complex operation, allowing for flexible and reusable code. +The Combinator pattern, a functional programming technique widely used in Java, is essential for combining functions to build complex behaviors. This pattern allows developers to combine multiple smaller functions or operations into a single, more complex operation, promoting flexible and reusable code. By leveraging higher-order functions, the Combinator pattern enhances code reuse and maintainability in Java applications, making it a valuable tool in software design. This approach fosters the creation of modular, scalable solutions in Java development. -## Explanation +## Detailed Explanation of Combinator Pattern with Real-World Examples Real-world example @@ -33,11 +35,11 @@ Wikipedia says > A combinator is a higher-order function that uses only function application and earlier defined combinators to define a result from its arguments. -**Programmatic Example** +## Programmatic Example of Combinator Pattern in Java -In computer science, combinatory logic is used as a simplified model of computation, used in computability theory and proof theory. Despite its simplicity, combinatory logic captures many essential features of computation. +In software design, combinatory logic is pivotal for creating reusable and modular code components. By leveraging higher-order functions, the Combinator pattern promotes code reuse and maintainability in Java applications. -First of all, we have an interface consist of several methods `contains`, `not`, `or`, `and` . +In this Java example, we demonstrate the implementation of combinators such as `contains`, `not`, `or`, and `and` to create complex finders. ```java // Functional interface to find lines in text. @@ -178,7 +180,7 @@ public class CombinatorApp { } ``` -**Program output:** +Program output: ``` 20:03:52.746 [main] INFO com.iluwatar.combinator.CombinatorApp -- the result of expanded(or) query[[many, Annabel]] is [It was many and many a year ago,, By the name of ANNABEL LEE;, I and my Annabel Lee;] @@ -189,15 +191,17 @@ public class CombinatorApp { Now we can design our app to with the queries finding feature `expandedFinder`, `specializedFinder`, `advancedFinder`, `filteredFinder` which are all derived from `contains`, `or`, `not`, `and`. -## Applicability +## When to Use the Combinator Pattern in Java -This pattern is applicable in scenarios where: +The Combinator pattern is particularly useful in functional programming where complex values are built from simpler, reusable components. + +The applicable scenarios include: * The solution to a problem can be constructed from simple, reusable components. * There is a need for high modularity and reusability of functions. * The programming environment supports first-class functions and higher-order functions. -## Known Uses +## Real-World Applications of Combinator Pattern in Java * Functional programming languages like Haskell and Scala extensively use combinators for tasks ranging from parsing to UI construction. * In domain-specific languages, particularly those involved in parsing, such as parsing expression grammars. @@ -205,10 +209,11 @@ This pattern is applicable in scenarios where: * java.util.function.Function#compose * java.util.function.Function#andThen -## Consequences +## Benefits and Trade-offs of Combinator Pattern Benefits: +* Enhances developer productivity by using domain-specific terms and facilitates parallel execution in Java applications. * Enhances modularity and reusability by breaking down complex tasks into simpler, composable functions. * Promotes readability and maintainability by using a declarative style of programming. * Facilitates lazy evaluation and potentially more efficient execution through function composition. @@ -219,13 +224,13 @@ Trade-offs: * May result in performance overhead due to the creation of intermediate functions. * Debugging can be challenging due to the abstract nature of function compositions. -## Related Patterns +## Related Java Design Patterns * [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Relies on chaining objects, whereas Combinator chains functions. * [Decorator](https://java-design-patterns.com/patterns/decorator/): Similar to Combinator in enhancing functionality, but Decorator focuses on object augmentation. * [Strategy](https://java-design-patterns.com/patterns/strategy/): Both involve selecting an algorithm at runtime, but Combinator uses composition of functions. -## Credits +## References and Credits * [Functional Programming in Scala](https://amzn.to/4cEo6K2) * [Haskell: The Craft of Functional Programming](https://amzn.to/4axxtcF) diff --git a/command-query-responsibility-segregation/README.md b/command-query-responsibility-segregation/README.md index a25ddbb8f..4c9749d97 100644 --- a/command-query-responsibility-segregation/README.md +++ b/command-query-responsibility-segregation/README.md @@ -1,22 +1,24 @@ --- -title: Command Query Responsibility Segregation +title: "Command Query Responsibility Segregation in Java: Optimizing Data Interaction for Scalability" +shortTitle: Command Query Responsibility Segregation (CQRS) +description: "Learn about the Command Query Responsibility Segregation (CQRS) pattern in Java. Discover how segregating commands and queries can enhance the scalability, performance, and maintainability of your software systems." category: Architectural language: en tag: - - Event-driven - - Performance - - Scalability + - Event-driven + - Performance + - Scalability --- ## Also known as * CQRS -## Intent +## Intent of Command Query Responsibility Segregation Design Pattern -Command Query Responsibility Segregation aims to segregate the operations that modify the state of an application (commands) from the operations that read the state (queries). +Command Query Responsibility Segregation (CQRS) aims to segregate the operations that modify the state of an application (commands) from the operations that read the state (queries). This separation enhances scalability, performance, and maintainability in complex software systems. -## Explanation +## Detailed Explanation of Command Query Responsibility Segregation Pattern with Real-World Examples Real-world example @@ -24,13 +26,13 @@ Real-world example In plain words -> The CQRS design pattern separates the actions of modifying data (commands) from the actions of retrieving data (queries) to enhance performance, scalability, and maintainability in software systems. +> The CQRS design pattern separates the actions of modifying data (commands) from the actions of retrieving data (queries) to enhance performance, scalability, and maintainability in software systems. By implementing CQRS, you can optimize your system's read and write operations independently, allowing for more efficient data handling and improved overall system performance. Microsoft's documentation says > CQRS separates reads and writes into different models, using commands to update data, and queries to read data. -**Programmatic Example** +## Programmatic Example of CQRS Pattern in Java One way to implement the Command Query Responsibility Segregation (CQRS) pattern is to separate the read and write operations into different services. @@ -93,19 +95,19 @@ Program output: 17:37:56.042 [main] INFO com.iluwatar.cqrs.app.App - jBloch books : [Book(title=Effective Java, price=40.54), Book(title=Java Puzzlers, price=39.99), Book(title=Java Concurrency in Practice, price=29.4)] ``` -## Applicability +## When to Use the Command Query Responsibility Segregation Pattern in Java -* Systems requiring distinct models for read and write operations for scalability and maintainability. -* Complex domain models where the task of updating objects differs significantly from the task of reading object data. -* Scenarios where performance optimization for read operations is crucial, and the system can benefit from different data models or databases for reads and writes. +* Systems requiring distinct models for read and write operations for scalability and maintainability, such as e-commerce platforms and high-traffic websites. +* Complex domain models, like financial services or healthcare applications, where the task of updating objects differs significantly from the task of reading object data. +* Scenarios where performance optimization for read operations is crucial, and the system can benefit from different data models or databases for reads and writes, enhancing data retrieval speed and accuracy. -## Known Uses +## Real-World Applications of CQRS Pattern in Java * Distributed Systems and Microservices Architecture, where different services manage read and write responsibilities. * Event-Sourced Systems, where changes to the application state are stored as a sequence of events. * High-Performance Web Applications, segregating read and write databases to optimize load handling. -## Consequences +## Benefits and Trade-offs of Command Query Responsibility Segregation Pattern Benefits: @@ -120,13 +122,13 @@ Trade-Offs: * Overhead: Might be an overkill for simple systems where the benefits do not outweigh the additional complexity. * Learning Curve: Requires a deeper understanding and careful design to implement effectively, increasing the initial learning curve. -## Related Patterns +## Related Java Design Patterns * [Event Sourcing](https://java-design-patterns.com/patterns/event-sourcing/): Often used in conjunction with CQRS, where changes to the application state are stored as a sequence of events. * Domain-Driven Design (DDD): CQRS fits well within the DDD context, providing clear boundaries and separation of concerns. * [Repository](https://java-design-patterns.com/patterns/repository/): Can be used to abstract the data layer, providing a more seamless integration between the command and query sides. -## Credits +## References and Credits * [Implementing Domain-Driven Design](https://amzn.to/3TJN2HH) * [Microsoft .NET: Architecting Applications for the Enterprise](https://amzn.to/4aktRes) diff --git a/command/README.md b/command/README.md index e311f8816..8877f722e 100644 --- a/command/README.md +++ b/command/README.md @@ -1,12 +1,14 @@ --- -title: Command +title: "Command Pattern in Java: Empowering Flexible Command Execution" +shortTitle: Command +description: "Learn about the Command design pattern in Java with real-world examples, detailed explanations, and practical use cases. Understand how this pattern encapsulates requests as objects to support undo operations and more." category: Behavioral language: en tag: - - Decoupling - - Extensibility - - Gang of Four - - Undo + - Decoupling + - Extensibility + - Gang of Four + - Undo --- ## Also known as @@ -14,15 +16,15 @@ tag: * Action * Transaction -## Intent +## Intent of Command Design Pattern -The Command design pattern encapsulates a request as an object, thereby allowing for parameterization of clients with queues, requests, and operations. It also allows for the support of undoable operations. +The Command design pattern is a behavioral pattern used in Java programming. It encapsulates a request as an object, allowing for parameterization of clients with queues, requests, and operations. This pattern also supports undoable operations, enhancing flexibility in managing and executing commands. -## Explanation +## Detailed Explanation of Command Pattern with Real-World Examples Real-world example -> Imagine a smart home system where you can control various devices such as lights, thermostat, and security cameras through a central application. Each command to turn a device on or off, adjust temperature, or start recording is encapsulated as an object. This way, the application can queue commands, execute them in sequence, and even undo them if needed (like turning the lights back on or stopping the recording). The system thus decouples the control logic from the actual implementation of device operations, allowing for easy addition of new devices or features without altering the core application. +> Imagine a smart home system where you can control devices such as lights, thermostats, and security cameras through a central application. Each command to operate these devices is encapsulated as an object, enabling the system to queue, execute sequentially, and undo commands if necessary. This approach decouples control logic from device implementation, allowing easy addition of new devices or features without altering the core application. This flexibility and functionality illustrate the practical application of the Command design pattern in Java programming. In plain words @@ -32,9 +34,11 @@ Wikipedia says > In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. -**Programmatic Example** +## Programmatic Example of Command Pattern in Java -There is a wizard casting spells on a goblin. The spells are executed on the goblin one by one. The first spell shrinks the goblin and the second makes him invisible. Then the wizard reverses the spells one by one. Each spell here is a command object that can be undone. +In the Command pattern, objects are used to encapsulate all information needed to perform an action or trigger an event at a later time. This pattern is particularly useful for implementing undo functionality in applications. + +In our example, a `Wizard` casts spells on a `Goblin`. Each spell is a command object that can be executed and undone, demonstrating the core principles of the Command pattern in Java. The spells are executed on the goblin one by one. The first spell shrinks the goblin and the second makes him invisible. Then the wizard reverses the spells one by one. Each spell here is a command object that can be undone. Let's start from the `Wizard` class. @@ -162,7 +166,9 @@ Here's the program output: 20:13:38.409 [main] INFO com.iluwatar.command.Target -- Goblin, [size=small] [visibility=invisible] ``` -## Applicability +## When to Use the Command Pattern in Java + +The Command design pattern is applicable when you need to parameterize objects with actions, support undo operations, or structure a system around high-level operations built on primitive ones. It is commonly used in GUI buttons, database transactions, and macro recording. Use the Command pattern when you want to: @@ -175,7 +181,7 @@ Use the Command pattern when you want to: * Implement callback functionality. * Implement undo functionality. -## Known uses +## Real-World Applications of Command Pattern in Java * GUI Buttons and menu items in desktop applications. * Operations in database systems and transactional systems that support rollback. @@ -185,7 +191,7 @@ Use the Command pattern when you want to: * [Netflix Hystrix](https://github.com/Netflix/Hystrix/wiki) * [javax.swing.Action](http://docs.oracle.com/javase/8/docs/api/javax/swing/Action.html) -## Consequences +## Benefits and Trade-offs of Command Pattern Benefits: @@ -198,13 +204,13 @@ Trade-offs: * Increases the number of classes for each individual command. * Can complicate the design by adding multiple layers between senders and receivers. -## Related Patterns +## Related Java Design Patterns * [Composite](https://java-design-patterns.com/patterns/composite/): Commands can be composed using the Composite pattern to create macro commands. * [Memento](https://java-design-patterns.com/patterns/memento/): Can be used for implementing undo mechanisms. * [Observer](https://java-design-patterns.com/patterns/observer/): The pattern can be observed for changes that trigger commands. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) diff --git a/commander/README.md b/commander/README.md index a11476209..902c6af1b 100644 --- a/commander/README.md +++ b/commander/README.md @@ -1,11 +1,17 @@ --- -title: Commander +title: "Commander Pattern in Java: Orchestrating Complex Commands with Ease" +shortTitle: Commander +description: "Learn about the Commander design pattern in Java, a powerful approach for managing distributed transactions across multiple services. Ensure data consistency and reliability in your microservices architecture with practical examples and use cases." category: Behavioral language: en tag: - - Cloud distributed - - Microservices - - Transactions + - Cloud distributed + - Microservices + - Transactions +head: + - - meta + - name: keywords + content: --- ## Also known as @@ -13,23 +19,23 @@ tag: * Distributed Transaction Commander * Transaction Coordinator -## Intent +## Intent of Commander Design Pattern -The intent of the Commander pattern in the context of distributed transactions is to manage and coordinate complex transactions across multiple distributed components or services, ensuring consistency and integrity of the overall transaction. It encapsulates transaction commands and coordination logic, facilitating the implementation of distributed transaction protocols like two-phase commit or Saga. +The intent of the Commander pattern in Java, especially in the context of distributed transactions, is to manage and coordinate complex transactions across multiple distributed components or services. This pattern ensures data consistency and integrity in distributed systems, making it crucial for microservices architecture. It encapsulates transaction commands and coordination logic, facilitating the implementation of distributed transaction protocols like two-phase commit or Saga. -## Explanation +## Detailed Explanation of Commander Pattern with Real-World Examples Real-world example -> Imagine organizing a large international music festival where various bands from around the world are scheduled to perform. Each band's arrival, soundcheck, and performance are like individual transactions in a distributed system. The festival organizer acts as the "Commander," coordinating these transactions to ensure that if a band's flight is delayed (akin to a transaction failure), there's a backup plan, such as rescheduling or swapping time slots with another band (compensating actions), to keep the overall schedule intact. This setup mirrors the Commander pattern in distributed transactions, where various components must be coordinated to achieve a successful outcome despite individual failures. +> Imagine organizing a large international music festival where various bands from around the world are scheduled to perform. Each band's arrival, soundcheck, and performance are akin to individual transactions in a distributed system. This scenario mirrors the Commander pattern in Java, where the "Commander" coordinates distributed transactions to maintain overall consistency and reliability. The festival organizer acts as the "Commander," coordinating these transactions to ensure that if a band's flight is delayed (akin to a transaction failure), there's a backup plan, such as rescheduling or swapping time slots with another band (compensating actions), to keep the overall schedule intact. This setup mirrors the Commander pattern in distributed transactions, where various components must be coordinated to achieve a successful outcome despite individual failures. In plain words > The Commander pattern turns a request into a stand-alone object, allowing for the parameterization of commands, queueing of actions, and the implementation of undo operations. -**Programmatic Example** +## Programmatic Example of Commander Pattern in Java -Managing transactions across different services in a distributed system, such as an e-commerce platform with separate `Payment` and `Shipping` microservices, requires careful coordination to avoid issues. When a user places an order but one service (e.g., `Payment`) is unavailable while the other (e.g., `Shipping`) is ready, we need a robust solution to handle this discrepancy. +Managing transactions across different services in a distributed system, such as an e-commerce platform with separate `Payment` and `Shipping` microservices, requires careful coordination. Using the Commander pattern in Java for transaction coordination helps ensure data consistency and reliability, even when services experience partial failures. A strategy to address this involves using a `Commander` component that orchestrates the process. Initially, the order is processed by the available service (`Shipping` in this case). The `Commander` then attempts to synchronize the order with the currently unavailable service (`Payment`) by storing the order details in a database or queueing it for future processing. This queueing system must also account for possible failures in adding requests to the queue. @@ -73,21 +79,21 @@ Here is the output from executing the `itemUnavailableCase`: 09:10:13.897 [Thread-0] INFO com.iluwatar.commander.Commander -- Order YN3V8B7IL2PI: Added order to employee database ``` -## Applicability +## When to Use the Commander Pattern in Java -Use the Commander pattern for distributed transactions when: +Use the Commander pattern in Java for distributed transactions when: * You need to ensure data consistency across distributed services in the event of partial system failures. * Transactions span multiple microservices or distributed components requiring coordinated commit or rollback. * You are implementing long-lived transactions requiring compensating actions for rollback. -## Known Uses +## Real-World Applications of Commander Pattern in Java * Two-Phase Commit (2PC) Protocols: Coordinating commit or rollback across distributed databases or services. * Saga Pattern Implementations: Managing long-lived business processes that span multiple microservices, with each step having a compensating action for rollback. * Distributed Transactions in Microservices Architecture: Coordinating complex operations across microservices while maintaining data integrity and consistency. -## Consequences +## Benefits and Trade-offs of Commander Pattern Benefits: @@ -101,11 +107,11 @@ Trade-offs: * Potentially impacts performance due to the overhead of coordination and consistency checks. * Saga-based implementations can lead to increased complexity in understanding the overall business process flow. -## Related Patterns +## Related Java Design Patterns * [Saga Pattern](https://java-design-patterns.com/patterns/saga/): Often discussed in tandem with the Commander pattern for distributed transactions, focusing on long-lived transactions with compensating actions. -## Credits +## References and Credits * [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/4aATcRe) * [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/4axHwOV) diff --git a/component/README.md b/component/README.md index 4bc974603..638133265 100644 --- a/component/README.md +++ b/component/README.md @@ -1,11 +1,13 @@ --- -title: Component +title: "Component Pattern in Java: Simplifying Complex Systems with Reusable Components" +shortTitle: Component +description: "Learn about the Component Design Pattern in Java, including ECS architecture, modularity, and decoupling. Explore examples, class diagrams, and real-world applications in game development for flexible and maintainable code." categories: Structural language: en tag: - - Game programming - - Decoupling - - Modularity + - Game programming + - Decoupling + - Modularity --- ## Also known as @@ -14,21 +16,21 @@ tag: * Component-Entity-System (CES) * Component-Based Architecture (CBA) -## Intent +## Intent of Component Design Pattern -The Component design pattern aims to organize code into reusable, interchangeable components, promoting flexibility and ease of maintenance in game development by allowing entities to be configured with varying behaviors. +The Component design pattern organizes code into reusable, interchangeable components, promoting flexibility, modularity, and ease of maintenance. This pattern is especially useful in game development, enabling entities to be configured with diverse behaviors dynamically. -## Explanation +## Detailed Explanation of Component Pattern with Real-World Examples Real-world example -> Imagine your video game has a graphics component and a sound component. Combining the methods and attributes of both features into a single Java class can lead to several issues. Firstly, the resulting class could become very lengthy and difficult to maintain. Additionally, the graphics and sound components might be developed by separate teams. If both teams work on the same Java class simultaneously, it could cause conflicts and significant delays. By using the Component design pattern, the development team can create separate component classes for graphics and sound, while still allowing the main game object to access both sets of attributes. +> Consider a video game with a graphics component and a sound component. Including both in a single Java class can create maintenance challenges due to lengthy code and potential conflicts from different teams working on the same class. The Component design pattern resolves this by creating individual component classes for graphics and sound, allowing flexible and independent development. This modular approach enhances maintainability and scalability. In plain words > The component design pattern provides a single attribute to be accessible by numerous objects without requiring the existence of a relationship between the objects themselves. -**Programmatic Example** +## Programmatic Example of Component Pattern in Java The `App` class creates a demonstration of the use of the component pattern by creating two different objects which inherit a small collection of individual components that are modifiable. @@ -122,17 +124,16 @@ public class PlayerInputComponent implements InputComponent { } ``` -## Applicability +## When to Use the Component Pattern in Java * Used in game development and simulations where game entities (e.g., characters, items) can have a dynamic set of abilities or states. * Suitable for systems requiring high modularity and systems where entities might need to change behavior at runtime without inheritance hierarchies. -## Known Uses +## Real-World Applications of Component Pattern in Java -* Game engines like Unity, Unreal Engine, and various custom engines in AAA and indie games. -* Simulation systems that require flexible, dynamic object composition. +The Component pattern is ideal for game development and simulations where entities like characters and items have dynamic abilities or states. It suits systems requiring high modularity and scenarios where entities need to change behavior at runtime without relying on inheritance hierarchies, enhancing flexibility and maintainability. -## Consequences +## Benefits and Trade-offs of Component Pattern Benefits: @@ -145,13 +146,13 @@ Trade-offs: * Complexity: Can introduce additional complexity in system architecture, particularly in managing dependencies and communications between components. * Performance Considerations: Depending on implementation, may incur a performance overhead due to indirection and dynamic behavior, especially critical in high-performance game loops. -## Related Patterns +## Related Java Design Patterns * [Decorator](https://java-design-patterns.com/patterns/decorator/): Similar concept of adding responsibilities dynamically, but without the focus on game entities. * [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Can be used in conjunction with the Component pattern to share component instances among many entities to save memory. * [Observer](https://java-design-patterns.com/patterns/observer/): Often used in Component systems to communicate state changes between components. -## Credits +## References and Credits * [Game Programming Patterns](https://amzn.to/4cDRWhV) * [Procedural Content Generation for Unity Game Development](https://amzn.to/3vBKCTp) diff --git a/composite-entity/README.md b/composite-entity/README.md index 015f44f90..9ac14d97e 100644 --- a/composite-entity/README.md +++ b/composite-entity/README.md @@ -1,40 +1,42 @@ --- -title: Composite Entity +title: "Composite Entity Pattern in Java: Streamlining Persistent Object Management" +shortTitle: Composite Entity +description: "Learn about the Composite Entity design pattern in Java, a structural pattern used to manage interrelated persistent objects as a single entity. Ideal for enterprise applications and EJB, this pattern simplifies complex data structures and client interactions." category: Structural language: en tag: - - Client-server - - Data access - - Decoupling - - Enterprise patterns - - Object composition - - Persistence - - Resource management + - Client-server + - Data access + - Decoupling + - Enterprise patterns + - Object composition + - Persistence + - Resource management --- ## Also known as * Coarse-Grained Entity -## Intent +## Intent of Composite Entity Design Pattern -The Composite Entity design pattern is aimed at managing a set of interrelated persistent objects as if they were a single entity. It is commonly used in the context of Enterprise JavaBeans (EJB) and similar enterprise frameworks to represent graph-based data structures within business models, enabling clients to treat them as a single unit. +The Composite Entity design pattern in Java is aimed at managing a set of interrelated persistent objects as if they were a single entity. It is commonly used in enterprise applications, particularly within the context of Enterprise JavaBeans (EJB) and similar enterprise frameworks, to represent graph-based data structures within business models. This pattern enables clients to treat these complex structures as a single unit, simplifying operations and interactions. -## Explanation +## Detailed Explanation of Composite Entity Pattern with Real-World Examples Real-world example -> Consider a university registration system where a "Student" entity is a composite entity. Each "Student" object includes several dependent objects: personal details, course enrollments, grades, and payment information. Instead of managing each of these aspects separately, the Composite Entity pattern allows the university system to treat the "Student" as a single entity. This simplifies operations such as enrolling a student in a new course, updating grades, and processing payments, since all related actions can be managed through the composite "Student" object. +> Consider a university registration system where a "Student" entity is a composite entity. Each "Student" object includes several dependent objects: personal details, course enrollments, grades, and payment information. Instead of managing each of these aspects separately, the Composite Entity design pattern allows the university system to treat the "Student" as a single entity. This simplifies operations such as enrolling a student in a new course, updating grades, and processing payments, since all related actions can be managed through the composite "Student" object. In plain words -> Composite entity pattern allows a set of related objects to be represented and managed by a unified object. +> The Composite Entity pattern in Java allows a set of related persistent objects to be represented and managed by a unified object, simplifying enterprise application design. Wikipedia says > Composite entity is a Java EE Software design pattern and it is used to model, represent, and manage a set of interrelated persistent objects rather than representing them as individual fine-grained entity beans, and also a composite entity bean represents a graph of objects. -**Programmatic Example** +## Programmatic Example of Composite Entity in Java For a console, there may be many interfaces that need to be managed and controlled. Using the composite entity pattern, dependent objects such as messages and signals can be combined and controlled using a single object. @@ -123,25 +125,26 @@ public App(String message, String signal) { } ``` -## Applicability +## When to Use the Composite Entity Pattern in Java -* Useful in enterprise applications where business objects are complex and involve various interdependent objects. +* Useful in Java enterprise applications where business objects are complex and involve various interdependent persistent objects. * Ideal for scenarios where clients need to work with a unified interface to a set of objects rather than individual entities. * Applicable in systems that require a simplified view of a complex data model for external clients or services. -## Known Uses + +## Real-World Applications of Composite Entity Pattern in Java * Enterprise applications with complex business models, particularly those using EJB or similar enterprise frameworks. * Systems requiring abstraction over complex database schemas to simplify client interactions. -* Applications that need to enforce consistency or transactions across multiple objects in a business entity. +* Applications that need to enforce consistency or transactions across multiple persistent objects in a business entity. -## Consequences +## Benefits and Trade-offs of Composite Entity Pattern Benefits: * Simplifies client interactions with complex entity models by providing a unified interface. * Enhances reusability and maintainability of the business layer by decoupling client code from the complex internals of business entities. -* Facilitates easier transaction management and consistency enforcement across a set of related objects. +* Facilitates easier transaction management and consistency enforcement across a set of related persistent objects. Trade-offs: @@ -149,13 +152,13 @@ Trade-offs: * Can lead to overly coarse-grained interfaces that might not be as flexible for all client needs. * Requires careful design to avoid bloated composite entities that are difficult to manage. -## Related Patterns +## Related Java Design Patterns * [Decorator](https://java-design-patterns.com/patterns/decorator/): For dynamically adding behavior to individual objects within the composite entity without affecting the structure. * [Facade](https://java-design-patterns.com/patterns/facade/): Provides a simplified interface to a complex subsystem, similar to how a composite entity simplifies access to a set of objects. * [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Useful for managing shared objects within a composite entity to reduce memory footprint. -## Credits +## References and Credits * [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap) * [Enterprise Patterns and MDA: Building Better Software with Archetype Patterns and UML](https://amzn.to/49mslqS) diff --git a/composite-view/README.md b/composite-view/README.md index 5f1c19e59..bb2704eed 100644 --- a/composite-view/README.md +++ b/composite-view/README.md @@ -1,19 +1,21 @@ --- -title: Composite View +title: "Composite View Pattern in Java: Enhancing UI Consistency Across Applications" +shortTitle: Composite View +description: "Learn about the Composite View design pattern in Java, which helps in managing complex hierarchical views. This guide includes examples, applications, and benefits of using the Composite View pattern." category: Structural language: en tag: - - Abstraction - - Enterprise patterns - - Object composition - - Presentation + - Abstraction + - Enterprise patterns + - Object composition + - Presentation --- -## Intent +## Intent of Composite View Design Pattern -The primary goal of the Composite View design pattern is to compose objects into tree structures to represent part-whole hierarchies. This allows clients to treat individual objects and compositions of objects uniformly, simplifying the management of complex structures. +The primary goal of the Composite View design pattern is to compose objects into tree structures to represent part-whole hierarchies. This allows clients to treat individual objects and compositions of objects uniformly, simplifying the management of complex hierarchical views. -## Explanation +## Detailed Explanation of Composite View Pattern with Real-World Examples Real-world example @@ -27,7 +29,7 @@ Wikipedia says > Composite views that are composed of multiple atomic subviews. Each component of the template may be included dynamically into the whole and the layout of the page may be managed independently of the content. This solution provides for the creation of a composite view based on the inclusion and substitution of modular dynamic and static template fragments. It promotes the reuse of atomic portions of the view by encouraging modular design. -**Programmatic Example** +## Programmatic Example of Composite View Pattern in Java A news site wants to display the current date and news to different users based on that user's preferences. The news site will substitute in different news feed components depending on the user's interest, defaulting to local news. @@ -301,7 +303,7 @@ Under `Run` and `edit configurations` Make sure Tomcat server is one of the run Ensure that the artifact is being built from the content of the `web` directory and the compilation results of the module. Point the output of the artifact to a convenient place. Run the configuration and view the landing page, follow instructions on that page to continue. -## Applicability: +## When to Use the Composite View Pattern in Java Use the Composite View design pattern when: @@ -309,16 +311,16 @@ Use the Composite View design pattern when: * You expect that the composite structures might include any new components in the future. * You want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly. -## Tutorials +## Composite View Pattern Java Tutorials * [Composite View Design Pattern – Core J2EE Patterns (Dinesh on Java)](https://www.dineshonjava.com/composite-view-design-pattern/) -## Known Uses +## Real-World Applications of Composite View Pattern in Java * Graphical User Interfaces (GUIs) where widgets can contain other widgets (e.g., a window containing panels, buttons, and text fields). * Document structures, such as the representation of tables containing rows, which in turn contain cells, all of which can be treated as elements in a unified hierarchy. -## Consequences +## Benefits and Trade-offs of Composite View Pattern Benefits: @@ -330,14 +332,14 @@ Trade-offs: * Overgeneralization: Designing the system might become more complex if you make everything composite, especially if your application doesn't require it. * Difficulty in constraint enforcement: It can be harder to restrict the components of a composite to only certain types. -## Related Patterns +## Related Java Design Patterns * [Composite](https://java-design-patterns.com/patterns/composite/): General structural pattern that is the foundation for Composite View, used for treating individual objects and compositions uniformly. * [Decorator](https://java-design-patterns.com/patterns/decorator/): Enhances the behavior of individual views without modifying the underlying view. * [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Can be used to manage memory consumption of large numbers of similar view objects. * View Helper: Separates the view logic from business logic, aiding in the clean organization and management of view components. -## Credits +## References and Credits * [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/3xfntGJ) * [Patterns of Enterprise Application Architecture](https://amzn.to/49jpQG3) diff --git a/composite/README.md b/composite/README.md index 8d4c5816d..0dc740c3b 100644 --- a/composite/README.md +++ b/composite/README.md @@ -1,12 +1,14 @@ --- -title: Composite +title: "Composite Pattern in Java: Building Flexible Tree Structures" +shortTitle: Composite +description: "Explore the Composite Design Pattern in Java. Learn how to compose objects into tree structures to represent part-whole hierarchies, making it easier to treat individual objects and compositions uniformly. Ideal for graphical user interfaces, file systems, and organizational structures." category: Structural language: en tag: - - Decoupling - - Gang of Four - - Object composition - - Recursion + - Decoupling + - Gang of Four + - Object composition + - Recursion --- ## Also known as @@ -14,25 +16,25 @@ tag: * Object Tree * Composite Structure -## Intent +## Intent of Composite Design Pattern -Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. +Compose objects into tree structures to represent part-whole hierarchies. The Composite Design Pattern lets clients treat individual objects and compositions of objects uniformly. -## Explanation +## Detailed Explanation of Composite Pattern with Real-World Examples Real-world example -> In a real-world example, consider a company with a complex organizational structure. The company consists of various departments, each of which can contain sub-departments, and ultimately individual employees. The Composite pattern can be used to represent this structure. Each department and employee are treated as a node in a tree structure, where departments can contain other departments or employees, but employees are leaf nodes with no children. This allows the company to perform operations uniformly, such as calculating total salaries or printing the organizational chart, by treating individual employees and entire departments in the same way. +> In a real-world example, consider a company with a complex organizational structure. The company consists of various departments, each of which can contain sub-departments, and ultimately individual employees. The Composite Design Pattern can be used to represent this structure. Each department and employee are treated as a node in a tree structure, where departments can contain other departments or employees, but employees are leaf nodes with no children. This allows the company to perform operations uniformly, such as calculating total salaries or printing the organizational chart, by treating individual employees and entire departments in the same way. In plain words -> Composite pattern lets clients uniformly treat the individual objects. +> The Composite Design Pattern lets clients uniformly treat individual objects and compositions of objects. Wikipedia says > In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects is to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly. -**Programmatic Example** +## Programmatic Example of Composite Pattern in Java Every sentence is composed of words which are in turn composed of characters. Each of these objects are printable, and they can have something printed before or after them like sentence always ends with full stop and word always has space before it. @@ -174,14 +176,14 @@ The console output: Much wind pours from your mouth. ``` -## Applicability +## When to Use the Composite Pattern in Java Use the Composite pattern when * You want to represent part-whole hierarchies of objects. * You want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly. -## Known uses +## Real-World Applications of Composite Pattern in Java * Graphical user interfaces where components can contain other components (e.g., panels containing buttons, labels, other panels). * File system representations where directories can contain files and other directories. @@ -189,7 +191,7 @@ Use the Composite pattern when * [java.awt.Container](http://docs.oracle.com/javase/8/docs/api/java/awt/Container.html) and [java.awt.Component](http://docs.oracle.com/javase/8/docs/api/java/awt/Component.html) * [Apache Wicket](https://github.com/apache/wicket) component tree, see [Component](https://github.com/apache/wicket/blob/91e154702ab1ff3481ef6cbb04c6044814b7e130/wicket-core/src/main/java/org/apache/wicket/Component.java) and [MarkupContainer](https://github.com/apache/wicket/blob/b60ec64d0b50a611a9549809c9ab216f0ffa3ae3/wicket-core/src/main/java/org/apache/wicket/MarkupContainer.java) -## Consequences +## Benefits and Trade-offs of Composite Pattern Benefits: @@ -201,13 +203,13 @@ Trade-offs: * Can make the design overly general. It might be difficult to restrict the components of a composite. * Can make it harder to restrict the types of components in a composite. -## Related Patterns +## Related Java Design Patterns * [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Composite can use Flyweight to share component instances among several composites. * [Iterator](https://java-design-patterns.com/patterns/iterator/): Can be used to traverse Composite structures. * [Visitor](https://java-design-patterns.com/patterns/visitor/): Can apply an operation over a Composite structure. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) diff --git a/context-object/README.md b/context-object/README.md index 5d31ffd98..831abb7c7 100644 --- a/context-object/README.md +++ b/context-object/README.md @@ -1,12 +1,14 @@ --- -title: Context Object +title: "Context Object Pattern in Java: Simplifying Access to Contextual Data" +shortTitle: Context Object +description: "Learn about the Context Object pattern in Java Design Patterns. Encapsulate state and behaviors relevant to users or requests to decouple application components from environmental complexities. Explore real-world examples, benefits, and implementation tips." category: Behavioral language: en tags: - - Context - - Decoupling - - Encapsulation - - Session management + - Context + - Decoupling + - Encapsulation + - Session management --- ## Also known as @@ -16,11 +18,11 @@ tags: * Context Holder * Encapsulate Context -## Intent +## Intent of Context Object Design Pattern -Encapsulate the context (state and behaviors) relevant to the user or the request being processed in order to decouple application components from the complexities of the environment. +Encapsulate the context (state and behaviors) relevant to the user or the request being processed to decouple Java application components from the complexities of the environment. This design pattern helps in managing the application's context efficiently. -## Explanation +## Detailed Explanation of Context Object Pattern with Real-World Examples Real-world example @@ -28,15 +30,15 @@ Real-world example In plain words -> Create an object to store the context data and pass it where needed. +> Create an object to store and manage context data, and pass this context object wherever needed in the Java application, ensuring decoupled and cleaner code. [Core J2EE Patterns](http://corej2eepatterns.com/ContextObject.htm) says > Use a Context Object to encapsulate state in a protocol-independent way to be shared throughout your application. -**Programmatic Example** +## Programmatic Example of Context Object in Java -This application has different layers labelled A, B and C with each extracting specific information from a similar context for further use in the software. Passing down each pieces of information individually would be inefficient, a method to efficiently store and pass information is needed. +In a multi-layered Java application, different layers such as A, B, and C extract specific information from a shared context. Passing each piece of information individually is inefficient. The Context Object pattern efficiently stores and passes this information, improving the overall performance and maintainability of the Java application. Define the data that the `ServiceContext` object contains. @@ -154,21 +156,21 @@ Program output: 08:15:32.137 [main] INFO com.iluwatar.context.object.App -- Context = com.iluwatar.context.object.ServiceContext@5577140b ``` -## Applicability +## When to Use the Context Object Pattern in Java -* When there is a need to abstract and encapsulate context information from different parts of an application to avoid cluttering the business logic with environment-specific code. +* When there is a need to abstract and encapsulate context information in a Java application to avoid cluttering the business logic with environment-specific code. This is especially useful in web applications for encapsulating request-specific information and in distributed systems for managing user preferences and security credentials. * In web applications, to encapsulate request-specific information and make it easily accessible throughout the application without passing it explicitly between functions or components. * In distributed systems, to encapsulate contextual information about the task being performed, user preferences, or security credentials, facilitating their propagation across different components and services. -## Known uses +## Real-World Applications of Context Object Pattern in Java -* Web application frameworks often implement a Context Object to encapsulate HTTP request and response objects, session information, and other request-specific data. +* Web application frameworks often use the Context Object pattern to encapsulate HTTP request and response objects, session information, and other request-specific data. Enterprise Java applications leverage this pattern to manage and propagate transactional information, security credentials, and user-specific settings across different layers and services. * Enterprise applications use Context Objects to manage and propagate transactional information, security credentials, and user-specific settings across different layers and services. * [Spring: ApplicationContext](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContext.html) * [Oracle: SecurityContext](https://docs.oracle.com/javaee/7/api/javax/ws/rs/core/SecurityContext.html) * [Oracle: ServletContext](https://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html) -## Consequences +## Benefits and Trade-offs of Context Object Pattern Benefits: @@ -181,13 +183,13 @@ Trade-offs: * Overhead: Introducing a Context Object can add overhead in terms of performance, especially if not implemented efficiently. * Complexity: If the Context Object is not well-designed, it can become a bloated and complex monolith, difficult to manage and understand. -## Related Patterns +## Related Java Design Patterns * [Singleton](https://java-design-patterns.com/patterns/singleton/): The Context Object is often implemented as a Singleton to ensure a global point of access. * [Strategy](https://java-design-patterns.com/patterns/strategy/): Context Objects can use Strategies to adapt their behavior based on the context they encapsulate. * [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used to dynamically add responsibilities to the Context Object. -## Credits +## References and Credits * [Core J2EE Design Patterns](https://amzn.to/3IhcY9w) * [Context Object (Core J2EE Patterns)](http://corej2eepatterns.com/ContextObject.htm) diff --git a/converter/README.md b/converter/README.md index 639c170c3..adf29383d 100644 --- a/converter/README.md +++ b/converter/README.md @@ -1,14 +1,16 @@ --- -title: Converter +title: "Converter Pattern in Java: Streamlining Data Conversion Across Layers" +shortTitle: Converter +description: "Discover the benefits and implementation of the Converter Pattern in Java. Learn how to achieve seamless bidirectional conversion between different data formats, promoting clean code and flexibility in your applications." category: Structural language: en tag: - - Compatibility - - Data transformation - - Decoupling - - Interface - - Object mapping - - Wrapping + - Compatibility + - Data transformation + - Decoupling + - Interface + - Object mapping + - Wrapping --- ## Also known as @@ -16,25 +18,25 @@ tag: * Mapper * Translator -## Intent +## Intent of Converter Design Pattern -The purpose of the Converter pattern is to provide a generic, common way of bidirectional conversion between corresponding types, allowing a clean implementation in which the types do not need to be aware of each other. Moreover, the Converter pattern introduces bidirectional collection mapping, reducing a boilerplate code to minimum. +The purpose of the Converter Pattern is to provide a generic, systematic way of bidirectional conversion between corresponding data types. This allows for a clean, decoupled implementation where types are unaware of each other. Additionally, the Converter pattern supports bidirectional collection mapping, minimizing boilerplate code. -## Explanation +## Detailed Explanation of Converter Pattern with Real-World Examples Real-world example -> In a real-world scenario, consider a scenario where a library system needs to interact with a third-party book database. The library system uses its own internal book format, while the third-party database provides book information in a different format. To facilitate communication between the two systems, a Converter design pattern can be employed. This pattern will define a converter class that transforms the third-party book data format into the library's internal book format and vice versa. This ensures that the library system can seamlessly integrate with the third-party database without altering its own internal structure or the third-party system's format. +> In a real-world scenario, consider a library system that interacts with a third-party book database. The library uses an internal book format, while the third-party database uses a different format. By employing the Converter Pattern, a converter class can transform the third-party book data into the library's format and vice versa. This ensures seamless integration without altering the internal structures of either system. In plain words -> Converter pattern makes it easy to map instances of one class into instances of another class. +> The Converter Pattern simplifies mapping instances of one class to instances of another class, ensuring consistent and clean data transformation. -**Programmatic Example** +## Programmatic Example of Converter Pattern in Java -In real world applications it is often the case that database layer consists of entities that need to be mapped into DTOs for use on the business logic layer. Similar mapping is done for potentially huge amount of classes, and we need a generic way to achieve this. +In applications, it's common for the database layer to have entities that need mapping to DTOs (Data Transfer Objects) for business logic. This mapping often involves many classes, necessitating a generic solution. -We need a generic solution for the mapping problem. To achieve this, let's introduce a generic `Converter`. +We introduce a generic `Converter` class: ```java public class Converter { @@ -65,7 +67,7 @@ public class Converter { } ``` -The specialized converters inherit from this base class as follows. +Specialized converters inherit from this base class: ```java public class UserConverter extends Converter { @@ -84,7 +86,7 @@ public class UserConverter extends Converter { } ``` -Now mapping between `User` and `UserDto` becomes trivial. +Mapping between `User` and `UserDto` becomes straightforward: ```java public static void main(String[] args) { @@ -122,7 +124,7 @@ Program output: 08:28:27.037 [main] INFO com.iluwatar.converter.App -- UserDto[firstName=Kate, lastName=Smith, active=true, email=if0243] ``` -## Applicability +## When to Use the Converter Pattern in Java Use the Converter Pattern in the following situations: @@ -131,18 +133,18 @@ Use the Converter Pattern in the following situations: * For legacy systems integration where data models differ significantly from newer systems. * When aiming to encapsulate conversion logic to promote single responsibility and cleaner code. -## Tutorials +## Converter Pattern Java Tutorials * [Converter Pattern in Java 8 (Boldare)](http://www.xsolve.pl/blog/converter-pattern-in-java-8/) -## Known Uses +## Real-World Applications of Converter Pattern in Java * Data Transfer Objects (DTOs) conversions in multi-layered applications. * Adapting third-party data structures or API responses to internal models. * ORM (Object-Relational Mapping) frameworks for mapping between database records and domain objects. * Microservices architecture for data exchange between different services. -## Consequences +## Benefits and Trade-offs of Converter Pattern Benefits: @@ -156,13 +158,13 @@ Trade-offs: * Overhead: Introducing converters can add complexity and potential performance overhead, especially in systems with numerous data formats. * Duplication: There's a risk of duplicating model definitions if not carefully managed, leading to increased maintenance. -## Related Patterns +## Related Java Design Patterns * [Adapter](https://java-design-patterns.com/patterns/adapter/): Similar in intent to adapting interfaces, but Converter focuses on data models. * [Facade](https://java-design-patterns.com/patterns/facade/): Provides a simplified interface to a complex system, which might involve data conversion. * [Strategy](https://java-design-patterns.com/patterns/strategy/): Converters can use different strategies for conversion, especially when multiple formats are involved. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/curiously-recurring-template-pattern/README.md b/curiously-recurring-template-pattern/README.md index 7f94811ef..0cf750504 100644 --- a/curiously-recurring-template-pattern/README.md +++ b/curiously-recurring-template-pattern/README.md @@ -1,15 +1,17 @@ --- -title: Curiously Recurring Template Pattern +title: "Curiously Recurring Template Pattern in Java: Leveraging Polymorphism Uniquely" +shortTitle: Curiously Recurring Template Pattern (CRTP) +description: "Discover the Curiously Recurring Template Pattern (CRTP) in Java. Learn how to achieve static polymorphism for efficient method overriding and compile-time polymorphic behavior. Perfect for performance-critical applications." language: en category: Structural tag: - - Code simplification - - Extensibility - - Generic - - Idiom - - Instantiation - - Polymorphism - - Recursion + - Code simplification + - Extensibility + - Generic + - Idiom + - Instantiation + - Polymorphism + - Recursion --- ## Also known as @@ -20,29 +22,25 @@ tag: * Recursive Generic * Static Polymorphism -## Intent +## Intent of Curiously Recurring Template Pattern -Curiously Recurring Template Pattern (CRTP) is used to achieve a form of static polymorphism by having a class template derive from a template instantiation of its own class, allowing method overriding and polymorphic behavior at compile time rather than at runtime. +The Curiously Recurring Template Pattern (CRTP) is a powerful design pattern in Java used to achieve static polymorphism. By having a class template derive from a template instantiation of its own class, CRTP enables method overriding and compile-time polymorphic behavior, enhancing efficiency and performance in your Java applications. -## Explanation +## Detailed Explanation of Curiously Recurring Template Pattern with Real-World Examples Real-world example -> Consider a scenario where a library system manages various types of media: books, DVDs, and magazines. Each media type has specific attributes and behaviors, but they all share common functionality like borrowing and returning. -> -> Using the Curiously Recurring Template Pattern (CRTP), you can create a base template class `MediaItem` that includes these common methods. Each specific media type (e.g., `Book`, `DVD`, `Magazine`) would then inherit from `MediaItem` using itself as a template parameter. This allows each media type to customize the common functionality without the overhead of virtual methods. -> -> For example, `Book` would inherit from `MediaItem`, allowing the library system to use polymorphic behavior at compile-time, ensuring that each media type implements the necessary methods efficiently. This approach provides the benefits of polymorphism and code reuse while maintaining high performance and type safety. +> Consider a scenario where a library system manages various types of media: books, DVDs, and magazines. Each media type has specific attributes and behaviors, but they all share common functionality like borrowing and returning. By applying the Curiously Recurring Template Pattern (CRTP) in Java, you can create a base template class `MediaItem` encompassing these common methods. Each specific media type (e.g., `Book`, `DVD`, `Magazine`) would inherit from `MediaItem` using itself as a template parameter. This approach allows each media type to customize shared functionality efficiently, avoiding the overhead of virtual methods. In plain words -> Make certain methods within a type to accept arguments specific to its subtypes. +> The CRTP in Java ensures that certain methods within a type can accept arguments specific to its subtypes, enabling more efficient and type-safe polymorphic behavior at compile time. Wikipedia says > The curiously recurring template pattern (CRTP) is an idiom, originally in C++, in which a class X derives from a class template instantiation using X itself as a template argument. -**Programmatic example** +## Programmatic example of CRTP in Java For a mixed martial arts promotion that is planning an event, ensuring that the fights are organized between athletes of the same weight class is crucial. This prevents mismatches between fighters of significantly different sizes, such as a heavyweight facing off against a bantamweight. @@ -115,7 +113,7 @@ Program output: 08:42:34.054 [main] INFO crtp.MmaFighter -- MmaFighter(name=Dave, surname=Davidson, nickName=The Bug Smasher, speciality=Kickboxing) is going to fight against MmaFighter(name=Jack, surname=Jackson, nickName=The Pragmatic, speciality=Brazilian Jiu-Jitsu) ``` -## Applicability +## When to Use the Curiously Recurring Template Pattern in Java * When you need to extend the functionality of a class through inheritance but prefer compile-time polymorphism to runtime polymorphism for efficiency reasons. * When you want to avoid the overhead of virtual functions but still achieve polymorphic behavior. @@ -124,17 +122,17 @@ Program output: * You want to use a parameterized class method that can accept subclasses of the class as arguments, allowing it to be applied to objects that inherit from the class. * You want certain methods to work only with instances of the same type, such as for achieving mutual comparability. -## Tutorials +## Curiously Recurring Template Pattern Java Tutorials * [Curiously Recurring Template Pattern in Java (The NuaH Blog)](https://nuah.livejournal.com/328187.html) -## Known uses +## Real-World Applications of Curiously Recurring Template Pattern in Java * Implementing compile-time polymorphic interfaces in template libraries. * Enhancing code reuse in libraries where performance is critical, like in mathematical computations, embedded systems, and real-time processing applications. * Implementation of the `Cloneable` interface in various Java libraries. -## Consequences +## Benefits and Trade-offs of Curiously Recurring Template Pattern Benefits: @@ -148,13 +146,13 @@ Trade-offs: * Can lead to code bloat because each instantiation of a template results in a new class. * Less flexibility compared to runtime polymorphism as the behavior must be determined entirely at compile time. -## Related Patterns +## Related Java Design Patterns * [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Can be used in conjunction with CRTP to instantiate derived classes without knowing their specific types. * [Strategy](https://java-design-patterns.com/patterns/strategy/): CRTP can implement compile-time strategy selection. * [Template Method](https://java-design-patterns.com/patterns/template-method/): Similar in structure but differs in that CRTP achieves behavior variation through compile-time polymorphism. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/currying/README.md b/currying/README.md index 720937165..22806a50d 100644 --- a/currying/README.md +++ b/currying/README.md @@ -1,27 +1,29 @@ --- -title: Currying +title: "Currying Pattern in Java: Enhancing Function Flexibility and Reusability" +shortTitle: Currying +description: "Learn about currying in Java, a technique to simplify functions by breaking them into a sequence of single-argument functions. Discover its applications, benefits, and examples in this comprehensive guide." category: Functional language: en tag: - - Code simplification - - Functional decomposition - - Generic - - Immutable + - Code simplification + - Functional decomposition + - Generic + - Immutable --- ## Also known as * Partial Function Application -## Intent +## Intent of Currying Design Pattern -Currying decomposes a function that takes multiple arguments into a sequence of functions that each take a single argument. It helps in creating a higher-order function by partial application of its arguments. +Currying decomposes a function that takes multiple arguments into a sequence of functions that each take a single argument. This technique is integral in functional programming, enabling the creation of higher-order functions through partial application of its arguments. Using currying in Java can lead to more modular, reusable, and maintainable code. -## Explanation +## Detailed Explanation of Currying Pattern with Real-World Examples Real-world example -> Currying in programming can be compared to an assembly line in a factory. Imagine a car manufacturing process where each station on the assembly line performs a specific task, such as installing the engine, painting the car, and adding the wheels. Each station takes a partially completed car and performs a single operation before passing it to the next station. Similarly, in currying, a function that requires multiple arguments is broken down into a series of functions, each taking a single argument and returning another function until all arguments are provided. This step-by-step processing simplifies complex tasks by dividing them into manageable, sequential operations. +> Currying in programming can be compared to an assembly line in a factory. Imagine a car manufacturing process where each station on the assembly line performs a specific task, such as installing the engine, painting the car, and adding the wheels. Each station takes a partially completed car and performs a single operation before passing it to the next station. Similarly, in currying, a function that requires multiple arguments is broken down into a series of functions, each taking a single argument and returning another function until all arguments are provided. This step-by-step processing simplifies complex tasks by dividing them into manageable, sequential operations, which is especially useful in Java functional programming. In plain words @@ -31,7 +33,7 @@ Wikipedia says > In mathematics and computer science, currying is the technique of translating a function that takes multiple arguments into a sequence of families of functions, each taking a single argument. -**Programmatic example** +## Programmatic example of Currying Pattern in Java Consider a librarian who wants to populate their library with books. The librarian wants functions which can create books corresponding to specific genres and authors. Currying makes this possible by writing a curried book builder function and utilising partial application. @@ -184,25 +186,26 @@ Program output: 09:04:52.506 [main] INFO com.iluwatar.currying.App -- Book{genre=SCIFI, author='Isaac Asimov', title='Foundation', publicationDate=1942-05-01} ``` -## Applicability +## When to Use the Currying Pattern in Java -* When functions need to be called with some arguments preset. +* When functions need to be called with some arguments preset in Java. * In functional programming languages or paradigms to simplify functions that take multiple arguments. -* To improve code reusability and composability by breaking down functions into simpler, unary functions. +* To improve code reusability and composability by breaking down functions into simpler, unary functions, enhancing the modularity of Java applications. -## Tutorials +## Currying Pattern Java Tutorials * [Currying in Java (Baeldung)](https://www.baeldung.com/java-currying) * [What Is Currying in Programming (Towards Data Science)](https://towardsdatascience.com/what-is-currying-in-programming-56fd57103431#:~:text=Currying%20is%20helpful%20when%20you,concise%2C%20and%20more%20readable%20solution.) * [Why the fudge should I use currying? (DailyJS)](https://medium.com/dailyjs/why-the-fudge-should-i-use-currying-84e4000c8743) -## Known uses +## Real-World Applications of Currying Pattern in Java * Functional programming languages like Haskell, Scala, and JavaScript. +* Java programming, especially with lambda expressions and streams introduced in Java 8. * Event handling in UIs where a function with specific parameters needs to be triggered upon an event. * APIs that require configuration with multiple parameters. -## Consequences +## Benefits and Trade-offs of Currying Pattern Benefits: @@ -217,13 +220,13 @@ Trade-offs: * Can be less intuitive for developers unfamiliar with functional programming concepts. * As shown in the programmatic example above, curried functions with several parameters have a cumbersome type signature in Java. -## Related patterns +## Related Java Design Patterns * Function Composition: Currying is often used in conjunction with function composition to enable more readable and concise code. * [Decorator](https://java-design-patterns.com/patterns/decorator/): While not the same, currying shares the decorator pattern's concept of wrapping functionality. * [Factory](https://java-design-patterns.com/patterns/factory/): Currying can be used to create factory functions that produce variations of a function with certain arguments preset. -## Credits +## References and Credits * [Functional Programming in Java: Harnessing the Power Of Java 8 Lambda Expressions](https://amzn.to/3TKeZPD) * [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://amzn.to/3J6vEaW) diff --git a/data-access-object/README.md b/data-access-object/README.md index 18d232aef..1491eacf3 100644 --- a/data-access-object/README.md +++ b/data-access-object/README.md @@ -1,14 +1,16 @@ --- -title: Data Access Object +title: "Data Access Object Pattern in Java: Streamlining Database Interaction" +shortTitle: Data Access Object (DAO) +description: "Explore the Java Data Access Object (DAO) pattern to effectively separate business logic from database operations. Learn implementation strategies, real-world examples, and best practices." category: Structural language: en tag: - - Abstraction - - Data access - - Data processing - - Decoupling - - Layered architecture - - Persistence + - Abstraction + - Data access + - Data processing + - Decoupling + - Layered architecture + - Persistence --- ## Also known as @@ -16,11 +18,11 @@ tag: * Data Access Layer * DAO -## Intent +## Intent of Data Access Object Design Pattern The Data Access Object (DAO) design pattern aims to separate the application's business logic from the persistence layer, typically a database or any other storage mechanism. By using DAOs, the application can access and manipulate data without being dependent on the specific database implementation details. -## Explanation +## Detailed Explanation of Data Access Object Pattern with Real-World Examples Real-world example @@ -34,7 +36,7 @@ Wikipedia says > In computer software, a data access object (DAO) is a pattern that provides an abstract interface to some type of database or other persistence mechanism. -**Programmatic Example** +## Programmatic Example of DAO Pattern in Java There's a set of customers that need to be persisted to database. Additionally, we need the whole set of CRUD (create/read/update/delete) operations, so we can operate on customers easily. @@ -193,11 +195,11 @@ The program output: 10:02:09.898 [main] INFO com.iluwatar.dao.App -- customerDao.getAllCustomers(): java.util.stream.ReferencePipeline$Head@f2f2cc1 ``` -## Class diagram +## Detailed Explanation of Data Access Object Pattern with Real-World Examples ![Data Access Object](./etc/dao.png "Data Access Object") -## Applicability +## When to Use the Data Access Object Pattern in Java Use the Data Access Object in any of the following situations: @@ -205,18 +207,18 @@ Use the Data Access Object in any of the following situations: * The application needs to support multiple types of databases or storage mechanisms without significant code changes. * You want to keep the database access clean and simple, and separate from business logic. -## Tutorials +## Data Access Object Pattern Java Tutorials * [The DAO Pattern in Java(Baeldung)](https://www.baeldung.com/java-dao-pattern) * [Data Access Object Pattern (TutorialsPoint)](https://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm) -## Known Uses +## Real-World Applications of DAO Pattern in Java * Enterprise applications that require database interaction. * Applications requiring data access to be adaptable to multiple storage types (relational databases, XML files, flat files, etc.). * Frameworks providing generic data access functionalities. -## Consequences +## Benefits and Trade-offs of Data Access Object Pattern Benefits: @@ -231,14 +233,14 @@ Trade-offs: * Overhead: For simple applications, the DAO pattern might introduce more overhead than necessary. * Learning Curve: Developers might need time to understand and implement the pattern effectively, especially in complex projects. -## Related Patterns +## Related Java Design Patterns * [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Helps in abstracting the creation of DAOs, especially when supporting multiple databases or storage mechanisms. * [Factory](https://java-design-patterns.com/patterns/factory/): Can be used to instantiate DAOs dynamically, providing flexibility in the choice of implementation. * [Service Layer](https://java-design-patterns.com/patterns/service-layer/): Often used in conjunction with the DAO pattern to define application's boundaries and its set of available operations. * [Strategy](https://java-design-patterns.com/patterns/strategy/): Might be employed to change the data access strategy at runtime, depending on the context. -## Credits +## References and Credits * [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/49u3r91) * [Expert One-on-One J2EE Design and Development](https://amzn.to/3vK3pfq) diff --git a/data-bus/README.md b/data-bus/README.md index fecc899a2..a033253cf 100644 --- a/data-bus/README.md +++ b/data-bus/README.md @@ -1,13 +1,15 @@ --- -title: Data Bus +title: "Data Bus Pattern in Java: Unifying Component Communication Efficiently" +shortTitle: Data Bus +description: "Explore the Data Bus pattern in Java for centralized communication and event handling. Learn how to decouple components, enhance scalability, and maintainability with practical examples and real-world applications." category: Messaging language: en tag: - - Decoupling - - Event-driven - - Messaging - - Publish/subscribe - - Scalability + - Decoupling + - Event-driven + - Messaging + - Publish/subscribe + - Scalability --- ## Also known as @@ -15,21 +17,21 @@ tag: * Event Bus * Message Bus -## Intent +## Intent of Data Bus Design Pattern The Data Bus design pattern aims to provide a centralized communication channel through which various components of a system can exchange data without being directly connected, thus promoting loose coupling and enhancing scalability and maintainability. -## Explanation +## Detailed Explanation of Data Bus Pattern with Real-World Examples Real-world example -> Consider a large airport as an analogous real-world example of the Data Bus design pattern. In an airport, various airlines, passengers, baggage handlers, and security personnel all need to communicate and share information. Instead of each entity communicating directly with every other entity, the airport uses a centralized announcement system (the Data Bus). Flight information, security alerts, and other critical updates are broadcast over this system, and each entity listens for the messages relevant to them. This setup allows the airport to decouple the communication process, ensuring that each entity only receives the information they need, while allowing the system to scale and integrate new entities without disrupting the existing ones. +> Consider a large airport as an analogous real-world example of the Data Bus pattern. In an airport, various airlines, passengers, baggage handlers, and security personnel all need to communicate and share information. Instead of each entity communicating directly with every other entity, the airport uses a centralized announcement system (the Data Bus). Flight information, security alerts, and other critical updates are broadcast over this system, and each entity listens for the messages relevant to them. This setup allows the airport to decouple the communication process, ensuring that each entity only receives the information they need, while allowing the system to scale and integrate new entities without disrupting the existing ones. This is similar to how the Data Bus pattern in Java promotes centralized communication and event handling, enhancing system scalability and maintainability. In plain words -> Data Bus is a design pattern that is able to connect components of an application for communication simply and solely by the type of message or event that may be transferred. +> Data Bus is a design pattern that connects components of an application for communication based on the type of message or event being transferred. This pattern promotes decoupling, making it easier to scale and maintain the system by allowing components to communicate without direct dependencies. -**Programmatic Example** +## Programmatic Example of Data Bus Pattern in Java Say you have an app that enables online bookings and participation in events. You want the app to send notifications, such as event advertisements, to all ordinary members of the community or organization holding the events. However, you do not want to send such advertisements to event administrators or organizers. Instead, you want to send them notifications about the timing of new advertisements sent to all members. The Data Bus enables you to selectively notify community members by type (ordinary members or event administrators) by making their classes or components only accept messages of a certain type. Thus, ordinary members and administrators do not need to know about each other or the specific classes or components used to notify the entire community, except for knowing the type of messages being sent. @@ -148,20 +150,21 @@ When the data bus publishes a message, the output is as follows: As shown, `MessageCollectorMembers` only accept messages of type `MessageData`, so they do not see the `StartingData` or `StoppingData` messages, which are only visible to `StatusMember` (the event administrators or organizers). This selective message handling prevents ordinary community members from receiving administrative notifications. -## Applicability +## When to Use the Data Bus Pattern in Java * When multiple components need to share data or events but direct coupling is undesirable. -* In complex systems where the flow of information varies dynamically. +* In complex, event-driven systems where the flow of information varies dynamically. * In distributed systems where components might be deployed across different environments. +* In microservices architectures for inter-service communication. -## Known Uses +## Real-World Applications of Data Bus Pattern in Java * Event handling systems in large-scale applications. * Microservices architectures for inter-service communication. * Real-time data processing systems, such as stock trading platforms. * In frameworks like Spring, particularly with its application event mechanism. -## Consequences +## Benefits and Trade-offs of Data Bus Pattern Benefits: @@ -176,13 +179,13 @@ Trade-offs: * Performance Overhead: The additional layer of communication may introduce latency. * Debugging Difficulty: Tracing data flow through the bus can be challenging, especially in systems with many events. -## Related Patterns +## Related Java Design Patterns * [Mediator](https://java-design-patterns.com/patterns/mediator/): Facilitates communication between components, but unlike Data Bus, it centralizes control. * [Observer](https://java-design-patterns.com/patterns/observer/): Similar in nature to the publish-subscribe mechanism used in Data Bus for notifying changes to multiple objects. * Publish/Subscribe: The Data Bus pattern is often implemented using the publish-subscribe mechanism, where publishers post messages to the bus without knowledge of the subscribers. -## Credits +## References and Credits * [Enterprise Integration Patterns](https://amzn.to/3J6WoYS) * [Pattern-Oriented Software Architecture, Volume 4: A Pattern Language for Distributed Computing](https://amzn.to/3PTRGBM) diff --git a/data-locality/README.md b/data-locality/README.md index bd92cb746..9056b2025 100644 --- a/data-locality/README.md +++ b/data-locality/README.md @@ -1,13 +1,15 @@ --- -title: Data Locality +title: "Data Locality Pattern in Java: Boosting Performance with Efficient Data Management" +shortTitle: Data Locality +description: "Learn about the Data Locality pattern in Java, a technique to optimize performance by improving cache utilization and minimizing data access times. Ideal for game development and high-performance computing." category: Performance optimization language: en tag: - - Caching - - Data access - - Game programming - - Memory management - - Performance + - Caching + - Data access + - Game programming + - Memory management + - Performance --- ## Also known as @@ -15,11 +17,11 @@ tag: * Cache-Friendly Design * Data-Oriented Design -## Intent +## Intent of Data Locality Design Pattern -The Data Locality design pattern aims to minimize data access times and improve cache utilization by arranging data in memory to take advantage of spatial locality. This pattern is particularly useful in high-performance computing and game development where access speed is crucial. +The Data Locality design pattern aims to minimize data access times and improve cache utilization by arranging data in memory to take advantage of spatial locality. This pattern is particularly useful in high-performance computing, real-time data processing, and game development where access speed is crucial. -## Explanation +## Detailed Explanation of Data Locality Pattern with Real-World Examples Real-world example @@ -27,9 +29,9 @@ Real-world example In plain words -> The Data Locality pattern organizes data in memory to reduce access times and improve performance by ensuring that data frequently accessed together is stored close together. +> The Data Locality pattern organizes data in memory to reduce access times and improve performance by ensuring that data frequently accessed together is stored close together. This is crucial for high-performance applications like game engines and real-time data processing systems. -**Programmatic Example** +## Programmatic Example of Data Locality Pattern in Java The Data Locality pattern is a design pattern that aims to improve performance by arranging data in memory to take advantage of spatial locality. This pattern is particularly useful in high-performance computing and game development where access speed is crucial. @@ -118,25 +120,27 @@ The console output: In this way, the data-locality module demonstrates the Data Locality pattern. By updating all components of the same type together, it increases the likelihood that the data needed for the update is already in the cache, thereby improving performance. -## Class diagram +## Detailed Explanation of Data Locality Pattern with Real-World Examples ![Data Locality](./etc/data-locality.urm.png "Data Locality pattern class diagram") -## Applicability +## When to Use the Data Locality Pattern in Java This pattern is applicable in scenarios where large datasets are processed and performance is critical. It's particularly useful in: * Game development for efficient rendering and physics calculations. * High-performance computing tasks that require rapid access to large data sets. * Real-time data processing systems where latency is a critical factor. +* Scientific computing applications needing optimized matrix operations. +* Data-intensive applications requiring enhanced memory access patterns. -## Known Uses +## Real-World Applications of Data Locality Pattern in Java * Game engines (e.g., Unity, Unreal Engine) to optimize entity and component data access. * High-performance matrix libraries in scientific computing to optimize matrix operations. * Real-time streaming data processing systems for efficient data manipulation and access. -## Consequences +## Benefits and Trade-offs of Data Locality Pattern Benefits: @@ -150,13 +154,13 @@ Trade-offs: * Maintenance Overhead: As data access patterns evolve, the layout may need to be re-evaluated, adding to the maintenance overhead. * Less Flexibility: The tight coupling of data layout to access patterns can reduce flexibility in how data structures are used and evolved over time. -## Related Patterns +## Related Java Design Patterns * [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Can be used in conjunction with Data Locality to share data efficiently among multiple objects. * [Object Pool](https://java-design-patterns.com/patterns/object-pool/): Often used together to manage a group of initialized objects that can be reused, further optimizing memory usage and access. * [Iterator](https://java-design-patterns.com/patterns/iterator/): Facilitates navigation through a collection of data laid out with data locality in mind. -## Credits +## References and Credits * [Effective Java](https://amzn.to/4cGk2Jz) * [Game Programming Patterns](https://amzn.to/3vK8c0d) diff --git a/data-mapper/README.md b/data-mapper/README.md index 0bbdf5f87..92c8e3021 100644 --- a/data-mapper/README.md +++ b/data-mapper/README.md @@ -1,24 +1,26 @@ --- -title: Data Mapper +title: "Data Mapper Pattern in Java: Decoupling Data Storage from Business Logic" +shortTitle: Data Mapper +description: "Explore the Data Mapper pattern in Java, which decouples database operations from business logic. Learn how to implement and utilize this pattern to enhance maintainability and flexibility in your Java applications." category: Behavioral language: en tag: - - Data access - - Decoupling - - Domain - - Object mapping - - Persistence + - Data access + - Decoupling + - Domain + - Object mapping + - Persistence --- ## Also known as * Object-Relational Mapping (ORM) -## Intent +## Intent of the Data Mapper Pattern -The Data Mapper pattern aims to create an abstraction layer between the database and the business logic, allowing them to evolve independently. It maps data from the database objects to in-memory data structures and vice versa, minimizing direct dependencies between the application's core logic and the underlying database structure. +The Data Mapper pattern aims to create an abstraction layer between the database and the business logic, allowing them to evolve independently. It maps data from the database objects to in-memory data structures and vice versa, minimizing direct dependencies between the application's core logic and the underlying database structure. This decoupling is essential in promoting maintainability and flexibility in Java programming. -## Explanation +## Detailed Explanation of Data Mapper Pattern with Real-World Examples Real-world example @@ -32,7 +34,7 @@ Wikipedia says > A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in-memory data representation (the domain layer). The goal of the pattern is to keep the in-memory representation and the persistent data store independent of each other and the data mapper itself. This is useful when one needs to model and enforce strict business processes on the data in the domain layer that do not map neatly to the persistent data store. -**Programmatic Example** +## Programmatic Example of Data Mapper Pattern in Java The Data Mapper is a design pattern that separates the in-memory objects from the database. Its responsibility is to transfer data between the two and also to isolate them from each other. This pattern promotes the [Single Responsibility Principle](https://java-design-patterns.com/principles/#single-responsibility-principle) and [Separation of Concerns](https://java-design-patterns.com/principles/#separation-of-concerns). @@ -117,7 +119,7 @@ Program output: 13:54:29.238 [main] DEBUG com.iluwatar.datamapper.App -- App.main(), student : Student(studentId=1, name=AdamUpdated, grade=A), is going to be deleted ``` -## Applicability +## When to Use the Data Mapper Pattern in Java Use the Data Mapper in any of the following situations @@ -125,19 +127,19 @@ Use the Data Mapper in any of the following situations * In applications requiring an ORM tool to bridge the gap between object-oriented models and relational databases. * When working with complex database schemas where direct data manipulation and object creation lead to cumbersome and error-prone code. -## Tutorials +## Data Mapper Pattern Java Tutorials * [Spring Boot RowMapper (ZetCode)](https://zetcode.com/springboot/rowmapper/) * [Spring BeanPropertyRowMapper tutorial (ZetCode)](https://zetcode.com/spring/beanpropertyrowmapper/) * [Data Transfer Object Pattern in Java - Implementation and Mapping (StackAbuse)](https://stackabuse.com/data-transfer-object-pattern-in-java-implementation-and-mapping/) -## Known uses +## Real-World Applications of Data Mapper Pattern in Java * ORM frameworks such as Hibernate in Java. * Data access layers in enterprise applications where business logic and database management are kept separate. * Applications requiring database interactions without tying the code to a specific database implementation. -## Consequences +## Benefits and Trade-offs of Data Mapper Pattern Benefits: @@ -151,14 +153,14 @@ Trade-offs: * Might lead to performance overhead due to the abstraction layer, especially in large-scale applications or with complex queries. * Requires developers to learn and understand the abstraction layer in addition to the database and ORM framework being used. -## Related patterns +## Related Java Design Patterns * Active Record: Combines data access logic and business logic in the domain entities themselves, contrary to Data Mapper's separation of concerns. * Object–Relational Mapping (ORM): A technique to map object-oriented programming language data to a relational database. * [Repository](https://java-design-patterns.com/patterns/repository/): Provides an abstraction of the data layer, acting as a collection of domain objects in memory. * [Unit of Work](https://java-design-patterns.com/patterns/unit-of-work/): Manages transactions and keeps track of the objects affected by a business transaction to ensure changes are consistent and transactional. -## Credits +## References and Credits * [Clean Architecture: A Craftsman's Guide to Software Structure and Design](https://amzn.to/3xyEFag) * [Java Persistence with Hibernate](https://amzn.to/3VNzlKe) diff --git a/data-transfer-object/README.md b/data-transfer-object/README.md index 747190254..40d2c1eb0 100644 --- a/data-transfer-object/README.md +++ b/data-transfer-object/README.md @@ -1,13 +1,15 @@ --- -title: Data Transfer Object +title: "Data Transfer Object Pattern in Java: Simplifying Data Exchange Between Subsystems" +shortTitle: Data Transfer Object (DTO) +description: "Learn about the Data Transfer Object (DTO) pattern, its implementation, and practical uses in Java applications. Optimize data transfer between layers with this structural design pattern." category: Structural language: en tag: - - Client-server - - Data transfer - - Decoupling - - Layered architecture - - Optimization + - Client-server + - Data transfer + - Decoupling + - Layered architecture + - Optimization --- ## Also known as @@ -15,11 +17,11 @@ tag: * Transfer Object * Value Object -## Intent +## Intent of Data Transfer Object Design Pattern The Data Transfer Object (DTO) pattern is used to transfer data between software application subsystems or layers, particularly in the context of network calls or database retrieval in Java applications. It reduces the number of method calls by aggregating the data in a single transfer. -## Explanation +## Detailed Explanation of Data Transfer Object Pattern with Real-World Examples Real-world example @@ -27,13 +29,13 @@ Real-world example In plain words -> Using DTO relevant information can be fetched with a single backend query. +> Using DTO, relevant information can be fetched with a single backend query. Wikipedia says > In the field of programming a data transfer object (DTO) is an object that carries data between processes. The motivation for its use is that communication between processes is usually done resorting to remote interfaces (e.g. web services), where each call is an expensive operation. Because the majority of the cost of each call is related to the round-trip time between the client and the server, one way of reducing the number of calls is to use an object (the DTO) that aggregates the data that would have been transferred by the several calls, but that is served by one call only. -**Programmatic Example** +## Programmatic Example of DTO Pattern in Java Let's first introduce our simple `CustomerDTO` record. @@ -164,7 +166,7 @@ The console output: 11:10:51.856 [main] INFO com.iluwatar.datatransfer.App -- ####### List of products after adding PS5: [Product{id=1, name='TV', price=1000.0, cost=1090.0, supplier='Sony'}, Product{id=2, name='microwave', price=1000.0, cost=1090.0, supplier='Delonghi'}, Product{id=3, name='refrigerator', price=1000.0, cost=1090.0, supplier='Botsch'}, Product{id=4, name='airConditioner', price=1000.0, cost=1090.0, supplier='LG'}, Product{id=5, name='PS5', price=1220.0, cost=1000.0, supplier='Sony'}] ``` -## Applicability +## When to Use the Data Transfer Object Pattern in Java Use the Data Transfer Object pattern when: @@ -172,19 +174,19 @@ Use the Data Transfer Object pattern when: * In scenarios where batch processing of data is preferred over individual processing. * When working with remote interfaces, to encapsulate the data transfer in a serializable object that can be easily transmitted. -## Tutorials +## Data Transfer Object Pattern Java Tutorials * [Data Transfer Object Pattern in Java - Implementation and Mapping (StackAbuse)](https://stackabuse.com/data-transfer-object-pattern-in-java-implementation-and-mapping/) * [Design Pattern - Transfer Object Pattern (TutorialsPoint)](https://www.tutorialspoint.com/design_pattern/transfer_object_pattern.htm) * [The DTO Pattern (Baeldung)](https://www.baeldung.com/java-dto-pattern) -## Known Uses +## Real-World Applications of DTO Pattern in Java * Remote Method Invocation (RMI) in Java, where DTOs are used to pass data across network. * Enterprise JavaBeans (EJB), particularly when data needs to be transferred from EJBs to clients. * Various web service frameworks where DTOs encapsulate request and response data. -## Consequences +## Benefits and Trade-offs of Data Transfer Object Pattern Benefits: @@ -204,7 +206,7 @@ Trade-offs: * [Facade](https://java-design-patterns.com/patterns/facade/): Similar to DTO, a Facade may aggregate multiple calls into one, improving efficiency. * [Service Layer](https://java-design-patterns.com/patterns/service-layer/): Often involves using DTOs to transfer data across the boundary between the service layer and its clients. -## Credits +## References and Credits * [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cKndQp) * [J2EE Design Patterns](https://amzn.to/4dpzgmx) diff --git a/decorator/README.md b/decorator/README.md index 0acd81111..ddd8a61a0 100644 --- a/decorator/README.md +++ b/decorator/README.md @@ -1,13 +1,15 @@ --- -title: Decorator +title: "Decorator Pattern in Java: Extending Classes Dynamically" +shortTitle: Decorator +description: "Learn how the Decorator Design Pattern enhances flexibility in Java programming by allowing dynamic addition of responsibilities to objects without modifying their existing code. Explore real-world examples and implementation." category: Structural language: en tag: - - Enhancement - - Extensibility - - Gang of Four - - Object composition - - Wrapping + - Enhancement + - Extensibility + - Gang of Four + - Object composition + - Wrapping --- ## Also known as @@ -15,11 +17,11 @@ tag: * Smart Proxy * Wrapper -## Intent +## Intent of Decorator Design Pattern -The Decorator pattern allows for the dynamic addition of responsibilities to objects without modifying their existing code. It achieves this by providing a way to "wrap" objects within objects of similar interface. +The Decorator pattern allows for the dynamic addition of responsibilities to objects without modifying their existing code. It achieves this by providing a way to "wrap" objects within objects of similar interface, enhancing Java design patterns flexibility. -## Explanation +## Detailed Explanation of Decorator Pattern with Real-World Examples Real-world example @@ -33,7 +35,7 @@ Wikipedia says > In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern as well as to the Open-Closed Principle, by allowing the functionality of a class to be extended without being modified. -**Programmatic Example** +## Programmatic Example of Decorator Pattern in Java There is an angry troll living in the nearby hills. Usually, it goes bare-handed, but sometimes it has a weapon. To arm the troll it's not necessary to create a new troll but to decorate it dynamically with a suitable weapon. @@ -131,33 +133,33 @@ Program output: 11:34:18.101 [main] INFO com.iluwatar.decorator.App -- Clubbed troll power: 20. ``` -## Applicability +## When to Use the Decorator Pattern in Java Decorator is used to: -* Add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects. +* Add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects, a key feature of Java design patterns. * For responsibilities that can be withdrawn. * When extending a class is impractical due to the proliferation of subclasses that could result. * For when a class definition might be hidden or otherwise unavailable for subclassing. -## Tutorials +## Decorator Pattern Java Tutorials * [Decorator Design Pattern in Java Example (DigitalOcean)](https://www.digitalocean.com/community/tutorials/decorator-design-pattern-in-java-example) -## Known uses +## Real-World Applications of Decorator Pattern in Java * GUI toolkits often use decorators to dynamically add behaviors like scrolling, borders, or layout management to components. -* [java.io.InputStream](http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html), [java.io.OutputStream](http://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html), [java.io.Reader](http://docs.oracle.com/javase/8/docs/api/java/io/Reader.html) and [java.io.Writer](http://docs.oracle.com/javase/8/docs/api/java/io/Writer.html) +* The [java.io.InputStream](http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html), [java.io.OutputStream](http://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html), [java.io.Reader](http://docs.oracle.com/javase/8/docs/api/java/io/Reader.html) and [java.io.Writer](http://docs.oracle.com/javase/8/docs/api/java/io/Writer.html) classes in Java are well-known examples utilizing the Decorator pattern. * [java.util.Collections#synchronizedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedCollection-java.util.Collection-) * [java.util.Collections#unmodifiableXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableCollection-java.util.Collection-) * [java.util.Collections#checkedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#checkedCollection-java.util.Collection-java.lang.Class-) -## Consequences +## Benefits and Trade-offs of Decorator Pattern Benefits: * Greater flexibility than static inheritance. -* Avoids feature-laden classes high up in the hierarchy. +* Avoids feature-laden classes high up in the hierarchy, showcasing the power of Java design patterns. * A decorator and its component aren't identical. * Responsibilities can be added or removed at runtime. @@ -167,13 +169,13 @@ Trade-offs: * Decorators can lead to a system with lots of small objects that look alike to the programmer, making the desired configuration hard to achieve. * Overuse can complicate the code structure due to the introduction of numerous small classes. -## Related Patterns +## Related Java Design Patterns * [Adapter](https://java-design-patterns.com/patterns/adapter/): A decorator changes an object's responsibilities, while an adapter changes an object's interface. * [Composite](https://java-design-patterns.com/patterns/composite/): Decorators can be viewed as a degenerate composite with only one component. However, a decorator adds additional responsibilities—it isn't intended for object aggregation. * [Strategy](https://java-design-patterns.com/patterns/strategy/): Decorator lets you change the skin of an object, while Strategy lets you change the guts. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Functional Programming in Java](https://amzn.to/3JUIc5Q) diff --git a/delegation/README.md b/delegation/README.md index fa3b1d570..8c90d8ee8 100644 --- a/delegation/README.md +++ b/delegation/README.md @@ -1,11 +1,13 @@ --- -title: Delegation +title: "Delegation Pattern in Java: Mastering Efficient Task Assignment" +shortTitle: Delegation +description: "Explore the Delegation Design Pattern in Java with real-world examples, class diagrams, and its benefits. Learn how to enhance your code flexibility and reuse." category: Behavioral language: en tag: - - Decoupling - - Delegation - - Object composition + - Decoupling + - Delegation + - Object composition --- ## Also known as @@ -13,11 +15,11 @@ tag: * Helper * Surrogate -## Intent +## Intent of Delegation Design Pattern To allow an object to delegate responsibility for a task to another helper object. -## Explanation +## Detailed Explanation of Delegation Pattern with Real-World Examples Real-world example @@ -31,7 +33,7 @@ Wikipedia says > In object-oriented programming, delegation refers to evaluating a member (property or method) of one object (the receiver) in the context of another original object (the sender). Delegation can be done explicitly, by passing the sending object to the receiving object, which can be done in any object-oriented language; or implicitly, by the member lookup rules of the language, which requires language support for the feature. -**Programmatic Example** +## Programmatic Example of Delegation Pattern in Java Let's consider a printing example. @@ -85,7 +87,7 @@ public class PrinterController implements Printer { } ``` -Now on the client code printer controllers can print messages differently depending on the object they're delegating that work to. +In the client code, printer controllers can print messages differently depending on the object they're delegating that work to. ```java public class App { @@ -112,23 +114,23 @@ Canon Printer:hello world Epson Printer:hello world ``` -## Class diagram +## Detailed Explanation of Delegation Pattern with Real-World Examples ![Delegate class diagram](./etc/delegation.png "Delegate") -## Applicability +## When to Use the Delegation Pattern in Java * When you want to pass responsibility from one class to another without inheritance. * To achieve composition-based reuse instead of inheritance-based. * When you need to use several interchangeable helper classes at runtime. -## Known Uses +## Real-World Applications of Delegation Pattern in Java * Java's java.awt.event package, where listeners are often used to handle events. * Wrapper classes in Java's Collections Framework (java.util.Collections), which delegate to other collection objects. * In Spring Framework, delegation is used extensively in the IoC container where beans delegate tasks to other beans. -## Consequences +## Benefits and Trade-offs of Delegation Pattern Benefits: @@ -141,13 +143,13 @@ Trade-offs: * Runtime Overhead: Delegation can introduce additional layers of indirection, which may result in slight performance costs. * Complexity: The design can become more complicated since it involves additional classes and interfaces to manage delegation. -## Related Patterns +## Related Java Design Patterns * [Composite](https://java-design-patterns.com/patterns/composite/): Delegation can be used within a composite pattern to delegate component-specific behavior to child components. * [Strategy](https://java-design-patterns.com/patterns/strategy/): Delegation is often used in the strategy pattern where a context object delegates tasks to a strategy object. * https://java-design-patterns.com/patterns/proxy/: The proxy pattern is a form of delegation where a proxy object controls access to another object, which it delegates work to. -## Credits +## References and Credits * [Effective Java](https://amzn.to/4aGE7gX) * [Head First Design Patterns](https://amzn.to/3J9tuaB) diff --git a/dependency-injection/README.md b/dependency-injection/README.md index d449452b2..51b138c20 100644 --- a/dependency-injection/README.md +++ b/dependency-injection/README.md @@ -1,11 +1,13 @@ --- -title: Dependency Injection +title: "Dependency Injection Pattern in Java: Boosting Maintainability with Loose Coupling" +shortTitle: Dependency Injection +description: "Learn about the Dependency Injection design pattern. Explore its benefits, real-world examples, class diagrams, and best practices for implementation in Java." category: Creational language: en tag: - - Decoupling - - Dependency management - - Inversion of control + - Decoupling + - Dependency management + - Inversion of control --- ## Also known as @@ -13,11 +15,11 @@ tag: * Inversion of Control (IoC) * Dependency Inversion -## Intent +## Intent of Dependency Injection Design Pattern To decouple the creation of object dependencies from their usage, allowing for more flexible and testable code. -## Explanation +## Detailed Explanation of Dependency Injection Pattern with Real-World Examples Real-world example @@ -27,13 +29,13 @@ Real-world example In plain words -> Dependency Injection separates creation of client's dependencies from its own behavior. +> Dependency Injection separates the creation of the client's dependencies from its own behavior. Wikipedia says > In software engineering, dependency injection is a technique in which an object receives other objects that it depends on. These other objects are called dependencies. -**Programmatic Example** +## Programmatic Example of Dependency Injection Pattern in Java The old wizard likes to fill his pipe and smoke tobacco once in a while. However, he doesn't want to depend on a single tobacco brand only but likes to be able to enjoy them all interchangeably. @@ -112,23 +114,23 @@ The program output: 11:54:05.308 [main] INFO com.iluwatar.dependency.injection.Tobacco -- GuiceWizard smoking RivendellTobacco ``` -## Class diagram +## Detailed Explanation of Dependency Injection Pattern with Real-World Examples ![Dependency Injection](./etc/dependency-injection.png "Dependency Injection") -## Applicability +## When to Use the Dependency Injection Pattern in Java * When aiming to reduce the coupling between classes and increase the modularity of the application. * In scenarios where the object creation process is complex or should be separated from the class usage. * In applications requiring easier unit testing by allowing dependencies to be mocked or stubbed. * Within frameworks or libraries that manage object lifecycles and dependencies, such as Spring or Jakarta EE (formerly Java EE). -## Known Uses +## Real-World Applications of Dependency Injection Pattern in Java -* Frameworks like Spring, Jakarta EE, and Google Guice use DI extensively to manage component lifecycles and dependencies. +* Frameworks like Spring, Jakarta EE, and Google Guice use Dependency Injection (DI) extensively to manage component lifecycles and dependencies. * Desktop and web applications that require flexible architecture with easily interchangeable components. -## Consequences +## Benefits and Trade-offs of Dependency Injection Pattern Benefits: @@ -139,16 +141,16 @@ Benefits: Trade-offs: * Can introduce complexity in the configuration, especially in large projects. -* Might increase the learning curve for developers unfamiliar with DI patterns or frameworks. +* Might increase the learning curve for developers unfamiliar with Dependency Injection patterns or frameworks. * Requires careful management of object lifecycles and scopes. -## Related Patterns +## Related Java Design Patterns * [Factory Method](https://java-design-patterns.com/patterns/factory-method/) and [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Used to create instances that the DI mechanism will inject. * [Service Locator](https://java-design-patterns.com/patterns/service-locator/): An alternative to DI for locating services or components, though it does not decouple the lookup process as effectively as DI. * [Singleton](https://java-design-patterns.com/patterns/singleton/): Often used in conjunction with DI to provide a single instance of a service across the application. -## Credits +## References and Credits * [Clean Code: A Handbook of Agile Software Craftsmanship](https://amzn.to/3wRnjp5) * [Dependency Injection: Design patterns using Spring and Guice](https://amzn.to/4aMyHkI) diff --git a/dirty-flag/README.md b/dirty-flag/README.md index a87feafe3..6abcedad1 100644 --- a/dirty-flag/README.md +++ b/dirty-flag/README.md @@ -1,12 +1,14 @@ --- -title: Dirty Flag +title: "Dirty Flag Pattern in Java: Optimizing Performance with Change Tracking" +shortTitle: Dirty Flag +description: "Learn about the Dirty Flag design pattern in Java for efficient state tracking and resource management. Avoid unnecessary computations with practical examples and use cases." category: Behavioral language: en tag: - - Game programming - - Performance - - Resource management - - State tracking + - Game programming + - Performance + - Resource management + - State tracking --- ## Also known as @@ -14,11 +16,11 @@ tag: * Change Tracking * Is-Modified Flag -## Intent +## Intent of Dirty Flag Design Pattern The Dirty Flag design pattern is employed to avoid unnecessary computations or resource-heavy operations by maintaining a boolean flag that tracks whether the state of an object has changed ('dirty') or remains unchanged ('clean'). This flag, when set, indicates that a particular operation, such as recalculating or refreshing data, needs to be performed again to reflect the updated state. -## Explanation +## Detailed Explanation of Dirty Flag Pattern with Real-World Examples Real-world example @@ -32,7 +34,7 @@ Wikipedia says > A dirty bit or modified bit is a bit that is associated with a block of computer memory and indicates whether the corresponding block of memory has been modified. The dirty bit is set when the processor writes to (modifies) this memory. The bit indicates that its associated block of memory has been modified and has not been saved to storage yet. When a block of memory is to be replaced, its corresponding dirty bit is checked to see if the block needs to be written back to secondary memory before being replaced or if it can simply be removed. Dirty bits are used by the CPU cache and in the page replacement algorithms of an operating system. -**Programmatic Example** +## Programmatic Example of Dirty Flag Pattern in Java The `DataFetcher` class is responsible for fetching data from a file. It has a dirty flag that indicates whether the data in the file has changed since the last fetch. @@ -106,43 +108,43 @@ The program output is as follows: 12:06:02.616 [pool-1-thread-1] INFO com.iluwatar.dirtyflag.App -- UNITED_STATES ``` -## Applicability +## When to Use the Dirty Flag Pattern in Java * When an operation is resource-intensive and only necessary after certain changes have occurred. -* In scenarios where checking for changes is significantly cheaper than performing the operation itself. -* Within systems where objects maintain state that is expensive to update and the updates are infrequent. +* In scenarios where checking for changes is significantly cheaper than performing the operation itself, enhancing cost-effectiveness. +* Within systems where objects maintain state that is expensive to update and the updates are infrequent, promoting performance efficiency. -## Tutorials +## Dirty Flag Pattern Java Tutorials * [89: Design Patterns: Dirty Flag (TakeUpCode)](https://www.takeupcode.com/podcast/89-design-patterns-dirty-flag/) -## Known Uses +## Real-World Applications of Dirty Flag Pattern in Java -* Graphic rendering engines to update only parts of the scene that have changed. +* Graphic rendering engines to update only parts of the scene that have changed, utilizing the Dirty Flag pattern for efficient rendering. * Web applications for partial page rendering or caching strategies. -* Database applications for tracking changes in datasets to minimize write operations. +* Database applications for tracking changes in datasets to minimize write operations, ensuring efficient database management. -## Consequences +## Benefits and Trade-offs of Dirty Flag Pattern Benefits: -* Reduces computational and resource overhead by avoiding unnecessary operations. -* Can significantly improve performance in systems where operations are costly and changes are infrequent. -* Simplifies the decision-making process about when to perform certain operations. +* Reduces computational and resource overhead by avoiding unnecessary operations, leading to performance gains. +* Can significantly improve performance in systems where operations are costly and changes are infrequent, fostering system optimization. +* Simplifies the decision-making process about when to perform certain operations, aiding in effective resource allocation. Trade-offs: * Introduces complexity by adding state management responsibility to the system. * Requires diligent management of the flag to ensure it accurately reflects the state changes, avoiding stale or incorrect data. -* Potentially increases the risk of bugs related to improper flag resetting. +* Potentially increases the risk of bugs related to improper flag resetting, impacting system reliability. -## Related Patterns +## Related Java Design Patterns * [Observer](https://java-design-patterns.com/patterns/observer/): Can be used in conjunction to notify interested parties when the dirty flag is set or cleared. * [Memento](https://java-design-patterns.com/patterns/memento/): Useful for storing the previous state of an object, which can work hand in hand with dirty flag logic to revert to clean states. * [Command](https://java-design-patterns.com/patterns/command/): Commands can set the dirty flag when executed, indicating a change in state that requires attention. -## Credits +## References and Credits * [Game Programming Patterns](https://amzn.to/3PUzbgu) * [J2EE Design Patterns](https://amzn.to/4dpzgmx) diff --git a/domain-model/README.md b/domain-model/README.md index 878dc1889..5a914c7ef 100644 --- a/domain-model/README.md +++ b/domain-model/README.md @@ -1,16 +1,18 @@ --- -title: Domain Model +title: "Domain Model Pattern in Java: Building Robust Business Logic" +shortTitle: Domain Model +description: "Learn about the Domain Model pattern in Java design with detailed explanations, examples, and applications. Improve your software's modularity, maintainability, and scalability." category: Structural language: en tag: - - Abstraction - - Business - - Data processing - - Domain - - Encapsulation - - Layered architecture - - Persistence - - Polymorphism + - Abstraction + - Business + - Data processing + - Domain + - Encapsulation + - Layered architecture + - Persistence + - Polymorphism --- ## Also known as @@ -18,11 +20,11 @@ tag: * Conceptual Model * Domain Object Model -## Intent +## Intent of Domain Model Design Pattern -The Domain Model pattern aims to create a conceptual model in your software that matches the real-world system it's designed to represent. It involves using rich domain objects that encapsulate both data and behavior relevant to the application domain. +The Domain Model pattern aims to create a conceptual model in your software that matches the real-world system it's designed to represent. It involves using rich domain objects that encapsulate both data and behavior relevant to the application domain, ensuring business logic is centralized. -## Explanation +## Detailed Explanation of Domain Model Pattern with Real-World Examples Real-world example @@ -32,7 +34,7 @@ In plain words > The Domain Model is an object model of the domain that incorporates both behavior and data. -**Programmatic Example** +## Programmatic Example of Domain Model Pattern in Java Let's assume that we need to build an e-commerce web application. While analyzing requirements you will notice that there are few nouns you talk about repeatedly. It’s your Customer, and a Product the customer looks for. These two are your domain-specific classes and each of that classes will include some business logic specific to its domain. @@ -223,28 +225,28 @@ The program output: 12:17:23.846 [main] INFO com.iluwatar.domainmodel.Customer -- Tom bought: Eggs - $10.00, Cheese - $20.00 ``` -## Class diagram +## Detailed Explanation of Domain Model Pattern with Real-World Examples ![Domain Model class diagram](./etc/domain-model.urm.png "Domain Model") -## Applicability +## When to Use the Domain Model Pattern in Java * Appropriate in complex applications with rich business logic. * When the business logic or domain complexity is high and requires a model that closely represents real-world entities and their relationships. * Suitable for applications where domain experts are involved in the development process to ensure the model accurately reflects domain concepts. -## Tutorials +## Domain Model Pattern Java Tutorials * [Architecture patterns: domain model and friends (Inviqa)](https://inviqa.com/blog/architecture-patterns-domain-model-and-friends) -## Known Uses +## Real-World Applications of Domain Model Pattern in Java * Enterprise applications (ERP, CRM systems) * Financial systems (banking, trading platforms) * Healthcare applications (patient records management) * E-commerce platforms (product catalogs, shopping carts) -## Consequences +## Benefits and Trade-offs of Domain Model Pattern Benefits: @@ -259,14 +261,14 @@ Trade-offs: * Performance Concerns: Rich domain objects with complex behaviors might lead to performance bottlenecks, requiring careful optimization. * Learning Curve: Requires a good understanding of the domain and may involve a steep learning curve for developers unfamiliar with the domain concepts. -## Related Patterns +## Related Java Design Patterns * [Data Access Object (DAO)](https://java-design-patterns.com/patterns/dao/): For abstracting and encapsulating all access to the data source. * [Repository](https://java-design-patterns.com/patterns/repository/): Mediates between the domain and data mapping layers, acting like an in-memory domain object collection. * [Service Layer](https://java-design-patterns.com/patterns/service-layer/): Defines an application's boundary with a layer of services that establishes a set of available operations and coordinates the application's response in each operation. * [Unit of Work](https://java-design-patterns.com/patterns/unit-of-work/): Maintains a list of objects affected by a business transaction and coordinates the writing out of changes. -## Credits +## References and Credits * [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3vMCjnP) * [Implementing Domain-Driven Design](https://amzn.to/4cUX4OL) diff --git a/double-buffer/README.md b/double-buffer/README.md index 1fef252d3..befa83a9a 100644 --- a/double-buffer/README.md +++ b/double-buffer/README.md @@ -1,12 +1,14 @@ --- -title: Double Buffer +title: "Double Buffer Pattern in Java: Enhancing Animation and Graphics Performance" +shortTitle: Double Buffer +description: "Learn how the Double Buffer Pattern in Java optimizes performance and ensures smooth graphics rendering for applications. Explore practical examples and real-world use cases." category: Behavioral language: en tag: - - Buffering - - Game programming - - Optimization - - Performance + - Buffering + - Game programming + - Optimization + - Performance --- ## Also known as @@ -14,11 +16,11 @@ tag: * Buffer Switching * Ping-Pong Buffer -## Intent +## Intent of Double Buffer Design Pattern -The Double Buffer pattern aims to reduce the time necessary for rendering and displaying graphical or computational data by utilizing two buffers. One buffer is used for rendering the next frame or computing the next set of data, while the other is used to display the current frame or data set to the user. +The Double Buffer pattern in Java is designed to reduce rendering time and enhance performance in graphical or computational applications by utilizing two buffers. This pattern is crucial for smooth graphics rendering and is commonly used in game development and other real-time applications. -## Explanation +## Detailed Explanation of Double Buffer Pattern with Real-World Examples Real-world example @@ -32,7 +34,7 @@ Wikipedia says > In computer science, multiple buffering is the use of more than one buffer to hold a block of data, so that a "reader" will see a complete (though perhaps old) version of the data, rather than a partially updated version of the data being created by a "writer". It is very commonly used for computer display images. -**Programmatic Example** +## Programmatic Example of Double Buffer Pattern in Java A typical example, and one that every game engine must address, is rendering. When the game draws the world the users see, it does so one piece at a time - the mountains in the distance, the rolling hills, the trees, each in its turn. If the user watched the view draw incrementally like that, the illusion of a coherent world would be shattered. The scene must update smoothly and quickly, displaying a series of complete frames, each appearing instantly. Double buffering solves the problem. @@ -210,40 +212,40 @@ The console output: 12:33:02.530 [main] INFO com.iluwatar.doublebuffer.App -- Black Pixels: (6, 1) (3, 7) ``` -## Applicability +## When to Use the Double Buffer Pattern in Java -* Real-time applications where the display needs to be updated frequently and smoothly, such as video games, simulations, and graphical user interfaces. -* Applications requiring high computational resources to prepare data, where the preparation can be done in parallel with data consumption. -* Scenarios where the goal is to minimize the perception of lag or stutter in the display of data or graphics. +* Real-time Applications: Ideal for video games, simulations, and GUI applications where frequent and smooth display updates are essential. +* High Computational Tasks: Suitable for applications that require intensive data preparation, enabling parallel processing and display. +* Minimizing Lag: Effective in reducing lag or stutter in data or graphics display. -## Known Uses +## Real-World Applications of Double Buffer Pattern in Java -* Graphics Rendering Engines: Used extensively in 2D and 3D rendering engines to ensure smooth animations and transitions. -* User Interface Frameworks: Employed in GUI frameworks to enhance the responsiveness and smoothness of interfaces. -* Simulation and Modeling: Utilized in simulations to display real-time updates without interrupting the simulation process. -* Video Playback Software: Applied in video players to provide seamless playback by preloading the next frame while the current one is displayed. +* Graphics Rendering Engines: Widely used in 2D and 3D rendering engines to ensure fluid animations and transitions. +* GUI Frameworks: Enhances the responsiveness and smoothness of user interfaces. +* Simulation and Modeling: Ensures real-time updates in simulations without interrupting ongoing processes. +* Video Playback Software: Provides seamless video playback by preloading the next frame during the display of the current one. -## Consequences +## Benefits and Trade-offs of Double Buffer Pattern Benefits: -* Smooth User Experience: Provides a seamless display experience by pre-rendering frames, leading to smoother animations and transitions. -* Performance Optimization: Allows intensive rendering or data preparation tasks to be performed in the background, optimizing overall performance. -* Minimizes Flickering: Reduces or eliminates flickering and visual artifacts in graphical applications. +* Smooth User Experience: Pre-renders frames to deliver smooth animations and transitions. +* Performance Optimization: Allows background rendering, optimizing overall application performance. +* Minimized Flickering: Reduces flickering and visual artifacts in graphical applications. Trade-offs: -* Memory Overhead: Requires additional memory for the secondary buffer, potentially doubling the memory usage for the buffered data. -* Implementation Complexity: Adds complexity to the system architecture, requiring careful management of the two buffers. -* Latency: Can introduce a slight delay, as the data must be fully rendered or prepared in the back buffer before being displayed. +* Memory Overhead: Requires additional memory for the secondary buffer, potentially increasing memory usage. +* Implementation Complexity: Adds complexity to the architecture, necessitating careful buffer management. +* Latency: May introduce slight delays as data must be fully rendered in the back buffer before display. -## Related Patterns +## Related Java Design Patterns * Triple Buffering: An extension of the Double Buffer pattern, where three buffers are used to further optimize rendering and reduce latency. * [Producer-Consumer](https://java-design-patterns.com/patterns/producer-consumer/): The Double Buffer pattern can be seen as a variant of the Producer-Consumer pattern, with one buffer being "produced" while the other is "consumed". * [Strategy](https://java-design-patterns.com/patterns/strategy/): Often used in conjunction with the Strategy pattern to dynamically choose the buffering strategy based on runtime conditions. -## Credits +## References and Credits * [Game Programming Patterns](https://amzn.to/4ayDNkS) * [Real-Time Design Patterns: Robust Scalable Architecture for Real-Time Systems](https://amzn.to/3xFfNxA) diff --git a/double-checked-locking/README.md b/double-checked-locking/README.md index 2bf7f0cd4..df2ddfe98 100644 --- a/double-checked-locking/README.md +++ b/double-checked-locking/README.md @@ -1,19 +1,21 @@ --- -title: Double-Checked Locking +title: "Double-Checked Locking Pattern in Java: Ensuring Thread Safety with Minimal Overhead" +shortTitle: Double-Checked Locking +description: "Master double-checked locking in Java with our detailed guide and practical examples. Enhance your Java design patterns knowledge today." category: Concurrency language: en tag: - - Lazy initialization - - Optimization - - Performance - - Thread management + - Lazy initialization + - Optimization + - Performance + - Thread management --- -## Intent +## Intent of Double-Checked Locking Design Pattern -The Double-Checked Locking pattern aims to reduce the overhead of acquiring a lock by first testing the locking criterion (the 'lock hint') without actually acquiring the lock. Only if the locking criterion check indicates that locking is necessary does the actual locking logic proceed. +Reduce the overhead of acquiring a lock by first testing the locking criterion (the "lock hint") without actually acquiring the lock. Only if the locking criterion appears to be true does the actual locking logic proceed. Double-checked locking in Java helps in optimizing performance and ensuring thread safety. -## Explanation +## Detailed Explanation of Double-Checked Locking Pattern with Real-World Examples Real-world example @@ -27,7 +29,7 @@ Wikipedia says > In software engineering, double-checked locking (also known as "double-checked locking optimization") is a software design pattern used to reduce the overhead of acquiring a lock by testing the locking criterion (the "lock hint") before acquiring the lock. Locking occurs only if the locking criterion check indicates that locking is required. -**Programmatic Example** +## Programmatic Example of Double-Checked Locking Pattern in Java The Double-Checked Locking pattern is used in the `HolderThreadSafe` class to ensure that the `Heavy` object is only created once, even when accessed from multiple threads. Here's how it works: @@ -87,19 +89,19 @@ public class HolderThreadSafe { In this code, the `Heavy` object is only created when the `getHeavy` method is called for the first time. This is known as lazy initialization. The double-checked locking pattern is used to ensure that the `Heavy` object is only created once, even when the `getHeavy` method is called from multiple threads simultaneously. -## Applicability +## When to Use the Double-Checked Locking Pattern in Java -This pattern is used in scenarios where: +Use the Double-Checked Locking pattern in Java when all the following conditions are met: -* There is a significant performance cost associated with acquiring a lock, and -* The lock is not frequently needed. +* There is a singleton resource that is expensive to create. +* There is a need to reduce the overhead of acquiring a lock every time the resource is accessed. -## Known Uses +## Real-World Applications of Double-Checked Locking Pattern in Java * Singleton pattern implementation in multithreading environments. * Lazy initialization of resource-intensive objects in Java applications. -## Consequences +## Benefits and Trade-offs of Double-Checked Locking Pattern Benefits: @@ -111,12 +113,12 @@ Trade-offs: * Complex implementation can lead to mistakes, such as incorrect publishing of objects due to memory visibility issues. * In Java, it can be redundant or broken in some versions unless volatile variables are used with care. -## Related Patterns +## Related Java Design Patterns * [Singleton](https://java-design-patterns.com/patterns/singleton/): Double-Checked Locking is often used in implementing thread-safe Singletons. * [Lazy Loading](https://java-design-patterns.com/patterns/lazy-loading/): Shares the concept of delaying object creation until necessary. -## Credits +## References and Credits * [Java Concurrency in Practice](https://amzn.to/4aIAPKa) * [Effective Java](https://amzn.to/3xx7KDh) diff --git a/double-dispatch/README.md b/double-dispatch/README.md index e7ef4465a..002246719 100644 --- a/double-dispatch/README.md +++ b/double-dispatch/README.md @@ -1,23 +1,25 @@ --- -title: Double Dispatch +title: "Double Dispatch Pattern in Java: Enhancing Polymorphic Behavior" +shortTitle: Double Dispatch +description: "Learn the Double Dispatch Pattern in Java with detailed implementation examples. Understand how to use this design pattern to enhance your Java applications. Read our comprehensive guide." category: Behavioral language: en tag: - - Decoupling - - Dynamic typing - - Polymorphism - - Runtime + - Decoupling + - Dynamic typing + - Polymorphism + - Runtime --- ## Also known as * Multi-methods -## Intent +## Intent of Double Dispatch Design Pattern The Double Dispatch pattern is used to achieve dynamic polymorphism based on the types of two objects involved in a method call. It allows method behavior to be different based on the combination of the runtime types of both the object on which the method is called and the object being passed as a parameter. -## Explanation +## Detailed Explanation of Double Dispatch Pattern with Real-World Examples Real-world example @@ -25,15 +27,15 @@ Real-world example In plain words -> The Double Dispatch design pattern allows a program to select a different function to execute based on the types of two objects involved in a call, enhancing flexibility in handling interactions between them. +> The Double Dispatch design pattern in Java allows a program to select a different function to execute based on the types of two objects involved in a call, enhancing flexibility in handling interactions between them. Wikipedia says > In software engineering, double dispatch is a special form of multiple dispatch, and a mechanism that dispatches a function call to different concrete functions depending on the runtime types of two objects involved in the call. In most object-oriented systems, the concrete function that is called from a function call in the code depends on the dynamic type of a single object and therefore they are known as single dispatch calls, or simply virtual function calls. -**Programmatic Example** +## Programmatic Example of Double Dispatch Pattern in Java -The Double Dispatch pattern is used to handle collisions between different types of game objects. Each game object is an instance of a class that extends the `GameObject` abstract class. The `GameObject` class has method `collision`, which is overridden in each subclass to define the behavior when a collision occurs with another game object. Here is a simplified version of the `GameObject` class and its subclasses: +The Double Dispatch pattern in Java is used to handle collisions between different types of game objects. Each game object is an instance of a class that extends the `GameObject` abstract class. The `GameObject` class has a `collision(GameObject)` method, which is overridden in each subclass to define the behavior when a collision occurs with another game object. Here is a simplified version of the `GameObject` class and its subclasses: ```java public abstract class GameObject { @@ -61,7 +63,7 @@ public class SpaceStationMir extends GameObject { } ``` -In the `App` class's `main` method, the Double Dispatch pattern is used to check for collisions between all pairs of game objects: +In the App class, the Double Dispatch pattern is used to check for collisions between all pairs of game objects: ```java public static void main(String[] args) { @@ -89,7 +91,7 @@ public static void main(String[] args) { } ``` -When a collision is detected between two objects, the `collision(GameObject)` method is called on the first object (o1) with the second object (o2) as the argument. This method call is dispatched at runtime to the appropriate `collision(GameObject)` method in the class of o1. Inside this method, another method call `gameObject.collisionWithX(this)` is made on o2 (where X is the type of o1), which is dispatched at runtime to the appropriate `collisionWithX(GameObject)` method in the class of o2. This is the "double dispatch" - two method calls are dispatched at runtime based on the types of two objects. +When a collision is detected between two objects, the `collision(GameObject)` method is called on the first object (o1) with the second object (o2) as the argument. This method call is dispatched at runtime to the appropriate `collision(GameObject)` method in the class of o1. Inside this method, another method call `gameObject.collisionWithX(this)` is made on o2 (where X is the type of o1), which is dispatched at runtime to the appropriate `collisionWithX(GameObject)` method in the class of o2. This is the "double dispatch" in Java - two method calls are dispatched at runtime based on the types of two objects. Here is the program output: @@ -111,22 +113,22 @@ Here is the program output: 15:47:23.773 [main] INFO com.iluwatar.doubledispatch.App -- SpaceStationIss at [12,12,14,14] damaged=true onFire=false ``` -## Class diagram +## Detailed Explanation of Double Dispatch Pattern with Real-World Examples ![Double Dispatch](./etc/double-dispatch.png "Double Dispatch") -## Applicability +## When to Use the Double Dispatch Pattern in Java * When the behavior of a method needs to vary not just based on the object it is called on, but also based on the type of the argument. * In scenarios where if-else or switch-case type checks against the type of objects are cumbersome and not scalable. * When implementing operations in domain classes without contaminating their code with complex decision-making logic about other domain classes. -## Known Uses +## Real-World Applications of Double Dispatch Pattern in Java * Graphical user interfaces where different actions are taken based on different types of mouse events interacting with different types of elements. * Simulation systems where interactions between different types of objects need to trigger distinct behaviors. -## Consequences +## Benefits and Trade-offs of Double Dispatch Pattern Benefits: @@ -138,12 +140,12 @@ Trade-offs: * Can lead to more complex code structures, especially in languages like Java that do not support this pattern natively. * May require additional effort in maintaining and extending as new classes are added. -## Related Patterns +## Related Java Design Patterns * [Strategy](https://java-design-patterns.com/patterns/strategy/): Similar in intent where it's used to choose an algorithm at runtime, though Strategy focuses on single object context rather than interactions between multiple objects. * [Visitor](https://java-design-patterns.com/patterns/visitor/): Often used together with Double Dispatch to encapsulate operations performed on a set of element objects. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/4awj7cV) * [Java Design Pattern Essentials](https://amzn.to/3Jg8ZZV) diff --git a/dynamic-proxy/README.md b/dynamic-proxy/README.md index 79eea3b92..9dedbedd0 100644 --- a/dynamic-proxy/README.md +++ b/dynamic-proxy/README.md @@ -1,5 +1,7 @@ --- -title: Dynamic Proxy +title: "Dynamic Proxy Pattern in Java: Facilitating Seamless Object Interception" +shortTitle: Dynamic Proxy +description: "Explore the Dynamic Proxy Pattern in Java, a flexible runtime mechanism for creating proxies that enhance functionality and control access to objects. Learn through real-world examples and detailed explanations." category: Structural language: en tag: @@ -15,11 +17,11 @@ tag: * Runtime Proxy -## Intent +## Intent of Dynamic Proxy Design Pattern To provide a flexible proxy mechanism capable of dynamically creating proxies for various interfaces at runtime, allowing for controlled access or functionality enhancement of objects. -## Explanation +## Detailed Explanation of Dynamic Proxy Pattern with Real-World Examples Real-world example @@ -27,13 +29,13 @@ Real-world example In plain words -> Dynamic proxy is a specialized form of proxy in Java, serving as a flexible and dynamic method to intercept and manipulate method calls. By utilizing dynamic proxies, developers can implement additional functionalities without modifying the original class code. +> The Dynamic Proxy Pattern in Java is a specialized form of proxy, serving as a flexible and dynamic method to intercept and manipulate method calls. By utilizing dynamic proxies, developers can implement additional functionalities without modifying the original class code. This is particularly useful in scenarios requiring enhancement of existing functionalities. Wikipedia says > A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface. Thus, a dynamic proxy class can be used to create a type-safe proxy object for a list of interfaces without requiring pre-generation of the proxy class, such as with compile-time tools. Method invocations on an instance of a dynamic proxy class are dispatched to a single method in the instance's invocation handler, and they are encoded with a _java.lang.reflect.Method_ object identifying the method that was invoked and an array of type _Object_ containing the arguments. -**Programmatic Example** +## Programmatic Example of Dynamic Proxy Pattern in Java This example demonstrates using the Dynamic Proxy pattern in Java to hit the public fake API [JSONPlaceholder](https://jsonplaceholder.typicode.com) for the resource `Album` through an interface. @@ -280,7 +282,7 @@ Running the example produces the following console output showcasing the API cal 16:05:43.357 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=null, title=null, userId=null) ``` -## Applicability +## When to Use the Dynamic Proxy Pattern in Java Dynamic proxy should be used when you need to augment or enhance your current functionality without modifying your current code. Some examples of that usage could be: @@ -288,7 +290,7 @@ Dynamic proxy should be used when you need to augment or enhance your current fu * You need to create a proxy object for one or more interfaces dynamically at runtime without coding it explicitly for each interface. * You aim to simplify complex systems by decoupling the client and the real object through a flexible proxy mechanism. -## Tutorials +## Dynamic Proxy Pattern Java Tutorials * [Dynamic Proxies in Java (CodeGym)](https://codegym.cc/groups/posts/208-dynamic-proxies) * [Introduction To Java Dynamic Proxy (Xperti)](https://xperti.io/blogs/java-dynamic-proxies-introduction/) @@ -296,7 +298,7 @@ Dynamic proxy should be used when you need to augment or enhance your current fu * [Intro To Java Dynamic Proxies (KapreSoft)](https://www.kapresoft.com/java/2023/12/27/intro-to-java-proxies.html) * [Exploring the Depths of Dynamic Proxy in Java: A Comprehensive Guide (Medium)](https://naveen-metta.medium.com/exploring-the-depths-of-dynamic-proxy-in-java-a-comprehensive-guide-f34fb45b38a3) -## Known uses +## Real-World Applications of Dynamic Proxy Pattern in Java Many frameworks and libraries use dynamic proxy to implement their functionalities: @@ -309,7 +311,7 @@ Many frameworks and libraries use dynamic proxy to implement their functionaliti * Frameworks: Extensively used in Java frameworks like Spring for AOP (Aspect-Oriented Programming) to handle transactions, security, logging, etc. * Middleware: In middleware services for transparently adding services like load balancing and access control. -## Consequences +## Benefits and Trade-offs of Dynamic Proxy Pattern Benefits: @@ -325,13 +327,13 @@ Trade-offs: * Limited to interface-based programming: They can only proxy interfaces, not classes. This limitation requires careful design considerations, particularly in situations where class-based proxies would be more appropriate. * Higher level of expertise: Developers are normally not a fan of “magic code” — code that works in a non-transparent or overly complex manner. Those unfamiliar with the proxy pattern or reflection might find the codebase more complex to understand and maintain, potentially leading to errors or misuse of the feature. This complexity can be perceived as a form of “magic” that obscures the underlying process, making the code less intuitive and more challenging to debug or extend. Therefore, while dynamic proxies are powerful, their use should be approached with caution and a thorough understanding of their inner workings. -## Related patterns +## Related Java Design Patterns * [Proxy](https://java-design-patterns.com/patterns/proxy): Static counterpart of the Dynamic Proxy, where proxies are explicitly coded. * [Decorator](https://java-design-patterns.com/patterns/decorator/): Similar in structure by providing additional functionality, but without the dynamic proxy's capability to handle any interface. * [Facade](https://java-design-patterns.com/patterns/facade/): Simplifies the interface to complex systems, not through dynamic proxies but through a single simplified interface. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3U0d8Gm) * [Java Reflection in Action](https://amzn.to/3TVpe3t) diff --git a/event-aggregator/README.md b/event-aggregator/README.md index 297e3a0cf..a052e87c4 100644 --- a/event-aggregator/README.md +++ b/event-aggregator/README.md @@ -1,13 +1,19 @@ --- -title: Event Aggregator +title: "Event Aggregator Pattern in Java: Centralizing Event Management in Large Applications" +shortTitle: Event Aggregator +description: "Explore the Event Aggregator design pattern with our in-depth guide. Learn how to implement it effectively with examples and improve your Java applications. Perfect for developers seeking to enhance their design pattern knowledge." category: Messaging language: en tag: - - Decoupling - - Event-driven - - Messaging - - Publish/subscribe - - Reactive + - Decoupling + - Event-driven + - Messaging + - Publish/subscribe + - Reactive +head: + - - meta + - name: keywords + content: --- ## Also known as @@ -16,21 +22,23 @@ tag: * Event Central * Message Hub -## Intent +## Intent of Event Aggregator Design Pattern -The Event Aggregator design pattern aims to reduce the direct dependencies between multiple systems and components that need to interact by introducing a single component, the Event Aggregator, that receives events from multiple sources and distributes them to multiple listeners. +An Event Aggregator is a design pattern used for handling events in a system. It centralizes the event handling logic, making it easier to manage and maintain. The Event Aggregator design pattern aims to decouple event generation from event handling. This design pattern collects events from multiple sources and routes them to the appropriate handlers. -## Explanation +## Detailed Explanation of Event Aggregator Pattern with Real-World Examples Real-world example -> An analogous real-world example of the Event Aggregator pattern can be found in a newsroom. In a newsroom, multiple reporters and correspondents are constantly gathering news and reporting on various events from different locations. Instead of each reporter communicating directly with every news editor or producer, all their reports and updates are channeled through a central news desk. This news desk acts as the Event Aggregator, receiving all incoming reports, filtering and prioritizing them, and then dispatching the relevant information to the appropriate editors or producers. This centralization simplifies the process, reduces direct dependencies, and ensures that news updates are managed efficiently and effectively. +> The Event Aggregator pattern is often compared to a hub in a wheel. In this analogy, the Event Aggregator is the hub, and the spokes are the event sources. The hub collects events from all the spokes and then distributes them to the appropriate handlers. In Plain Words -> Event Aggregator is an event mediator that collects events from multiple sources and delivers them to registered observers. +> Event Aggregator is a design pattern that allows multiple event sources to communicate with event handlers through a central point, rather than having each event source communicate directly with each handler. -**Programmatic Example** +## Programmatic Example of Event Aggregator Pattern in Java + +Consider the following example where we use the Event Aggregator to handle multiple events. King Joffrey sits on the iron throne and rules the seven kingdoms of Westeros. He receives most of his critical information from King's Hand, the second in command. King's hand has many close advisors himself, feeding him with relevant information about events occurring in the kingdom. @@ -153,42 +161,44 @@ The console output after running the example. 21:37:38.739 [main] INFO com.iluwatar.event.aggregator.KingJoffrey -- Received event from the King's Hand: Traitor detected ``` -## Class diagram +## Detailed Explanation of Event Aggregator Pattern with Real-World Examples ![Event Aggregator](./etc/classes.png "Event Aggregator") -## Applicability +## When to Use the Event Aggregator Pattern in Java Use the Event Aggregator pattern when -* Use the Event Aggregator pattern in systems where multiple components generate events and multiple components need to receive those events, but direct coupling between these components leads to complex dependencies and hard-to-manage code. -* Suitable in applications where a reduction in the number of explicit references between decoupled systems is desired, such as in microservices architectures or complex user interface systems. +* You have multiple event sources and handlers. +* You want to decouple the event generation and handling logic. +* You need a centralized event management system. -## Known Uses +## Real-World Applications of Event Aggregator Pattern in Java * Enterprise application integrations where systems need a central point to handle events generated by various subsystems. * Complex GUI applications where user actions in one part of the interface need to affect other parts without tight coupling between the components. -## Consequences +## Benefits and Trade-offs of Event Aggregator Pattern Benefits: -* Reduces Coupling: By centralizing event handling, the Event Aggregator minimizes direct interaction between components, leading to a more modular and easier-to-manage system. +* Decoupling: By centralizing event handling, the Event Aggregator minimizes direct interaction between components, leading to a more modular and easier-to-manage system. * Improves Flexibility and Scalability: Adding new publishers or subscribers involves less effort since the central aggregator handles all routing. * Simplifies Component Interface: Components need to know only about the Event Aggregator, not about other components. +* Centralizes event management: Makes the system easier to maintain. Trade-offs: * Complexity of the Aggregator: The Event Aggregator itself can become a complex and high-maintenance component if not properly designed. * Potential Performance Bottleneck: If not scaled properly, the central event handling mechanism can become a bottleneck in the system. -## Related Patterns +## Related Java Design Patterns * [Mediator](https://java-design-patterns.com/patterns/mediator/): Similar to Mediator in that it abstracts direct communications between components, but focused specifically on event messages. * [Observer](https://java-design-patterns.com/patterns/observer/): The Event Aggregator pattern is often implemented using the Observer pattern, where the aggregator observes events and notifies subscribers. * Publish-Subscribe: The Event Aggregator can be seen as a special case of the Publish-Subscribe pattern, with the aggregator acting as the broker. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/44eWKXv) * [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/440b0CZ) diff --git a/event-based-asynchronous/README.md b/event-based-asynchronous/README.md index c86e9ba16..eee9758dd 100644 --- a/event-based-asynchronous/README.md +++ b/event-based-asynchronous/README.md @@ -1,26 +1,28 @@ --- -title: Event-Based Asynchronous +title: "Event-Based Asynchronous Pattern in Java: Mastering Non-Blocking System Design" +shortTitle: Event-Based Asynchronous +description: "Explore the best practices and implementations of event-based asynchronous patterns in Java. Enhance your programming skills with our comprehensive guide and real-world examples." category: Concurrency language: en tag: - - Asynchronous - - Decoupling - - Event-driven - - Fault tolerance - - Messaging - - Reactive - - Scalability + - Asynchronous + - Decoupling + - Event-driven + - Fault tolerance + - Messaging + - Reactive + - Scalability --- ## Also known as * Asynchronous Event Handling -## Intent +## Intent of Event-Based Asynchronous Design Pattern The Event-Based Asynchronous pattern allows a system to handle tasks that might take some time to complete without blocking the execution of the program. It enables better resource utilization by freeing up a thread that would otherwise be blocked waiting for the task to complete. -## Explanation +## Detailed Explanation of Event-Based Asynchronous Pattern with Real-World Examples Real-world example @@ -30,9 +32,9 @@ In Plain Words > The Event-Based Asynchronous design pattern allows tasks to be executed in the background, notifying the main program via events when completed, thereby enhancing system efficiency and responsiveness without blocking ongoing operations. -**Programmatic Example** +## Programmatic Example of Event-Based Asynchronous Pattern in Java -The Event-Based Asynchronous design pattern allows tasks to be executed in the background, notifying the main program via events when completed. This enhances system efficiency and responsiveness without blocking ongoing operations. +Event-Based Asynchronous design pattern allows tasks to be executed in the background, notifying the main program via events when completed, thereby enhancing system efficiency and responsiveness without blocking ongoing operations. In the provided code, we have several key classes implementing this pattern: @@ -141,20 +143,20 @@ In this snippet, when a `SyncEvent` is started, it runs on the main thread, bloc These are the key parts of the Event-Based Asynchronous design pattern as implemented in this code. The pattern allows tasks to be executed in the background, notifying the main program via events when completed, thereby enhancing system efficiency and responsiveness without blocking ongoing operations. -## Applicability +## When to Use the Event-Based Asynchronous Pattern in Java * When multiple tasks can be processed in parallel and independently. * Systems that require responsiveness and cannot afford to have threads blocked waiting for an operation to complete. * In GUI applications where user interface responsiveness is critical. * Distributed systems where long network operations are involved. -## Known Uses +## Real-World Applications of Event-Based Asynchronous Pattern in Java * GUI libraries in Java (e.g., JavaFX, Swing with SwingWorker). * Java Message Service (JMS) for handling asynchronous messaging. * Java’s CompletableFuture and various Event-Driven Frameworks. -## Consequences +## Benefits and Trade-offs of Event-Based Asynchronous Pattern Benefits: @@ -167,13 +169,13 @@ Trade-offs: * Increases complexity of error handling as errors may occur in different threads or at different times. * Can lead to harder-to-follow code and debugging challenges due to the non-linear nature of asynchronous code execution. -Related Patterns +## Related Java Design Patterns * [Observer](https://java-design-patterns.com/patterns/observer/): Often used in conjunction where the observer reacts to events as they occur. * Publish/Subscribe: Related in terms of event handling mechanisms, particularly for messaging and event distribution across components. * [Command](https://java-design-patterns.com/patterns/command/): Useful for encapsulating all information needed to perform an action or trigger an event. -## Credits +## References and Credits * [Java Concurrency in Practice](https://amzn.to/4cYY4kU) * [Patterns of Enterprise Application Architecture](https://amzn.to/3Uh7rW1) diff --git a/event-driven-architecture/README.md b/event-driven-architecture/README.md index 298b4e4c5..435637a95 100644 --- a/event-driven-architecture/README.md +++ b/event-driven-architecture/README.md @@ -1,16 +1,18 @@ --- -title: Event-Driven Architecture +title: "Event-Driven Architecture Pattern in Java: Building Responsive and Scalable Java Systems" +shortTitle: Event-Driven Architecture +description: "Discover comprehensive guides on Event-Driven Architecture patterns with practical Java examples. Learn to implement effective event-driven systems in your projects." category: Architectural language: en tag: - - Asynchronous - - Decoupling - - Enterprise patterns - - Event-driven - - Messaging - - Publish/subscribe - - Reactive - - Scalability + - Asynchronous + - Decoupling + - Enterprise patterns + - Event-driven + - Messaging + - Publish/subscribe + - Reactive + - Scalability --- ## Also known as @@ -18,11 +20,11 @@ tag: * Event-Driven System * Event-Based Architecture -## Intent +## Intent of Event-Driven Architecture Design Pattern Event-Driven Architecture (EDA) is designed to orchestrate behavior around the production, detection, consumption of, and reaction to events. This architecture enables highly decoupled, scalable, and dynamic interconnections between event producers and consumers. -## Explanation +## Detailed Explanation of Event-Driven Architecture Pattern with Real-World Examples Real-world example @@ -36,7 +38,7 @@ Wikipedia says > Event-driven architecture (EDA) is a software architecture paradigm concerning the production and detection of events. -**Programmatic Example** +## Programmatic Example of Event-Driven Architecture in Java The Event-Driven Architecture (EDA) pattern in this module is implemented using several key classes and concepts: @@ -151,11 +153,11 @@ Running the example produces the following console output: This example demonstrates the Event-Driven Architecture pattern, where the occurrence of events drives the flow of the program. The system is designed to respond to events as they occur, which allows for a high degree of flexibility and decoupling between components. -## Class diagram +## Detailed Explanation of Event-Driven Architecture Pattern with Real-World Examples ![Event-Driven Architecture](./etc/eda.png "Event-Driven Architecture") -## Applicability +## When to Use the Event-Driven Architecture Pattern in Java Use an Event-driven architecture when @@ -164,7 +166,7 @@ Use an Event-driven architecture when * Systems needing to efficiently handle high throughput and sporadic loads. * When integrating with microservices to enhance agility and scalability. -## Known Uses +## Real-World Applications of Event-Driven Architecture Pattern in Java * Real-time data processing applications. * Complex event processing systems in finance, such as stock trading platforms. @@ -173,7 +175,7 @@ Use an Event-driven architecture when * Amazon's AWS Lambda, lets you execute code in response to events such as changes to Amazon S3 buckets, updates to an Amazon DynamoDB table, or custom events generated by your applications or devices. (https://aws.amazon.com/lambda) * MySQL runs triggers based on events such as inserts and update events happening on database tables. -## Consequences +## Benefits and Trade-offs of Event-Driven Architecture Pattern Benefits: @@ -187,12 +189,12 @@ Trade-offs: * Dependency on Messaging Systems: Heavily relies on robust messaging infrastructures. * Event Consistency: Requires careful design to handle event ordering and consistency. -## Related Patterns +## Related Java Design Patterns * Microservices Architecture: Often used together with EDA to enhance agility and scalability. * Publish/Subscribe: A common pattern used within EDA for messaging between event producers and consumers. -## Credits +## References and Credits * [Patterns of Enterprise Application Architecture](https://amzn.to/3Q3vBki) * [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/49Aljz0) diff --git a/event-queue/README.md b/event-queue/README.md index 9a5c31a51..8b2991b1d 100644 --- a/event-queue/README.md +++ b/event-queue/README.md @@ -1,13 +1,15 @@ --- -title: Event Queue +title: "Event Queue Pattern in Java: Managing Concurrent Events Efficiently" +shortTitle: Event Queue +description: "Learn about the Event Queue design pattern in Java. Discover its best practices, examples, and how to implement it effectively in your Java projects." category: Concurrency language: en tag: - - Asynchronous - - Decoupling - - Messaging - - Event-driven - - Scalability + - Asynchronous + - Decoupling + - Messaging + - Event-driven + - Scalability --- ## Also known as @@ -15,11 +17,11 @@ tag: * Event Stream * Message Queue -## Intent +## Intent of Event Queue Design Pattern -The Event Queue pattern is designed to manage tasks in an asynchronous manner, allowing applications to handle operations without blocking user interactions or other processes. +The Event Queue pattern is designed to manage tasks in an asynchronous manner, allowing applications to handle operations without blocking user interactions or other processes. This improves scalability and system performance. -## Explanation +## Detailed Explanation of Event Queue Pattern with Real-World Examples Real-world example @@ -27,13 +29,13 @@ Real-world example In plain words -> The buffer between sender and receiver improves maintainability and scalability of a system. Event queues are typically used to organise and carry out interprocess communication (IPC). +> The buffer between sender and receiver improves maintainability and scalability of a system. Event queues are typically used to organize and carry out interprocess communication (IPC). Wikipedia says > Message queues (also known as event queues) implement an asynchronous communication pattern between two or more processes/threads whereby the sending and receiving party do not need to interact with the queue at the same time. -**Programmatic Example** +## Programmatic Example of Event Queue Pattern in Java This example demonstrates an application using an event queue system to handle audio playback asynchronously. @@ -133,7 +135,7 @@ public void playSound(AudioInputStream stream, float volume) { } ``` -## Applicability +## When to Use the Event Queue Pattern in Java This pattern is applicable in scenarios where tasks can be handled asynchronously outside the main application flow, such as in GUI applications, server-side event handling, or in systems that require task scheduling without immediate execution. In particular: @@ -142,13 +144,13 @@ This pattern is applicable in scenarios where tasks can be handled asynchronousl * You want to process events asynchronously. * You have a limited accessibility resource and the asynchronous process is acceptable to reach that. -## Known Uses +## Real-World Applications of Event Queue Pattern in Java * Event-driven architectures * GUI frameworks in Java (such as Swing and JavaFX) * Server applications handling requests asynchronously -## Consequences +## Benefits and Trade-offs of Event Queue Pattern Benefits: @@ -161,14 +163,15 @@ Trade-offs: * Complexity in managing the event queue. * Potential for difficult-to-track bugs due to asynchronous behavior. * Overhead of maintaining event queue integrity and performance. +* As the event queue model decouples the sender-receiver relationship - this means that the event-queue design pattern is unsuitable for scenarios in which the sender requires a response. For example, this is a prominent feature within online multiplayer games, therefore, this approach requires thorough consideration. -## Related Patterns +## Related Java Design Patterns * [Command](https://java-design-patterns.com/patterns/command/) (for encapsulating request processing in a command object) * [Observer](https://java-design-patterns.com/patterns/observer/) (for subscribing and notifying changes to multiple observers) * [Reactor](https://java-design-patterns.com/patterns/reactor/) (handles requests in a non-blocking event-driven manner similar to Event Queue) -## Credits +## References and Credits * [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/3xzSlC2) * [Game Programming Patterns](https://amzn.to/3K96fOn) diff --git a/event-sourcing/README.md b/event-sourcing/README.md index acd9edacf..17dc44773 100644 --- a/event-sourcing/README.md +++ b/event-sourcing/README.md @@ -1,15 +1,21 @@ --- -title: Event Sourcing +title: "Event Sourcing Pattern in Java: Building Immutable Historical Records for Robust Systems" +shortTitle: Event Sourcing +description: "Discover the Event Sourcing design pattern in Java. Learn how it stores state changes as events and benefits complex applications. See examples and explanations on Java Design Patterns." category: Architectural language: en tag: - - Decoupling - - Event-driven - - Fault tolerance - - Messaging - - Persistence - - Scalability - - Transactions + - Decoupling + - Event-driven + - Fault tolerance + - Messaging + - Persistence + - Scalability + - Transactions +head: + - - meta + - name: keywords + content: --- ## Also known as @@ -17,11 +23,11 @@ tag: * Event Logging * Event Streaming -## Intent +## Intent of Event Sourcing Design Pattern Event Sourcing is a design pattern that advocates for the storage of state changes as a sequence of events. Instead of updating a record in a database, all changes are stored as individual events which, when replayed, can recreate the state of an application at any point in time. -## Explanation +## Detailed Explanation of Event Sourcing Pattern with Real-World Examples Real-world example @@ -35,7 +41,7 @@ In plain words > The Event Sourcing pattern defines an approach to handling operations on data that's driven by a sequence of events, each of which is recorded in an append-only store. Application code sends a series of events that imperatively describe each action that has occurred on the data to the event store, where they're persisted. Each event represents a set of changes to the data (such as AddedItemToOrder). -**Programmatic Example** +## Programmatic Example of Event Sourcing Pattern in Java In the programmatic example we transfer some money between bank accounts. @@ -194,20 +200,20 @@ Running the example produces the following console output. In this example, the state of the system can be recreated at any point by replaying the events in the queue. This is a key feature of the Event Sourcing pattern. -## Applicability +## When to Use the Event Sourcing Pattern in Java * In systems where complete audit trails and historical changes are crucial. * In complex domains where the state of an application is derived from a series of changes. * For systems that benefit from high availability and scalability as Event Sourcing naturally lends itself to distributed systems. -## Known Uses +## Real-World Applications of Event Sourcing Pattern in Java * Financial systems to track transactions and account balances over time. * E-commerce applications for order and inventory management. * Real-time data processing systems where event consistency and replayability are critical. * [The LMAX Architecture](https://martinfowler.com/articles/lmax.html) -## Consequences +## Benefits and Trade-offs of Event Sourcing Pattern Benefits: @@ -215,18 +221,18 @@ Benefits: * Replayability: Events can be reprocessed to recreate historical states or move to new states. * Scalability: Events can be processed asynchronously and in parallel. -## Trade-offs +Trade-offs * Complexity: Implementing and maintaining an event-sourced system can introduce additional complexity. * Event store size: Storing every state change can lead to large data volumes. * Event versioning: Changes in event structure over time require careful handling to ensure system integrity. -## Related Patterns +## Related Java Design Patterns * [Command Query Responsibility Segregation (CQRS)](https://java-design-patterns.com/patterns/cqrs/): Often used together with Event Sourcing to separate read and write responsibilities, enhancing performance and scalability. * Snapshot: Used to optimize Event Sourcing systems by periodically saving the current state to avoid replaying a long sequence of events. -## Credits +## References and Credits * [Building Microservices: Designing Fine-Grained Systems](https://amzn.to/443WfiS) * [Implementing Domain-Driven Design](https://amzn.to/3JgvA8V) diff --git a/execute-around/README.md b/execute-around/README.md index b24b1ae68..aea3ae9e7 100644 --- a/execute-around/README.md +++ b/execute-around/README.md @@ -1,13 +1,19 @@ --- -title: Execute Around +title: "Execute Around Pattern in Java: Encapsulating Pre and Post Execution Steps" +shortTitle: Execute Around +description: "Explore the Execute Around Pattern in Java with detailed explanations, real-world examples, and best practices. Learn how to implement this design pattern to streamline resource management." category: Behavioral language: en tag: - - Closure - - Code simplification - - Encapsulation - - Functional decomposition - - Resource management + - Closure + - Code simplification + - Encapsulation + - Functional decomposition + - Resource management +head: + - - meta + - name: keywords + content: --- ## Also known as @@ -15,11 +21,11 @@ tag: * Around Method Pattern * Resource Block Management -## Intent +## Intent of Execute Around Design Pattern -Execute Around idiom frees the user from certain actions that should always be executed before and after the business method. A good example of this is resource allocation and deallocation leaving the user to specify only what to do with the resource. +Real-world business applications often require executing necessary operations before and after the business method invocation. The Execute Around Pattern in Java provides a way to encapsulate these operations, enhancing code readability and reusability. -## Explanation +## Detailed Explanation of Execute Around Pattern with Real-World Examples Real-world example @@ -33,7 +39,9 @@ In plain words > Basically it's the pattern where you write a method to do things which are always required, e.g. resource allocation and clean-up, and make the caller pass in "what we want to do with the resource". -**Programmatic Example** +## Programmatic Example of Execute Around Pattern in Java + +The Execute Around Pattern is a design pattern that is widely used in Java programming to manage resource allocation and deallocation. It ensures that important setup and cleanup operations are performed reliably around a core business operation. This pattern is particularly useful for resource management, such as handling files, databases, or network connections in Java applications. A class needs to be provided for writing text strings to files. To make it easy for the user, the service class opens and closes the file automatically. The user only has to specify what is written into which file. @@ -86,18 +94,24 @@ Here's the console output. 21:18:07.199 [main] INFO com.iluwatar.execute.around.App - Gandalf was here ``` -## Applicability +## When to Use the Execute Around Pattern in Java + +When to use the Execute Around Pattern in Java: * Useful in scenarios requiring repetitive setup and cleanup activities, particularly in resource management (e.g., files, network connections, database sessions). * Ideal for ensuring proper resource handling and cleanup in the face of exceptions, ensuring resources do not leak. * Suitable in any Java application where the same preparation and finalization steps are executed around varying core functionalities. -## Known Uses +## Real-World Applications of Execute Around Pattern in Java + +In real-world Java applications, the Execute Around Pattern is applied in these scenarios: * Java's try-with-resources statement, which ensures that resources are closed after execution regardless of whether an exception was thrown. * Frameworks like Spring for managing database transactions, where predefined cleanup or rollback operations are performed depending on the execution outcome. -## Consequences +## Benefits and Trade-offs of Execute Around Pattern + +Implementing the Execute Around Pattern in Java offers several benefits and trade-offs. Benefits: @@ -110,12 +124,12 @@ Trade-offs: * Introduces additional abstraction layers, which might increase complexity and obscure control flow for some developers. * May require more sophisticated understanding of closures and functional interfaces in Java. -## Related Patterns +## Related Java Design Patterns * [Template Method](https://java-design-patterns.com/patterns/template-method/): Similar in concept but differs in that it uses inheritance and abstract classes, while Execute Around typically uses interfaces and lambdas. * [Decorator](https://java-design-patterns.com/patterns/decorator/): Shares the concept of adding functionality around a core component; can be extended to wrap additional behaviors dynamically. -## Credits +## References and Credits * [Effective Java](https://amzn.to/4aDdWbs) * [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3vUGApm) diff --git a/extension-objects/README.md b/extension-objects/README.md index 8007832eb..058fce654 100644 --- a/extension-objects/README.md +++ b/extension-objects/README.md @@ -1,23 +1,25 @@ --- -title: Extension Objects +title: "Extension Objects Pattern in Java: Enhancing Object Functionality Flexibly" +shortTitle: Extension Objects +description: "Learn about the Extension Objects Design Pattern in Java. Understand its purpose, benefits, and implementation with examples to enhance your software design." category: Structural language: en tag: - - Encapsulation - - Extensibility - - Object composition - - Polymorphism + - Encapsulation + - Extensibility + - Object composition + - Polymorphism --- ## Also known as * Interface Extensions -## Intent +## Intent of Extension Objects Design Pattern The Extension Objects pattern allows for the flexible extension of an object's behavior without modifying its structure, by attaching additional objects that can dynamically add new functionality. -## Explanation +## Detailed Explanation of Extension Objects Pattern with Real-World Examples Real-world example @@ -31,11 +33,11 @@ Wikipedia says > In object-oriented computer programming, an extension objects pattern is a design pattern added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension object patterns are features of some object-oriented programming languages. There is no syntactic difference between calling an extension method and calling a method declared in the type definition. -**Programmatic example** +## Programmatic Example of Extension Objects Pattern in Java The Extension Objects pattern allows for the flexible extension of an object's behavior without modifying its structure, by attaching additional objects that can dynamically add new functionality. -In this example, we have three types of units: `SoldierUnit`, `SergeantUnit`, and `CommanderUnit`. Each unit can have extensions that provide additional functionality. The extensions are `SoldierExtension`, `SergeantExtension`, and `CommanderExtension`. +In this Java implementation, we have three types of units: `SoldierUnit`, `SergeantUnit`, and `CommanderUnit`. Each unit can have extensions that provide additional functionality. The extensions are `SoldierExtension`, `SergeantExtension`, and `CommanderExtension`. The `Unit` class is the base class for all units. It has a method `getUnitExtension` that returns an extension object based on the extension name. @@ -141,15 +143,15 @@ This produces the following console output. This example demonstrates how the Extension Objects pattern allows for the flexible extension of an object's behavior without modifying its structure. -## Class diagram +## Detailed Explanation of Extension Objects Pattern with Real-World Examples ![Extension_objects](./etc/extension_obj.png "Extension objects") -## Applicability +## When to Use the Extension Objects Pattern in Java This pattern is applicable in scenarios where an object's functionality needs to be extended at runtime, avoiding the complications of subclassing. It's particularly useful in systems where object capabilities need to be augmented post-deployment, or where the capabilities might vary significantly across instances. -## Known Uses +## Real-World Applications of Extension Objects Pattern in Java * Extending services in an application server without altering existing code. * Plugins in IDEs like IntelliJ IDEA or Eclipse to add features to the base application. @@ -157,7 +159,7 @@ This pattern is applicable in scenarios where an object's functionality needs to * [OpenDoc](https://en.wikipedia.org/wiki/OpenDoc) * [Object Linking and Embedding](https://en.wikipedia.org/wiki/Object_Linking_and_Embedding) -## Consequences +## Benefits and Trade-offs of Extension Objects Pattern Benefits: @@ -170,13 +172,13 @@ Trade-offs: * Can increase complexity due to the management of extension objects. * May introduce performance overhead if the interaction between objects and extensions is not efficiently designed. -## Related Patterns +## Related Java Design Patterns * [Decorator](https://java-design-patterns.com/patterns/decorator/): Similar in intent to add responsibilities dynamically, but uses a different structure. * [Composite](https://java-design-patterns.com/patterns/composite/): Also manages a group of objects, which can be seen as a form of extension. * [Strategy](https://java-design-patterns.com/patterns/strategy/): Offers an alternative way to change the behavior of an object dynamically. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/4aBMuuL) * [Pattern-Oriented Software Architecture: A System of Patterns](https://amzn.to/3Q9YOtX) diff --git a/facade/README.md b/facade/README.md index 87b7cbdb6..ea27e4afa 100644 --- a/facade/README.md +++ b/facade/README.md @@ -1,23 +1,25 @@ --- -title: Facade +title: "Facade Pattern in Java: Simplifying Complex System Interfaces" +shortTitle: Facade +description: "Learn how to implement the Facade Design Pattern in Java to create a unified interface for complex subsystems. Simplify your code and enhance maintainability with practical examples and use cases." category: Structural language: en tag: - - Abstraction - - API design - - Code simplification - - Decoupling - - Encapsulation - - Gang Of Four - - Interface - - Object composition + - Abstraction + - API design + - Code simplification + - Decoupling + - Encapsulation + - Gang Of Four + - Interface + - Object composition --- -## Intent +## Intent of Facade Design Pattern -Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. +The Facade Design Pattern provides a unified interface to a set of interfaces in a subsystem. This Java design pattern simplifies complex system interactions. -## Explanation +## Detailed Explanation of Facade Pattern with Real-World Examples Real-world example @@ -31,7 +33,9 @@ Wikipedia says > A facade is an object that provides a simplified interface to a larger body of code, such as a class library. -**Programmatic Example** +## Programmatic Example of Facade Pattern in Java + +Here's an example of the Facade Design Pattern in a goldmine scenario, demonstrating how a Java facade can streamline complex operations. How does a goldmine work? "Well, the miners go down there and dig gold!" you say. That is what you believe because you are using a simple interface that goldmine provides on the outside, internally it has to do a lot of stuff to make it happen. This simple interface to the complex subsystem is a facade. @@ -195,30 +199,33 @@ Program output: 06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarven tunnel digger goes to sleep. ``` -## Applicability +## When to Use the Facade Pattern in Java -Use the Facade pattern when +Use the Facade pattern in Java when: * You want to provide a simple interface to a complex subsystem. * Subsystems are getting more complex and depend on multiple classes, but most clients only need a part of the functionality. * There is a need to layer your subsystems. Use a facade to define an entry point to each subsystem level. +* You want to reduce dependencies and enhance code readability in Java development. -## Tutorials +## Facade Pattern Java Tutorials * [Facade Design Pattern in Java (DigitalOcean)](https://www.digitalocean.com/community/tutorials/facade-design-pattern-in-java) * [Facade (Refactoring Guru)](https://refactoring.guru/design-patterns/facade) * [Facade Method Design Pattern (GeekforGeeks)](https://www.geeksforgeeks.org/facade-design-pattern-introduction/) * [Design Patterns - Facade Pattern (TutorialsPoint)](https://www.tutorialspoint.com/design_pattern/facade_pattern.htm) -## Known Uses +## Real-World Applications of Facade Pattern in Java * Java libraries such as java.net.URL and javax.faces.context.FacesContext use Facade to simplify complex underlying classes. * In many Java frameworks, facades are used to simplify the usage of APIs by providing a simpler interface to more complex underlying code structures. -## Consequences +## Benefits and Trade-offs of Facade Pattern Benefits: +Implementing the Facade Design Pattern in Java: + * Isolates clients from subsystem components, making it easier to use and reducing dependencies. * Promotes weak coupling between the subsystem and its clients. * Often simplifies the API of complex systems. @@ -227,12 +234,12 @@ Trade-offs: * A facade can become a god object coupled to all classes of an app if not implemented correctly. -## Related Patterns +## Related Java Design Patterns * [Adapter](https://java-design-patterns.com/patterns/adapter/): Facade provides a unified interface while Adapter makes two existing interfaces work together. * [Mediator](https://java-design-patterns.com/patterns/mediator/): Facade defines a simpler interface to a subsystem while Mediator centralizes complex communications and control between objects. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3QbO7qN) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/factory-kit/README.md b/factory-kit/README.md index f4963b93c..d13379a4e 100644 --- a/factory-kit/README.md +++ b/factory-kit/README.md @@ -1,14 +1,16 @@ --- -title: Factory Kit +title: "Factory Kit Pattern in Java: Crafting Flexible Component Assemblies" +shortTitle: Factory Kit +description: "Learn about the Factory Kit Pattern in Java with detailed explanations, real-world examples, and practical applications. Improve your Java skills with our comprehensive guide." category: Creational language: en tag: - - Abstraction - - Decoupling - - Encapsulation - - Generic - - Instantiation - - Object composition + - Abstraction + - Decoupling + - Encapsulation + - Generic + - Instantiation + - Object composition --- ## Also known as @@ -16,23 +18,25 @@ tag: * Object Kit * Toolkit -## Intent +## Intent of Factory Kit Design Pattern -Define a factory of immutable content with separated builder and factory interfaces. +The Factory Kit Pattern in Java is a powerful design pattern that helps in creating factories with separated builder and factory interfaces. This pattern is essential for managing complex object creation scenarios. -## Explanation +## Detailed Explanation of Factory Kit Pattern with Real-World Examples Real-world example -> An analogous real-world example of the Factory Kit pattern is a restaurant kitchen where different types of dishes are prepared. Imagine the kitchen has a central station with various ingredients and recipes registered for different dishes. When an order comes in, the chef consults this central station to gather the necessary ingredients and follow the registered recipe to prepare the dish. This setup allows the kitchen to efficiently manage and switch between different dish preparations without the need for each chef to know the specifics of every recipe, promoting flexibility and consistency in the cooking process. +> An analogous real-world example of the Factory Kit Pattern is a restaurant kitchen where different types of dishes are prepared efficiently. This setup promotes flexibility and consistency, similar to how the Factory Kit Pattern operates in Java. Imagine the kitchen has a central station with various ingredients and recipes registered for different dishes. When an order comes in, the chef consults this central station to gather the necessary ingredients and follow the registered recipe to prepare the dish. This setup allows the kitchen to efficiently manage and switch between different dish preparations without the need for each chef to know the specifics of every recipe, promoting flexibility and consistency in the cooking process. In plain words > Factory kit is a configurable object builder, a factory to create factories. -**Programmatic Example** +## Programmatic Example of Factory Kit Pattern in Java -Imagine a magical weapon factory capable of creating any desired weapon. Upon activation, the master recites the names of the weapon types needed to configure it. Once set up, any of these weapon types can be summoned instantly. +Imagine a magical weapon factory in Java capable of creating any desired weapon using the Factory Kit Pattern. This pattern allows for configurable object builders, making it ideal for scenarios where the types of objects are not known upfront. + +Upon activation, the master recites the names of the weapon types needed to configure it. Once set up, any of these weapon types can be summoned instantly. Let's first define the simple `Weapon` hierarchy. @@ -108,43 +112,43 @@ Here is the console output when the example is run. 06:32:23.029 [main] INFO com.iluwatar.factorykit.App -- Bow ``` -## Applicability +## When to Use the Factory Kit Pattern in Java -Use the Factory Kit pattern when +Use the Factory Kit Pattern when -* The factory class can't anticipate the types of objects it must create -* A new instance of a custom builder is needed instead of a global one -* The types of objects that the factory can build need to be defined outside the class -* The builder and creator interfaces need to be separated -* Game developments and other applications that have user customisation +* The factory class cannot anticipate the types of objects it must create, and a new instance of a custom builder is needed. +* A new instance of a custom builder is needed instead of a global one. +* The types of objects that the factory can build need to be defined outside the class. +* The builder and creator interfaces need to be separated. +* Game developments and other applications that have user customization. -## Tutorials +## Factory Kit Pattern Java Tutorials * [Factory Kit Pattern (Diego Pacheco)](https://diego-pacheco.medium.com/factory-kit-pattern-66d5ccb0c405) -## Known Uses +## Real-World Applications of Factory Kit Pattern in Java * In Java libraries such as the Java Development Kit (JDK) where different rendering engines might be instantiated based on the runtime environment. * Frameworks like Spring or applications where dependency injection is heavily used, often implement this pattern to manage object creation more flexibly. -## Consequences +## Benefits and Trade-offs of Factory Kit Pattern Benefits: -* Promotes loose coupling by eliminating the need to bind application-specific classes into the code. -* Simplifies code by shifting the responsibility of instantiation to a factory object. +* The Factory Kit Pattern in Java promotes loose coupling by eliminating the need to bind application-specific classes into the code. +* It simplifies the code by shifting the responsibility of instantiation to a factory object, making the development process more efficient. Trade-offs: * Can introduce complexity into the code by requiring additional classes and interfaces. * Sometimes can lead to dependency issues if not properly managed. -## Related patterns +## Related Java Design Patterns * [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Often used together with the Factory Kit to create families of related objects. * [Builder](https://java-design-patterns.com/patterns/builder/): Can be used to construct complex objects step-by-step using a similar approach. * [Prototype](https://java-design-patterns.com/patterns/prototype/): Objects that are created by cloning a prototypical instance often use a factory to manage it. -## Credits +## References and Credits * [Design Pattern Reloaded (Remi Forax)](https://www.youtube.com/watch?v=-k2X7guaArU) diff --git a/factory-method/README.md b/factory-method/README.md index a62c8c07c..6aad53596 100644 --- a/factory-method/README.md +++ b/factory-method/README.md @@ -1,24 +1,26 @@ --- -title: Factory Method +title: "Factory Method Pattern in Java: Enhancing Flexibility with Polymorphic Manufacturing" +shortTitle: Factory Method +description: "Learn about the Factory Method pattern in Java. Explore examples, uses, benefits, and how it enhances code flexibility and maintenance." category: Creational language: en tag: - - Encapsulation - - Gang of Four - - Instantiation - - Object composition - - Polymorphism + - Encapsulation + - Gang of Four + - Instantiation + - Object composition + - Polymorphism --- ## Also known as * Virtual Constructor -## Intent +## Intent of Factory Method Design Pattern -Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. +Define an interface for creating an object using the Factory Method Pattern, but let subclasses decide which class to instantiate. This creational design pattern lets a class defer instantiation to subclasses, enhancing code flexibility and maintenance. -## Explanation +## Detailed Explanation of Factory Method Pattern with Real-World Examples Real-world example @@ -34,7 +36,9 @@ Wikipedia says > In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method — either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor. -**Programmatic Example** +## Programmatic Example of Factory Method Pattern in Java + +The Factory Method approach is pivotal in Java Design Patterns for achieving flexible and maintainable code as we see in the following example. Blacksmith manufactures weapons. Elves require Elvish weapons and orcs require Orcish weapons. Depending on the customer at hand the right type of blacksmith is summoned. @@ -85,15 +89,15 @@ Program output: 06:40:07.272 [main] INFO com.iluwatar.factory.method.App -- The elf blacksmith manufactured an elven axe ``` -## Applicability +## When to Use the Factory Method Pattern in Java -Use the Factory Method pattern when: +Use the Factory Method Pattern in Java when: * Class cannot anticipate the class of objects it must create. * Class wants its subclasses to specify the objects it creates. * Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate. -## Known uses +## Real-World Applications of Factory Method Pattern in Java * [java.util.Calendar](http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--) * [java.util.ResourceBundle](http://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-) @@ -104,11 +108,11 @@ Use the Factory Method pattern when: * [javax.xml.bind.JAXBContext](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--) * Frameworks that run application components, configured dynamically at runtime. -## Consequences +## Benefits and Trade-offs of Factory Method Pattern Benefits: -* Provides hooks for subclasses, creating flexibility in code. +* The Factory Method Pattern provides hooks for subclasses, enhancing code flexibility and maintainability. * Connects parallel class hierarchies. * Eliminates the need to bind application-specific classes into the code. The code only deals with the product interface; hence it can work with any user-defined concrete product classes. @@ -116,12 +120,12 @@ Trade-offs: * Can complicate the code by requiring the addition of new subclasses to implement the extended factory methods. -## Related Patterns +## Related Java Design Patterns * [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Factory methods are often called within Abstract Factory patterns. * [Prototype](https://java-design-patterns.com/patterns/prototype/): A factory method that returns a new instance of a class that is a clone of a prototype class. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0Rk5y) * [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/3UpTLrG) diff --git a/factory/README.md b/factory/README.md index 4eb2d3503..da5b220e9 100644 --- a/factory/README.md +++ b/factory/README.md @@ -1,34 +1,36 @@ --- -title: Factory +title: "Factory Pattern in Java: Streamlining Object Creation" +shortTitle: Factory +description: "Learn the Factory Design Pattern in Java with detailed examples and explanations. Understand how to create flexible and scalable code using the Factory Pattern. Ideal for developers looking to improve their object-oriented design skills." category: Creational language: en tag: - - Abstraction - - Encapsulation - - Gang of Four - - Instantiation - - Polymorphism + - Abstraction + - Encapsulation + - Gang of Four + - Instantiation + - Polymorphism --- -## Intent +## Intent of Factory Design Pattern -The Factory design pattern is intended to define an interface for creating an object, but allows subclasses to alter the type of objects that will be created. This pattern is particularly useful when the creation process involves complexity. +The Factory Design Pattern in Java is a creational pattern that defines an interface for creating an object but allows subclasses to alter the type of objects that will be created. This pattern promotes flexibility and scalability in your codebase. -## Explanation +## Detailed Explanation of Factory Pattern with Real-World Examples Real-world example -> Imagine a scenario in a bakery where different types of cakes are made. The bakery has a "CakeFactory" where customers can order cakes. The CakeFactory can produce various types of cakes such as chocolate cake, vanilla cake, and strawberry cake. Instead of the bakery staff manually selecting ingredients and following specific recipes for each type of cake, they use the CakeFactory to handle the process. The customer simply requests a cake type, and the CakeFactory determines the appropriate ingredients and recipe to use, then creates the specific type of cake. This setup allows the bakery to easily add new cake types without modifying the core cake-making process, promoting flexibility and scalability. +> Imagine a scenario in a bakery where different types of cakes are made using a Factory Design Pattern. The bakery's `CakeFactory` handles the creation process, allowing easy addition of new cake types without altering the core cake-making process. The `CakeFactory` can produce various types of cakes such as chocolate cake, vanilla cake, and strawberry cake. Instead of the bakery staff manually selecting ingredients and following specific recipes for each type of cake, they use the `CakeFactory` to handle the process. The customer simply requests a cake type, and the `CakeFactory` determines the appropriate ingredients and recipe to use, then creates the specific type of cake. This setup allows the bakery to easily add new cake types without modifying the core cake-making process, promoting flexibility and scalability. Wikipedia says > Factory is an object for creating other objects – formally a factory is a function or method that returns objects of a varying prototype or class. -**Programmatic Example** +## Programmatic Example of Factory Pattern in Java Imagine an alchemist who is about to manufacture coins. The alchemist must be able to create both gold and copper coins and switching between them must be possible without modifying the existing source code. The factory pattern makes it possible by providing a static construction method which can be called with relevant parameters. -We have an interface `Coin` and two implementations `GoldCoin` and `CopperCoin`. +In Java, you can implement the Factory Pattern by defining an interface `Coin` and its implementations `GoldCoin` and `CopperCoin`. The `CoinFactory` class provides a static method `getCoin` to create coin objects based on the type. ```java public interface Coin { @@ -105,13 +107,13 @@ Program output: 06:19:53.533 [main] INFO com.iluwatar.factory.App -- This is a gold coin. ``` -## Applicability +## When to Use the Factory Pattern in Java -* Use the Factory pattern in Java when the class doesn't know beforehand the exact types and dependencies of the objects it needs to create. +* Use the Factory Design Pattern in Java when the class does not know beforehand the exact types and dependencies of the objects it needs to create. * When a method returns one of several possible classes that share a common super class and wants to encapsulate the logic of which object to create. * The pattern is commonly used when designing frameworks or libraries to give the best flexibility and isolation from concrete class types. -## Known uses +## Real-World Applications of Factory Pattern in Java * [java.util.Calendar#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--) * [java.util.ResourceBundle#getBundle()](https://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-) @@ -122,11 +124,11 @@ Program output: * [javax.xml.bind.JAXBContext#createMarshaller()](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--) and other similar methods. * JavaFX uses Factory patterns for creating various UI controls tailored to the specifics of the user's environment. -## Consequences +## Benefits and Trade-offs of Factory Pattern Benefits: -* Reduces coupling between the implementation of an application and the classes it uses. +* Implementing the Factory Pattern in your Java application reduces coupling between the implementation and the classes it uses. * Supports the [Open/Closed Principle](https://java-design-patterns.com/principles/#open-closed-principle), as the system can introduce new types without changing existing code. Trade-offs: @@ -134,14 +136,14 @@ Trade-offs: * The code can become more complicated due to the introduction of multiple additional classes. * Overuse can make the code less readable if the underlying complexity of the object creation is low or unnecessary. -## Related Patterns +## Related Java Design Patterns * [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Can be considered a kind of Factory that works with groups of products. * [Singleton](https://java-design-patterns.com/patterns/singleton/): Often used in conjunction with Factory to ensure that a class has only one instance. * [Builder](https://java-design-patterns.com/patterns/builder/): Separates the construction of a complex object from its representation, similar to how factories manage instantiation. * [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/): Is a factory of immutable content with separated builder and factory interfaces. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0Rk5y) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/fanout-fanin/README.md b/fanout-fanin/README.md index f52bcd86a..d92373760 100644 --- a/fanout-fanin/README.md +++ b/fanout-fanin/README.md @@ -1,27 +1,29 @@ --- -title: Fan-Out/Fan-In +title: "Fan-Out Fan-In Pattern in Java: Maximizing Concurrency for Efficient Data Processing" +shortTitle: Fan-Out/Fan-In +description: "Learn how the Fan-Out/Fan-In design pattern in Java can optimize concurrency and processing efficiency. Explore real-world examples, detailed explanations, and programmatic implementations." category: Concurrency language: en tag: - - Asynchronous - - Data processing - - Decoupling - - Scalability + - Asynchronous + - Data processing + - Decoupling + - Scalability --- ## Also known as * Scatter-Gather -## Intent +## Intent of Fan-Out/Fan-In Design Pattern -The Fan-Out/Fan-In pattern aims to improve concurrency and optimize processing time by dividing a task into multiple sub-tasks that can be processed in parallel (fan-out) and then combining the results of these sub-tasks into a single outcome (fan-in). +The Fan-Out/Fan-In design pattern in Java aims to improve concurrency and optimize processing time by dividing a task into multiple sub-tasks that can be processed in parallel (fan-out) and then combining the results of these sub-tasks into a single outcome (fan-in). -## Explanation +## Detailed Explanation of Fan-Out/Fan-In Pattern with Real-World Examples Real-world example -> A real-world example of the Fan-Out/Fan-In design pattern is a food delivery service like UberEats or DoorDash. When a customer places an order, the service (fan-out) sends out individual tasks to different restaurants to prepare the various items. Each restaurant works independently to prepare its part of the order. Once all restaurants have completed their tasks, the delivery service (fan-in) aggregates the items from different restaurants into a single order, ensuring that everything is delivered together to the customer. This parallel processing improves efficiency and ensures timely delivery. +> A real-world example of the Fan-Out/Fan-In pattern in Java is a food delivery service like UberEats or DoorDash. When a customer places an order, the service (fan-out) sends out individual tasks to different restaurants to prepare the various items. Each restaurant works independently to prepare its part of the order. Once all restaurants have completed their tasks, the delivery service (fan-in) aggregates the items from different restaurants into a single order, ensuring that everything is delivered together to the customer. This parallel processing improves efficiency and ensures timely delivery. In plain words @@ -33,11 +35,11 @@ Wikipedia says > > The fan-in concept, on the other hand, typically refers to the aggregation of multiple inputs. In digital electronics, it describes the number of inputs a logic gate can handle. Combining these concepts, the Fan-Out/Fan-In pattern in software engineering involves distributing tasks (fan-out) and then aggregating the results (fan-in). -**Programmatic Example** +## Programmatic Example of Fan-Out/Fan-In Pattern in Java The provided implementation involves a list of numbers with the objective to square them and aggregate the results. The `FanOutFanIn` class receives the list of numbers as `SquareNumberRequest` objects and a `Consumer` instance that collects the squared results as the requests complete. Each `SquareNumberRequest` squares its number with a random delay, simulating a long-running process that finishes at unpredictable times. The `Consumer` instance gathers the results from the various `SquareNumberRequest` objects as they become available at different times. -Here's the `FanOutFanIn` class that asynchronously distributes the requests: +Here's the `FanOutFanIn` class in Java that demonstrates the Fan-Out/Fan-In pattern by asynchronously distributing the requests. ```java public class FanOutFanIn { @@ -130,22 +132,22 @@ Running the example produces the following console output. 06:52:11.465 [main] INFO com.iluwatar.fanout.fanin.App -- Sum of all squared numbers --> 139 ``` -## Applicability +## When to Use the Fan-Out/Fan-In Pattern in Java -Appropriate in scenarios where tasks can be broken down and executed in parallel, especially suitable for data processing, batch processing, and situations requiring aggregation of results from various sources. +The Fan-Out/Fan-In design pattern in Java is appropriate in scenarios where tasks can be broken down and executed in parallel, especially suitable for data processing, batch processing, and situations requiring aggregation of results from various sources. -## Tutorials +## Fan-Out/Fan-In Pattern Java Tutorials * [Fan-out/fan-in scenario in Durable Functions - Cloud backup example (Microsoft)](https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-cloud-backup) * [Understanding Azure Durable Functions - Part 8: The Fan Out/Fan In Pattern (Don't Code Tired)](http://dontcodetired.com/blog/post/Understanding-Azure-Durable-Functions-Part-8-The-Fan-OutFan-In-Pattern) * [Understanding the Fan-Out/Fan-In API Integration Pattern (DZone)](https://dzone.com/articles/understanding-the-fan-out-fan-in-api-integration-p) -## Known Uses +## Real-World Applications of Fan-Out/Fan-In Pattern in Java -* Large-scale data processing applications. +* The Fan-Out/Fan-In pattern in Java is widely used in large-scale data processing applications. * Services requiring aggregation from multiple sources before delivering a response, such as in distributed caching or load balancing systems. -## Consequences +## Benefits and Trade-offs of Fan-Out/Fan-In Pattern Benefits: @@ -159,13 +161,13 @@ Trade-offs: * Potential for increased overhead due to task synchronization and result aggregation. * Dependency on the underlying infrastructure's ability to support concurrent execution. -## Related Patterns +## Related Java Design Patterns * MapReduce: Similar to Fan-Out/Fan-In, MapReduce also involves distributing tasks across a number of workers (map) and aggregating the results (reduce), which is particularly useful for processing large data sets. * [Command](https://java-design-patterns.com/patterns/command/): Command Pattern facilitates the decoupling of the sender and the receiver, akin to how Fan-Out/Fan-In decouples task submission from task processing. * [Producer-Consumer](https://java-design-patterns.com/patterns/producer-consumer/): Works synergistically with Fan-Out/Fan-In by organizing task execution where producers distribute tasks that are processed by multiple consumers, and results are then combined, enhancing throughput and efficiency in data processing. -## Credits +## References and Credits * [Java Concurrency in Practice](https://amzn.to/3vXytsb) * [Patterns of Enterprise Application Architecture](https://amzn.to/49QQcPD) diff --git a/feature-toggle/README.md b/feature-toggle/README.md index 458b22a4a..b010cba59 100644 --- a/feature-toggle/README.md +++ b/feature-toggle/README.md @@ -1,12 +1,14 @@ --- -title: Feature Toggle +title: "Feature Toggle Pattern in Java: Managing Features in Production Seamlessly" +shortTitle: Feature Toggle +description: "Learn how to implement the Feature Toggle design pattern in Java. This guide covers dynamic feature management, benefits, use cases, and practical examples to help you enhance your software development process." category: Behavioral language: en tag: - - Decoupling - - Extensibility - - Feature management - - Scalability + - Decoupling + - Extensibility + - Feature management + - Scalability --- ## Also known as @@ -14,11 +16,11 @@ tag: * Feature Flag * Feature Switch -## Intent +## Intent of Feature Toggle Design Pattern To enable or disable features in a software application dynamically without deploying new code. -## Explanation +## Detailed Explanation of Feature Toggle Pattern with Real-World Examples Real-world Example @@ -26,13 +28,13 @@ Real-world Example In plain words -> Feature Toggle is a way to introduce new features gradually instead of deployment all at once. +> The Feature Toggle design pattern in Java allows developers to introduce new features gradually instead of deploying them all at once, facilitating better dynamic feature management. Wikipedia says > A feature toggle in software development provides an alternative to maintaining multiple feature branches in source code. A condition within the code enables or disables a feature during runtime. In agile settings the toggle is used in production, to switch on the feature on demand, for some or all the users. -**Programmatic Example** +## Programmatic Example of Feature Toggle Pattern in Java This Java code example demonstrates how to display a feature when it is enabled by the developer and the user is a Premium member of the application. This approach is useful for managing subscription-locked features. @@ -101,11 +103,11 @@ Running the example produces the following output. 07:31:50.804 [main] INFO com.iluwatar.featuretoggle.App -- You're amazing Jamie Coder. Thanks for paying for this awesome software. ``` -## Applicability +## When to Use the Feature Toggle Pattern in Java -Use the Feature Toggle pattern when +Use the Feature Toggle Pattern in Java when: -* Conditional feature access to different users and groups. +* Dynamic feature management to different users and groups. * Rolling out a new feature incrementally. * Switching between development and production environments. * Quickly disable problematic features @@ -113,12 +115,12 @@ Use the Feature Toggle pattern when * Ability to maintain multiple version releases of a feature * 'Hidden' deployment, releasing a feature in code for designated testing but not publicly making it available -## Known Uses +## Real-World Applications of Feature Toggle Pattern in Java -* Web development platforms use feature toggles to gradually roll out new features to users to ensure stability. +* Many web development platforms utilize the Feature Toggle design pattern to gradually roll out new features to users, ensuring stability and effective dynamic feature management. * Enterprise applications use feature toggles to enable or disable features during runtime to cater to different market needs. -## Consequences +## Benefits and Trade-offs of Feature Toggle Pattern Benefits: @@ -133,12 +135,12 @@ Trade-offs: * Potential for technical debt if toggles remain in the code longer than necessary. * Risk of toggle misconfiguration leading to unexpected behavior. -## Related Patterns +## Related Java Design Patterns * [Strategy](https://java-design-patterns.com/patterns/strategy/): Both patterns allow changing the behavior of software at runtime. The Feature Toggle changes features dynamically, while the Strategy allows switching algorithms or strategies. * [Observer](https://java-design-patterns.com/patterns/observer/): Useful for implementing feature toggles by notifying components of feature state changes, which allows dynamic feature modification without restarts. -## Credits +## References and Credits * [Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation](https://amzn.to/4488ESM) * [Release It! Design and Deploy Production-Ready Software](https://amzn.to/3UoeJY4) diff --git a/filterer/README.md b/filterer/README.md index 3d79ba30d..be895411b 100644 --- a/filterer/README.md +++ b/filterer/README.md @@ -1,15 +1,17 @@ --- -title: Filterer +title: "Filterer Pattern in Java: Streamlining Data Processing with Dynamic Filters" +shortTitle: Filterer +description: "Learn about the Filterer design pattern in Java, which enhances data processing flexibility by applying a series of filters to data objects. Ideal for dynamic and scalable filtering solutions." language: en category: Behavioral tag: - - Data processing - - Data transformation - - Decoupling - - Functional decomposition - - Object composition - - Performance - - Runtime + - Data processing + - Data transformation + - Decoupling + - Functional decomposition + - Object composition + - Performance + - Runtime --- ## Also known as @@ -17,23 +19,23 @@ tag: * Filters * Pipes and Filters -## Intent +## Intent of Filterer Design Pattern -The Filterer pattern aims to apply a series of filters to data objects, where each filter processes the data based on specific rules and criteria, and passes the data to the next filter in the sequence. +The Filterer design pattern in Java is essential for creating dynamic and scalable filtering solutions. This pattern allows the application of a series of filters to data objects, enhancing data processing flexibility and scalability. -## Explanation +## Detailed Explanation of Filterer Pattern with Real-World Examples Real-world example -> Imagine a library that needs to filter books based on different criteria such as genre, author, publication year, or availability. Instead of writing separate methods for each possible combination of criteria, the library system employs the Filterer design pattern. Each filter criterion is encapsulated as an object, and these filter objects can be combined dynamically at runtime to create complex filtering logic. For example, a user can search for books that are both available and published after 2010 by combining the availability filter and the publication year filter. This approach makes the system more flexible and easier to maintain, as new filtering criteria can be added without modifying existing code. +> Imagine a library system employing the Filterer pattern to dynamically combine filter criteria such as genre, author, and availability. This Java pattern makes the system more maintainable and scalable. Instead of writing separate methods for each possible combination of criteria, the library system employs the Filterer design pattern. Each filter criterion is encapsulated as an object, and these filter objects can be combined dynamically at runtime to create complex filtering logic. For example, a user can search for books that are both available and published after 2010 by combining the availability filter and the publication year filter. This approach makes the system more flexible and easier to maintain, as new filtering criteria can be added without modifying existing code. In plain words > Filterer pattern is a design pattern that helps container-like objects return filtered versions of themselves. -**Programmatic Example** +## Programmatic Example of Filterer Pattern in Java -We are designing a threat (malware) detection software which can analyze target systems for threats that are present in it. In the design we have to take into consideration that new Threat types can be added later. Additionally, there is a requirement that the threat detection system can filter the detected threats based on different criteria (the target system acts as container-like object for threats). +To illustrate, we use the Filterer design pattern for a malware detection system in Java. This system can filter threats based on various criteria, showcasing the pattern’s flexibility and dynamic nature. In the design we have to take into consideration that new Threat types can be added later. Additionally, there is a requirement that the threat detection system can filter the detected threats based on different criteria (the target system acts as container-like object for threats). To model the threat detection system, we introduce `Threat` and `ThreatAwareSystem` interfaces. @@ -224,23 +226,23 @@ Running the example produces the following console output. 08:33:23.581 [main] INFO com.iluwatar.filterer.App -- Filtered by probability = 0.99 : SimpleProbabilisticThreatAwareSystem(systemId=Sys-1, threats=[SimpleProbableThreat{probability=0.99} SimpleThreat(threatType=TROJAN, id=1, name=Trojan-ArcBomb)]) ``` -## Applicability +## When to Use the Filterer Pattern in Java -* Use when you need to filter a collection of objects dynamically based on different criteria. -* Suitable for applications where filtering logic changes frequently or needs to be combined in various ways. +* Use the Filterer pattern when dynamic and flexible filtering of a collection of objects is needed. +* This Java design pattern is ideal for applications where filtering logic frequently changes or requires combination in various ways. * Ideal for scenarios requiring separation of filtering logic from the core business logic. -## Tutorials +## Filterer Pattern Java Tutorials * [Filterer Pattern (Tomasz Linkowski)](https://blog.tlinkowski.pl/2018/filterer-pattern/) * [Filterer Pattern in 10 Steps (Java Code Geeks)](https://www.javacodegeeks.com/2019/02/filterer-pattern-10-steps.html) -## Known Uses +## Real-World Applications of Filterer Pattern in Java * Stream processing libraries in Java, such as Apache Kafka Streams, utilize this pattern to build complex data processing pipelines. * Image processing software often uses filters to apply effects or transformations to images sequentially. -## Consequences +## Benefits and Trade-offs of Filterer Pattern Benefits: @@ -253,12 +255,12 @@ Trade-offs: * Potential performance overhead from continuous data passing between filters. * Complexity can increase with the number of filters, potentially affecting maintainability. -## Related Patterns +## Related Java Design Patterns * [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Filters can be seen as a specialized form of the Chain of Responsibility, where each filter decides if and how to process the input data and whether to pass it along the chain. * [Decorator](https://java-design-patterns.com/patterns/decorator/): Similar to Decorator in that both modify behavior dynamically; however, filters focus more on data transformation than on adding responsibilities. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3W8sn2W) * [Kafka: The Definitive Guide: Real-Time Data and Stream Processing at Scale](https://amzn.to/49N3nRU) diff --git a/fluent-interface/README.md b/fluent-interface/README.md index d2660ac41..8b2a04420 100644 --- a/fluent-interface/README.md +++ b/fluent-interface/README.md @@ -1,13 +1,15 @@ --- -title: Fluent Interface +title: "Fluent Interface Pattern in Java: Enhancing Code Expressiveness with Fluent APIs" +shortTitle: Fluent Interface +description: "Learn how to implement the Fluent Interface design pattern in Java. Explore method chaining and Fluent API with practical examples and improve your code readability and maintainability." category: Behavioral language: en tag: - - API design - - Code simplification - - Decoupling - - Object composition - - Reactive + - API design + - Code simplification + - Decoupling + - Object composition + - Reactive --- ## Also known as @@ -15,15 +17,15 @@ tag: * Fluent API * Method Chaining -## Intent +## Intent of Fluent Interface Design Pattern -To provide an easily readable, flowing API by chaining method calls. +The primary goal of the Fluent Interface pattern is to provide an easily readable and flowing API by chaining method calls, often referred to as method chaining. This approach is ideal for building complex objects step-by-step and improving the overall developer experience. -## Explanation +## Detailed Explanation of Fluent Interface Pattern with Real-World Examples Real-world example -> Imagine you are at a coffee shop and you want to customize your coffee order. Instead of telling the barista everything at once, you specify each customization step-by-step in a way that flows naturally. For instance, you might say, "I'd like a large coffee, add two shots of espresso, no sugar, and top it with almond milk." This approach is similar to the Fluent Interface design pattern, where you chain together method calls to configure an object in a readable and intuitive manner. Just as you specify each part of your coffee order sequentially, a Fluent Interface allows you to chain method calls to build and configure objects step-by-step in code. +> Imagine you are at a coffee shop customizing your order step-by-step. This approach is similar to how the Fluent Interface design pattern works in Java, allowing you to chain method calls to build and configure objects sequentially. Instead of telling the barista everything at once, you specify each customization step-by-step in a way that flows naturally. For instance, you might say, "I'd like a large coffee, add two shots of espresso, no sugar, and top it with almond milk." This approach is similar to the Fluent Interface design pattern, where you chain together method calls to configure an object in a readable and intuitive manner. Just as you specify each part of your coffee order sequentially, a Fluent Interface allows you to chain method calls to build and configure objects step-by-step in code. In plain words @@ -33,7 +35,7 @@ Wikipedia says > In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). -**Programmatic Example** +## Programmatic Example of Fluent Interface Pattern in Java We need to select numbers based on different criteria from the list. It's a great chance to utilize fluent interface pattern to provide readable easy-to-use developer experience. @@ -150,19 +152,19 @@ Program output: 08:50:08.270 [main] INFO com.iluwatar.fluentinterface.app.App -- Last amongst first two negatives: -22 ``` -## Applicability +## When to Use the Fluent Interface Pattern in Java -Use the Fluent Interface pattern when +Use the Fluent Interface Pattern in Java when * Designing APIs that are heavily used and where readability of client code is of high importance. * Building complex objects step-by-step, and there is a need to make the code more intuitive and less error-prone. * Enhancing code clarity and reducing the boilerplate code, especially in configurations and object-building scenarios. -## Tutorials +## Fluent Interface Pattern Java Tutorials * [An Approach to Internal Domain-Specific Languages in Java (InfoQ)](http://www.infoq.com/articles/internal-dsls-java) -## Known uses +## Real-World Applications of Fluent Interface Pattern in Java * [Java 8 Stream API](http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html) * [Google Guava FluentIterable](https://github.com/google/guava/wiki/FunctionalExplained) @@ -171,11 +173,11 @@ Use the Fluent Interface pattern when * [Java Hamcrest](http://code.google.com/p/hamcrest/wiki/Tutorial) * Builders in libraries like Apache Camel for integration workflows. -## Consequences +## Benefits and Trade-offs of Fluent Interface Pattern Benefits: -* Improved code readability and maintainability. +* Adopting the Fluent Interface pattern in your Java projects can significantly enhance code readability and maintainability. * Encourages building immutable objects since methods typically return new instances. * Reduces the need for variables as the context is maintained in the chain. @@ -185,12 +187,12 @@ Trade-offs: * Debugging can be challenging due to the chaining of method calls. * Overuse can lead to complex and hard-to-maintain code structures. -## Related Patterns +## Related Java Design Patterns * [Builder](https://java-design-patterns.com/patterns/builder/): Often implemented using a Fluent Interface to construct objects step-by-step. The Builder Pattern focuses on constructing complex objects, while Fluent Interface emphasizes the method chaining mechanism. * [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Fluent Interfaces can be seen as a specific utilization of the Chain of Responsibility, where each method in the chain handles a part of the task and then delegates to the next method. -## Credits +## References and Credits * [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3UrXkh2) * [Domain Specific Languages](https://amzn.to/3R1UYDA) diff --git a/flux/README.md b/flux/README.md index aee4bab81..95bfa2870 100644 --- a/flux/README.md +++ b/flux/README.md @@ -1,20 +1,22 @@ --- -title: Flux +title: "Flux Pattern in Java: Streamlining Complex UIs with Unidirectional Data Flow" +shortTitle: Flux +description: "Learn how the Flux design pattern simplifies data flow in Java applications through unidirectional architecture. Explore examples, benefits, and real-world applications." category: Architectural language: en tag: - - Client-server - - Decoupling - - Event-driven - - Publish/subscribe - - Reactive + - Client-server + - Decoupling + - Event-driven + - Publish/subscribe + - Reactive --- -## Intent +## Intent of Flux Design Pattern -The Flux design pattern is intended to manage the flow of data in applications, particularly client-side web applications, by enforcing a unidirectional data flow. It aims to simplify the management of complex data interactions and promote a more predictable state behavior across components. +The Flux design pattern is intended to manage the flow of data in Java applications, particularly client-side web applications, by enforcing a unidirectional data flow. It aims to simplify the management of complex data interactions and promote a more predictable state behavior across components. -## Explanation +## Detailed Explanation of Flux Pattern with Real-World Examples Real-world example @@ -22,13 +24,13 @@ Real-world example In plain words -> The Flux design pattern manages data flow in applications through a unidirectional architecture, coordinating actions, dispatchers, stores, and views to ensure stable and predictable state management. +> The Flux design pattern manages data flow in applications through a unidirectional architecture, coordinating actions, dispatchers, stores, and views to ensure stable and predictable state management. This pattern is particularly useful in Java design patterns for developing responsive client-side web applications. Wikipedia says > To support React's concept of unidirectional data flow (which might be contrasted with AngularJS's bidirectional flow), the Flux architecture was developed as an alternative to the popular model–view–controller architecture. Flux features actions which are sent through a central dispatcher to a store, and changes to the store are propagated back to the view. -**Programmatic Example** +## Programmatic Example of Flux Pattern in Java The Flux design pattern is used for building client-side web applications. It advocates for a unidirectional data flow. When a user interacts with a view, the view propagates an action through a central dispatcher, to the various stores that hold the application's data and business logic, which updates all the views that are affected. @@ -81,20 +83,20 @@ In this example, when a menu item is clicked, the `MenuView` triggers a `MENU_IT This is a basic example of the Flux pattern, where actions are dispatched from the views, handled by the stores, and cause the views to update. -## Class diagram +## Detailed Explanation of Flux Pattern with Real-World Examples ![Flux](./etc/flux.png "Flux") -## Applicability +## When to Use the Flux Pattern in Java -Flux is applicable in developing client-side applications, where maintaining consistent data across various components and managing complex state interactions are critical. It is especially suited for applications with dynamic user interfaces that react to frequent data updates. +Flux is applicable in developing client-side Java applications, where maintaining consistent data across various components and managing complex state interactions are critical. It is especially suited for applications with dynamic user interfaces that react to frequent data updates. -## Known Uses +## Real-World Applications of Flux Pattern in Java -* Facebook extensively uses Flux in conjunction with React to build robust, scalable user interfaces that can handle complex data updates efficiently. +* Facebook extensively uses the Flux design pattern in conjunction with React to build robust, scalable user interfaces that can handle complex data updates efficiently. Many modern web applications adopt Flux or its variations (like Redux) to manage state in environments that demand high responsiveness and predictability. * Many modern web applications adopt Flux or its variations (like Redux) to manage state in environments that demand high responsiveness and predictability. -## Consequences +## Benefits and Trade-offs of Flux Pattern Benefits: @@ -107,13 +109,13 @@ Trade-offs: * Can introduce boilerplate and complexity in smaller applications. * May require a learning curve to understand the pattern's architecture and its implementation nuances. -## Related Patterns +## Related Java Design Patterns * [Observer](https://java-design-patterns.com/patterns/observer/): Flux's dispatcher component acts similarly to an observer, managing notifications about data changes to various stores. * [Singleton](https://java-design-patterns.com/patterns/singleton/): Typically, the dispatcher in Flux is implemented as a singleton. * [Mediator](https://java-design-patterns.com/patterns/mediator/): Flux can be considered a variation of the mediator pattern where the dispatcher mediates the flow of data and ensures components do not update the state directly. -## Credits +## References and Credits * [Learning React: Modern Patterns for Developing React Apps](https://amzn.to/3Qdn9Pg) * [Pro React](https://amzn.to/3xNRttK) diff --git a/flyweight/README.md b/flyweight/README.md index 328b788c0..e8e95097a 100644 --- a/flyweight/README.md +++ b/flyweight/README.md @@ -1,24 +1,26 @@ --- -title: Flyweight +title: "Flyweight Pattern in Java: Maximizing Memory Efficiency with Shared Object Instances" +shortTitle: Flyweight +description: "Learn how the Flyweight design pattern optimizes memory usage in Java applications by sharing data among similar objects. Enhance performance and reduce memory footprint with practical examples and detailed explanations." category: Structural language: en tag: - - Gang of Four - - Memory management - - Object composition - - Optimization - - Performance + - Gang of Four + - Memory management + - Object composition + - Optimization + - Performance --- -## Intent +## Intent of Flyweight Design Pattern -The Flyweight pattern's primary intent is to reduce the number of objects created, decrease memory footprint and increase performance by sharing as much data as possible with similar objects. +The Flyweight design pattern in Java is crucial for optimizing memory usage and enhancing application performance. By minimizing the number of objects created, it significantly reduces the memory footprint. The primary goal of the Flyweight pattern is to share as much data as possible among similar objects, thereby improving efficiency and performance. -## Explanation +## Detailed Explanation of Flyweight Pattern with Real-World Examples Real-world example -> A real-world example of the Flyweight design pattern is in a document editor like Microsoft Word or Google Docs. In such applications, each character in a document could potentially be a separate object, which would be highly inefficient in terms of memory usage. Instead, the Flyweight pattern can be used to share character objects. For instance, all instances of the letter 'A' can share a single 'A' object with its intrinsic state (e.g., the shape of the character). The extrinsic state, such as the position, font, and color, can be stored separately and applied as needed. This way, the application efficiently manages memory by reusing existing objects for characters that appear multiple times. +> A real-world application of the Flyweight pattern in Java can be seen in text editors like Microsoft Word or Google Docs. These applications use Flyweight to efficiently manage memory by sharing character objects, reducing the memory footprint significantly. In such applications, each character in a document could potentially be a separate object, which would be highly inefficient in terms of memory usage. Instead, the Flyweight pattern can be used to share character objects. For instance, all instances of the letter 'A' can share a single 'A' object with its intrinsic state (e.g., the shape of the character). The extrinsic state, such as the position, font, and color, can be stored separately and applied as needed. This way, the application efficiently manages memory by reusing existing objects for characters that appear multiple times. In plain words @@ -28,7 +30,7 @@ Wikipedia says > In computer programming, flyweight is a software design pattern. A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. -**Programmatic example** +## Programmatic Example of Flyweight Pattern in Java Alchemist's shop has shelves full of magic potions. Many of the potions are the same so there is no need to create a new object for each of them. Instead, one object instance can represent multiple shelf items so the memory footprint remains small. @@ -176,23 +178,23 @@ Program output: 09:02:52.734 [main] INFO com.iluwatar.flyweight.HolyWaterPotion -- You feel blessed. (Potion=1689843956) ``` -## Applicability +## When to Use the Flyweight Pattern in Java The Flyweight pattern's effectiveness depends heavily on how and where it's used. Apply the Flyweight pattern when all the following are true: -* An application uses a large number of objects. -* Storage costs are high because of the sheer quantity of objects. +* The Flyweight pattern is particularly effective in Java applications that use a large number of objects. +* When storage costs are high due to the quantity of objects, Flyweight helps by sharing intrinsic data and managing extrinsic state separately. * Most of the object state can be made extrinsic. * Many groups of objects may be replaced by relatively few shared objects once the extrinsic state is removed. * The application doesn't depend on object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects. -## Known uses +## Real-World Applications of Flyweight Pattern in Java * [java.lang.Integer#valueOf(int)](http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#valueOf%28int%29) and similarly for Byte, Character and other wrapped types. -* Java’s String class, which uses the Flyweight pattern internally to manage string literals. -* GUI applications, where objects like fonts or graphical components are shared rather than duplicated. +* Java’s String class utilizes the Flyweight pattern to manage string literals efficiently. +* GUI applications often use Flyweight for sharing objects like fonts or graphical components, thereby conserving memory and improving performance. -## Consequences +## Benefits and Trade-offs of Flyweight Pattern Benefits: @@ -204,12 +206,12 @@ Trade-offs: * Increases complexity by adding the management layer for shared objects. * Potential overhead in accessing shared objects if not well implemented. -## Related Patterns +## Related Java Design Patterns * [Composite](https://java-design-patterns.com/patterns/composite/): Often combined with Flyweight when the composites are shareable. Both are used to manage hierarchies and structures of objects. * [State](https://java-design-patterns.com/patterns/state/): Can be used to manage state in a shared Flyweight object, distinguishing internal state (invariant) from external state (context-specific). -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) diff --git a/front-controller/README.md b/front-controller/README.md index 44f61abee..b4576c7ca 100644 --- a/front-controller/README.md +++ b/front-controller/README.md @@ -1,28 +1,30 @@ --- -title: Front Controller +title: "Front Controller Pattern in Java: Centralizing Web Request Handling" +shortTitle: Front Controller +description: "Explore the Front Controller design pattern in Java for centralized request handling. Learn how to improve web application efficiency and consistency with this architectural pattern." category: Architectural language: en tag: - - Architecture - - Decoupling - - Enterprise patterns - - Layered architecture - - Web development + - Architecture + - Decoupling + - Enterprise patterns + - Layered architecture + - Web development --- ## Also known as * Centralized Request Handling -## Intent +## Intent of Front Controller Design Pattern -The Front Controller design pattern aims to provide a centralized entry point for handling all incoming web requests, ensuring that request handling is managed consistently and efficiently across an application. +The Front Controller design pattern aims to provide a centralized entry point for handling all incoming web requests. This pattern ensures consistent and efficient request routing and management across a Java web application. -## Explanation +## Detailed Explanation of Front Controller Pattern with Real-World Examples Real-world example -> Imagine a busy hotel where all guest requests and queries are first directed to a central reception desk. This desk acts as the "front controller" of the hotel, responsible for receiving all inquiries, from room service orders to maintenance requests. The receptionist assesses each request and routes it to the appropriate department—housekeeping, the kitchen, or maintenance. This system centralizes request handling, ensuring that guest needs are addressed efficiently and consistently, similar to how a Front Controller in a software application manages all incoming requests and delegates them to specific handlers. +> In a real-world scenario, a front desk in a hotel serves as the centralized request handling point, similar to how the Front Controller design pattern functions in web application architecture. This desk acts as the "front controller" of the hotel, responsible for receiving all inquiries, from room service orders to maintenance requests. The receptionist assesses each request and routes it to the appropriate department—housekeeping, the kitchen, or maintenance. This system centralizes request handling, ensuring that guest needs are addressed efficiently and consistently, similar to how a Front Controller in a software application manages all incoming requests and delegates them to specific handlers. In plain words @@ -32,7 +34,7 @@ Wikipedia says > The front controller software design pattern is listed in several pattern catalogs and is related to the design of web applications. It is "a controller that handles all requests for a website", which is a useful structure for web application developers to achieve flexibility and reuse without code redundancy. -**Programmatic example** +## Programmatic Example of Front Controller Pattern in Java The Front Controller design pattern is a pattern that provides a centralized entry point for handling all requests in a web application. It ensures that request handling is managed consistently and efficiently across an application. @@ -102,25 +104,25 @@ In this example, when a request is received, the `FrontController` delegates the This is a basic example of the Front Controller pattern, where all requests are handled by a single controller and dispatcher, ensuring consistent and efficient request handling. -## Class diagram +## Detailed Explanation of Front Controller Pattern with Real-World Examples ![Front Controller](./etc/front-controller.png "Front Controller") -## Applicability +## When to Use the Front Controller Pattern in Java -* Web applications requiring a centralized mechanism for request handling. +* The Front Controller design pattern is particularly useful for Java web applications that require a centralized mechanism for request handling. * Systems that need a common processing point for all requests to perform tasks such as authentication, logging, and routing. -## Known uses +## Real-World Applications of Front Controller Pattern in Java * [Apache Struts](https://struts.apache.org/) * Java web frameworks like Spring MVC and JavaServer Faces (JSF) implement the Front Controller pattern through their central dispatcher servlet, which manages web requests and delegates responsibilities. -## Consequences +## Benefits and Trade-offs of Front Controller Pattern Benefits: -* Centralizes request handling, which simplifies maintenance and promotes consistency. +* The main benefit of the Front Controller design pattern is the centralization of request handling, which simplifies maintenance and ensures consistent behavior across the application. * Eases the integration of services like security and user session management. * Facilitates common behavior like routing, logging, and authentication across requests. @@ -129,13 +131,13 @@ Trade-offs: * Can become a bottleneck if not properly managed. * Increases complexity in the dispatcher controller, requiring careful design to avoid tight coupling. -## Related Patterns +## Related Java Design Patterns * [Page Controller](https://java-design-patterns.com/patterns/page-controller/): Front Controller can delegate requests to Page Controllers, which handle specific page requests. This division supports the Single Responsibility Principle. * [Model-View-Controller (MVC)](https://java-design-patterns.com/patterns/model-view-controller/): Front Controller acts as the controller, managing the flow between model and view. * [Command](https://java-design-patterns.com/patterns/command/): Can be used to encapsulate a request as an object, which the Front Controller can manipulate and delegate. -## Credits +## References and Credits * [J2EE Design Patterns](https://amzn.to/4dpzgmx) * [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/function-composition/README.md b/function-composition/README.md index dec490584..3398f4e9f 100644 --- a/function-composition/README.md +++ b/function-composition/README.md @@ -1,14 +1,16 @@ --- -title: Function Composition +title: "Function Composition Pattern in Java: Crafting Elegant Functional Pipelines" +shortTitle: Function Composition +description: "Learn about the Function Composition design pattern in Java. Discover how to create complex functions by combining simpler ones, enhancing code modularity and reusability. Explore real-world examples, benefits, and applications." category: Functional language: en tag: - - Code simplification - - Composition - - Decoupling - - Functional decomposition - - Lambda - - Reusability + - Code simplification + - Composition + - Decoupling + - Functional decomposition + - Lambda + - Reusability --- ## Also known as @@ -17,11 +19,11 @@ tag: * Function Pipelining * Functional Composition -## Intent +## Intent of Function Composition Design Pattern -To enable creating complex functions by composing simpler ones, enhancing modularity and reusability of function-based logic. +The Function Composition design pattern in Java enables the creation of complex functions by combining simpler ones. This enhances modular code and reusability, crucial for maintainable software development. -## Explanation +## Detailed Explanation of Function Composition Pattern with Real-World Examples Real-world example @@ -37,7 +39,11 @@ Wikipedia says > Function composition is an act or mechanism to combine simple functions to build more complicated ones. Like the usual composition of functions in mathematics, the result of each function is passed as the argument of the next, and the result of the last one is the result of the whole. -**Programmatic Example** +## Programmatic Example of Function Composition Pattern in Java + +In the functional programming paradigm, function composition is a powerful technique. For instance, in Java, you can use higher-order functions to compose operations like multiplying and squaring numbers. + +Using Java's functional interfaces, we can define simple functions and compose them. Here's how function composition works in Java. Let's start with defining two simple functions. In this case, we have a function `timesTwo` that multiplies its input by 2, and a function `square` that squares its input. @@ -75,32 +81,31 @@ Result of composing 'timesTwo' and 'square' functions applied to 3 is: 36 This example demonstrates how the Function Composition pattern can be used to create complex functions by composing simpler ones, enhancing modularity and reusability of function-based logic. -## Sequence diagram +## Function Composition Pattern Sequence diagram ![Functional Composition Diagram](./etc/function.composition.urm.png "Functional Composition") -## Applicability +## When to Use the Function Composition Pattern in Java -Use the Function Composer pattern when: +Use the Function Composition pattern when: -* You want to create a pipeline of operations where the output of one function is the input to another. -* You need to enhance the clarity and quality of your code by structuring complex function logic into simpler, reusable components. +* You want to create a pipeline of operations in Java. This enhances code clarity and quality by structuring complex logic into simpler, reusable components. * You are working in a functional programming environment or a language that supports higher-order functions. * When you want to avoid deep nesting of function calls and instead build a pipeline of operations. * When aiming to promote immutability and side-effect-free functions in your design. -## Tutorials +## Function Composition Pattern Java Tutorials * [Function Composition in Java (Medium)](https://functionalprogramming.medium.com/function-composition-in-java-beaf39426f52) * [Functional Programming in Java (Baeldung)](https://www.baeldung.com/java-functional-programming) -## Known uses +## Real-World Applications of Function Composition Pattern in Java * Stream processing in Java 8 and above * Query builders in ORM libraries * Middleware composition in web frameworks -## Consequences +## Benefits and Trade-offs of Function Composition Pattern Benefits: @@ -116,13 +121,13 @@ Trade-offs: * Overhead from creating and managing multiple function objects in memory-intensive scenarios. * May require a paradigm shift for developers unfamiliar with functional programming concepts. -## Related patterns +## Related Java Design Patterns * [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/) - Both patterns allow processing to be broken down into a series of steps, but Functional Composition focuses on function composition rather than responsibility delegation. * [Decorator](https://java-design-patterns.com/patterns/decorator/) - Similar in combining behaviors, but Decorator applies additional behavior to objects, while Functional Composition builds new functions. * [Strategy](https://java-design-patterns.com/patterns/strategy/) - Provides interchangeable functions (strategies), which can be composed in Functional Composition. -## Credits +## References and Credits * [Effective Java](https://amzn.to/4cGk2Jz) * [Functional Programming in Java](https://amzn.to/3JUIc5Q) diff --git a/game-loop/README.md b/game-loop/README.md index f7aa2fcda..69d2d6411 100644 --- a/game-loop/README.md +++ b/game-loop/README.md @@ -1,12 +1,14 @@ --- -title: Game Loop +title: "Game Loop Pattern in Java: Mastering Smooth Game Mechanics" +shortTitle: Game Loop +description: "Learn about the Game Loop design pattern, its implementation in Java, and how it ensures smooth gameplay by continuously updating game state, processing inputs, and rendering. Ideal for real-time simulations and gaming." category: Behavioral language: en tag: - - Concurrency - - Event-driven - - Game programming - - Performance + - Concurrency + - Event-driven + - Game programming + - Performance --- ## Also known as @@ -14,15 +16,15 @@ tag: * Game Cycle * Main Game Loop -## Intent +## Intent of Game Loop Design Pattern -The Game Loop design pattern aims to facilitate the continuous execution of a game, where each loop cycle processes input, updates game state, and renders the game state to the screen, maintaining a smooth and interactive gaming experience. +The Game Loop design pattern is essential for creating smooth and interactive gaming experiences by facilitating continuous game execution. Each loop cycle processes input, updates the game state, and renders the game state to the screen, ensuring consistent performance across all hardware setups. -## Explanation +## Detailed Explanation of Game Loop Pattern with Real-World Examples Real-world example -> An analogous real-world example of the Game Loop pattern can be found in an amusement park ride, such as a roller coaster. The roller coaster operates in a continuous loop, where the state of the ride (the position and speed of the coaster) is continuously updated while the ride is running. The control system of the roller coaster ensures that the cars move smoothly along the track, adjusting speeds, and handling the ride's safety systems in real-time. Just like the game loop, this control system repeatedly processes inputs (such as the current speed and position), updates the state, and triggers outputs (like adjusting the brakes or accelerating the cars) to maintain the desired operation throughout the duration of the ride. +> A practical analogy of the Game Loop can be seen in an amusement park ride, like a roller coaster. Similar to how the ride operates in a loop, updating its state and ensuring smooth operation, the Game Loop continuously processes inputs and updates the game state for a seamless gaming experience. The roller coaster operates in a continuous loop, where the state of the ride (the position and speed of the coaster) is continuously updated while the ride is running. The control system of the roller coaster ensures that the cars move smoothly along the track, adjusting speeds, and handling the ride's safety systems in real-time. Just like the game loop, this control system repeatedly processes inputs (such as the current speed and position), updates the state, and triggers outputs (like adjusting the brakes or accelerating the cars) to maintain the desired operation throughout the duration of the ride. In plain words @@ -32,11 +34,9 @@ Wikipedia says > The central component of any game, from a programming standpoint, is the game loop. The game loop allows the game to run smoothly regardless of a user's input, or lack thereof. -**Programmatic Example** +## Programmatic Example of Game Loop Pattern in Java -Game loop is the main process of all the game rendering threads. It's present in all modern games. It drives input process, internal status update, rendering, AI and all the other processes. - -In our game example, let's start with something simple. Here's `Bullet` class. Bullets will move in our game. For demonstration purposes it's enough that it has 1-dimensional position. +In our Java example, we illustrate a simple game loop controlling a bullet's movement, updating its position, ensuring smooth rendering, and responding to user inputs. The Game Loop is the main process driving all game rendering threads, present in all modern games. It handles input processing, internal status updates, rendering, AI, and other processes. Starting with a simple `Bullet` class, we demonstrate the movement of bullets in our game, focusing on their 1-dimensional position for demonstration purposes. ```java public class Bullet { @@ -303,16 +303,16 @@ Current bullet position: 0.98999935 Stop variable-step game loop. ``` -## Applicability +## When to Use the Game Loop Pattern in Java -The Game Loop pattern is applicable in real-time simulation and gaming where the state needs to be updated continuously and consistently in response to user inputs and other events. +The Game Loop pattern is perfect for real-time simulations and gaming where continuous state updates and smooth frame rates are critical. -## Known Uses +## Real-World Applications of Game Loop Pattern in Java * Video games, both 2D and 3D, across various platforms. * Real-time simulations that require a steady frame rate for updating logic and rendering. -## Consequences +## Benefits and Trade-offs of Game Loop Pattern Benefits: @@ -325,12 +325,12 @@ Trade-offs: * Can lead to performance issues if the loop is not well-managed, especially in resource-intensive updates or rendering. * Difficulty in managing varying frame rates across different hardware. -## Related Patterns +## Related Java Design Patterns * [State](https://java-design-patterns.com/patterns/state/): Often used within a game loop to manage different states of the game (e.g., menu, playing, paused). The relationship lies in managing the state-specific behavior and transitions smoothly within the game loop. * [Observer](https://java-design-patterns.com/patterns/observer/): Useful in a game loop for event handling, where game entities can subscribe to and react to events (e.g., collision, scoring). -## Credits +## References and Credits * [Game Programming Patterns](https://amzn.to/3K96fOn) * [Game Engine Architecture, Third Edition](https://amzn.to/3VgB4av) diff --git a/gateway/README.md b/gateway/README.md index fb01c40a2..0df5d1b74 100644 --- a/gateway/README.md +++ b/gateway/README.md @@ -1,26 +1,30 @@ --- -title: Gateway +title: "Gateway Pattern in Java: Simplifying External System Integration" +shortTitle: Gateway +description: "Discover the Gateway design pattern in Java, a powerful technique for integrating remote services and APIs. Learn how to encapsulate interactions and simplify your application architecture with practical examples and real-world use cases." category: Integration language: en tag: - - API design - - Data access - - Decoupling - - Enterprise patterns + - API design + - Data access + - Decoupling + - Enterprise patterns --- ## Also known as * Service Gateway -## Intent +## Intent of Gateway Design Pattern -The Gateway design pattern aims to encapsulate the interaction with a remote service or external system, providing a simpler and more unified API to the rest of the application. +The Gateway design pattern is a crucial concept in Java design patterns for simplifying API integration and interactions with remote services. It provides a unified and simplified interface to external systems, enhancing the maintainability and architecture of applications. By encapsulating these interactions, the Gateway pattern ensures loose coupling and promotes a more modular and scalable software design, making it essential for robust and efficient application development. -## Explanation +## Detailed Explanation of Gateway Pattern with Real-World Examples Real-world example +> In real-world applications, companies often need to interact with multiple external systems. The Gateway design pattern provides a unified interface for such interactions, handling protocol translation and data transformation, thereby ensuring loose coupling between the internal and external components. ' +> > Consider a logistics company that uses multiple third-party services for various operations, such as shipping, inventory management, and customer notifications. Each of these services has its own API with different protocols and data formats. To simplify the interaction, the company implements a Gateway design pattern. This gateway acts as a unified interface for all third-party service interactions, allowing the company's internal systems to communicate with these services seamlessly. The gateway handles the translation of protocols, data transformation, and routing of requests, ensuring that the internal systems remain decoupled from the specifics of each external service. This setup improves maintainability and scalability while providing a single point of control for external communications. In plain words @@ -31,7 +35,7 @@ Wikipedia says > A server that acts as an API front-end, receives API requests, enforces throttling and security policies, passes requests to the back-end service and then passes the response back to the requester. -**Programmatic Example** +## Programmatic Example of Gateway Pattern in Java First, we define a `Gateway` interface. This interface represents the contract for our external services. Each service that we want to interact with will implement this interface. @@ -126,20 +130,20 @@ Running the example produces the following output. This example demonstrates how the Gateway design pattern can be used to simplify the interaction with multiple external services. Each service is encapsulated behind a common interface, and the application interacts with this interface rather than directly with the services. This reduces coupling and makes the application easier to maintain and extend. -## Applicability +## When to Use the Gateway Pattern in Java -Use the Gateway pattern when you need to integrate with remote services or APIs, and you want to minimize the coupling between your application and external systems. It is particularly useful in microservices architectures where different services need to communicate through well-defined APIs. +Use the Gateway pattern when integrating with remote services or APIs. It is particularly beneficial in microservices architecture to manage communication through well-defined interfaces. -## Known uses +## Real-World Applications of Gateway Pattern in Java * API Gateways in Microservices: Acts as an intermediary that processes incoming requests from clients, directing them to appropriate services within a microservices architecture. * Database Gateways: Provides a unified interface to access data from various database systems, hiding the specifics of database querying and data retrieval. -## Consequences +## Benefits and Trade-offs of Gateway Pattern Benefits: -* Reduces complexity by hiding the details of the external API or service behind a simpler interface. +* The Gateway design pattern reduces complexity by abstracting the details of external APIs and services behind a simpler interface. * Promotes loose coupling between the application and its dependencies on external systems. * Makes the system easier to test and maintain. @@ -148,14 +152,14 @@ Trade-offs: * Introduces an additional layer that could potentially impact performance. * Requires careful design to avoid creating a monolithic gateway that becomes a bottleneck. -## Related Patterns +## Related Java Design Patterns * [Facade](https://java-design-patterns.com/patterns/facade/): Similar to Gateway in abstracting complex subsystems, but Gateway specifically targets external or remote interfaces. * [Adapter](https://java-design-patterns.com/patterns/adapter/): While both patterns provide a different interface to a subsystem, Gateway focuses more on networked data sources and services. * [Proxy](https://java-design-patterns.com/patterns/proxy/): Often used together, as both can control and manage access to another object, but Gateway specifically deals with external services. * [API Gateway](https://java-design-patterns.com/patterns/microservices-api-gateway/): Often considered a specialization of the Gateway pattern, it specifically manages API requests and routes them to the appropriate services within a backend system. -## Credits +## References and Credits * [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/3WcFVui) * [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/guarded-suspension/README.md b/guarded-suspension/README.md index 8a52bc3dc..f13e40684 100644 --- a/guarded-suspension/README.md +++ b/guarded-suspension/README.md @@ -1,13 +1,15 @@ --- -title: Guarded Suspension +title: "Guarded Suspension Pattern in Java: Ensuring Safe Concurrency in Critical Sections" +shortTitle: Guarded Suspension +description: "Learn about the Guarded Suspension design pattern in Java. Understand its implementation for efficient concurrency control, with real-world examples and code snippets." category: Concurrency language: en tag: - - Asynchronous - - Decoupling - - Resource management - - Synchronization - - Thread management + - Asynchronous + - Decoupling + - Resource management + - Synchronization + - Thread management --- ## Also known as @@ -15,15 +17,15 @@ tag: * Conditional Block * Suspended Execution -## Intent +## Intent of Guarded Suspension Design Pattern -The Guarded Suspension pattern manages operations that require both a lock and a condition to proceed, allowing a thread to wait for an appropriate condition while being efficient with resource use. +The Guarded Suspension pattern is crucial in Java design patterns for managing operations that require both a lock and a condition to proceed. It optimizes concurrency control by allowing a thread to wait for the right condition efficiently. -## Explanation +## Detailed Explanation of Guarded Suspension Pattern with Real-World Examples Real-world example -> A real-world example of the Guarded Suspension pattern is a ride-sharing service where passengers wait for a car to be available. When a passenger requests a ride, the request is suspended until a driver becomes available. The system monitors the availability of drivers, and once a driver is ready to take a new passenger, the system notifies the waiting passenger and resumes the ride request process. This ensures that passengers are not continuously checking for available drivers and that drivers are efficiently matched with passengers based on their availability. +> A practical example of the Guarded Suspension pattern can be seen in a ride-sharing service. In this system, passengers wait for a car to become available, ensuring efficient resource use without continuous checking. When a passenger requests a ride, the request is suspended until a driver becomes available. The system monitors the availability of drivers, and once a driver is ready to take a new passenger, the system notifies the waiting passenger and resumes the ride request process. This ensures that passengers are not continuously checking for available drivers and that drivers are efficiently matched with passengers based on their availability. In plain words @@ -33,7 +35,9 @@ Wikipedia says > In concurrent programming, Guarded Suspension manages operations requiring a lock and a precondition, delaying execution until the precondition is met. -**Programmatic Example** +## Programmatic Example of Guarded Suspension Pattern in Java + +The `GuardedQueue` class in Java showcases concurrent programming using the Guarded Suspension pattern. It includes synchronized methods that manage thread management and synchronization, demonstrating how threads wait for the right conditions to execute. The `GuardedQueue` class demonstrates the Guarded Suspension pattern by encapsulating a queue and providing two synchronized methods, `get` and `put`. The `get` method waits if the queue is empty, while the `put` method adds an item to the queue and notifies any waiting threads. @@ -119,17 +123,17 @@ Execution yields: * The log output shows the sequence of events: the first thread waits, the second thread puts an item, and the first thread then retrieves the item. This demonstrates the Guarded Suspension pattern in action. -## Applicability +## When to Use the Guarded Suspension Pattern in Java -This pattern is used in scenarios where a thread needs to wait for certain conditions to be met before it can proceed, ensuring that resources are utilized only when necessary and reducing the overhead of busy waiting. +This pattern is ideal for scenarios requiring a thread to wait for specific conditions, promoting efficient concurrency control and reducing busy waiting overhead. -## Known Uses +## Real-World Applications of Guarded Suspension Pattern in Java * Network servers waiting for client requests. * Producer-consumer scenarios where the consumer must wait for the producer to provide data. * Event-driven applications where actions are triggered only after specific events have occurred. -## Consequences +## Benefits and Trade-offs of Guarded Suspension Pattern Benefits: @@ -141,13 +145,13 @@ Trade-offs: * Complexity in implementation, especially when multiple conditions need to be managed. * Potential for deadlocks if not carefully managed. -## Related Patterns +## Related Java Design Patterns * [Monitor](https://java-design-patterns.com/patterns/monitor/): Both patterns manage the synchronization of threads based on conditions. Guarded Suspension specifically deals with suspending threads until conditions are met, while Monitor Object encapsulates condition and mutual exclusion handling. * [Producer-Consumer](https://java-design-patterns.com/patterns/producer-consumer/): Often implemented using Guarded Suspension to handle waiting consumers and producers efficiently. * [Balking](https://java-design-patterns.com/patterns/balking/): Similar to Guarded Suspension, Balking is used when a thread checks a condition and only proceeds if the condition is favorable; if not, it immediately returns or bails out. This pattern complements Guarded Suspension by managing actions based on immediate condition checks without waiting. -## Credits +## References and Credits * [Concurrent Programming in Java : Design Principles and Patterns](https://amzn.to/4dIBqxL) * [Java Concurrency in Practice](https://amzn.to/3JxnXek) diff --git a/half-sync-half-async/README.md b/half-sync-half-async/README.md index 5f3383730..784197023 100644 --- a/half-sync-half-async/README.md +++ b/half-sync-half-async/README.md @@ -1,12 +1,14 @@ --- -title: Half-Sync/Half-Async +title: "Half-Sync/Half-Async Pattern in Java: Enhancing System Performance with Dual Processing" +shortTitle: Half-Sync/Half-Async +description: "Learn how the Half-Sync/Half-Async design pattern in Java improves concurrency and system efficiency by decoupling asynchronous and synchronous processing. Explore real-world examples, programmatic implementations, and key use cases." category: Concurrency language: en tag: - - Asynchronous - - Decoupling - - Synchronization - - Thread management + - Asynchronous + - Decoupling + - Synchronization + - Thread management --- ## Also known as @@ -14,15 +16,15 @@ tag: * Async-Sync Bridge * Half-Synchronous/Half-Asynchronous -## Intent +## Intent of Half-Sync/Half-Async Design Pattern -The Half-Sync/Half-Async pattern aims to decouple asynchronous and synchronous processing in concurrent systems, allowing efficient interaction and data exchange between asynchronous and synchronous components. +The Half-Sync/Half-Async pattern in Java aims to decouple asynchronous and synchronous processing in concurrent systems, enhancing efficiency and performance. This pattern is particularly useful for managing complex concurrent operations in software systems. -## Explanation +## Detailed Explanation of Half-Sync/Half-Async Pattern with Real-World Examples Real-world example -> Imagine a busy restaurant kitchen where the process of taking orders is asynchronous, allowing waiters to continue taking orders from customers without waiting for the chefs to cook the previous ones. Meanwhile, the cooking (synchronous part) follows a specific sequence and requires waiting for each dish to be prepared before starting the next. This setup enables the restaurant to handle multiple customer orders efficiently, while ensuring each dish is cooked with the required attention and timing, much like the Half-Sync/Half-Async pattern manages asynchronous tasks and synchronous processing in software systems. +> Imagine a busy restaurant kitchen where order taking is asynchronous, allowing waiters to keep working while chefs cook each dish synchronously. Similarly, the Half-Sync/Half-Async pattern handles multiple asynchronous tasks and synchronous processing in Java applications efficiently. Meanwhile, the cooking (synchronous part) follows a specific sequence and requires waiting for each dish to be prepared before starting the next. This setup enables the restaurant to handle multiple customer orders efficiently, while ensuring each dish is cooked with the required attention and timing, much like the Half-Sync/Half-Async pattern manages asynchronous tasks and synchronous processing in software systems. In plain words @@ -32,11 +34,11 @@ Wikipedia says > The Half-Sync/Half-Async design pattern is used to solve situations where one part of the application runs synchronously while another runs asynchronously, and the two modules need to communicate with each other. -## Programmatic Example +## Programmatic Example of Half-Sync/Half-Async Pattern in Java The Half-Sync/Half-Async design pattern is a concurrency pattern that separates synchronous and asynchronous processing in a system, simplifying the programming model without affecting performance. It's particularly useful in scenarios where you have a mix of short, mid, and long duration tasks. -In the provided code, we can see an example of the Half-Sync/Half-Async pattern in the `App`, `AsynchronousService`, and `ArithmeticSumTask` classes. +In the provided Java implementation, we can see an example of the Half-Sync/Half-Async pattern in the `App`, `AsynchronousService`, and `ArithmeticSumTask` classes. The `App` class is the entry point of the application. It creates an instance of `AsynchronousService` and uses it to handle various tasks asynchronously. @@ -126,27 +128,25 @@ Running the code produces: This is a basic example of the Half-Sync/Half-Async pattern, where tasks are enqueued and processed asynchronously, while the main thread continues to handle other tasks. -## Applicability +## When to Use the Half-Sync/Half-Async Pattern in Java Use the Half-Sync/Half-Async pattern in scenarios where: -* High-performance is required and the system must handle asynchronous operations along with synchronous processing. +* High performance and efficient concurrency are crucial, such as in Java's standard libraries and network servers managing concurrent connections. * The system needs to effectively utilize multicore architectures to balance tasks between asynchronous and synchronous processing. * Decoupling of asynchronous tasks from synchronous processing is necessary to simplify the design and implementation. -## Known uses +## Real-World Applications of Half-Sync/Half-Async Pattern in Java -* [BSD Unix networking subsystem](https://www.dre.vanderbilt.edu/~schmidt/PDF/PLoP-95.pdf) -* [Real Time CORBA](http://www.omg.org/news/meetings/workshops/presentations/realtime2001/4-3_Pyarali_thread-pool.pdf) -* [Android AsyncTask framework](https://developer.android.com/reference/android/os/AsyncTask) +* The Half-Sync/Half-Async pattern is utilized in various frameworks and systems, including BSD Unix networking, Real-Time CORBA, and Android's AsyncTask framework. * Java's standard libraries utilize this pattern with thread pools and execution queues in the concurrency utilities (e.g., java.util.concurrent). * Network servers handling concurrent connections where IO operations are handled asynchronously and processing of requests is done synchronously. -## Consequences +## Benefits and Trade-offs of Half-Sync/Half-Async Pattern Benefits: -* Improves responsiveness and throughput by separating blocking operations from non-blocking operations. +* This pattern improves system responsiveness and throughput by isolating blocking operations from non-blocking ones, making it a valuable design pattern in Java concurrency. * Simplifies programming model by isolating asynchronous and synchronous processing layers. Trade-offs: @@ -154,13 +154,13 @@ Trade-offs: * Adds complexity in managing two different processing modes. * Requires careful design to avoid bottlenecks between the synchronous and asynchronous parts. -## Related Patterns +## Related Java Design Patterns * [Leader/Followers](https://java-design-patterns.com/patterns/leader-followers/): Both patterns manage thread assignments and concurrency, but Leader/Followers uses a single thread to handle all I/O events, dispatching work to others. * [Producer/Consumer](https://java-design-patterns.com/patterns/producer-consumer/): Can be integrated with Half-Sync/Half-Async to manage work queues between the async and sync parts. * [Reactor](https://java-design-patterns.com/patterns/reactor/): Often used with Half-Sync/Half-Async to handle multiple service requests delivered to a service handler without blocking the handler. -## Credits +## References and Credits * [Java Concurrency in Practice](https://amzn.to/4aRMruW) * [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V) diff --git a/health-check/README.md b/health-check/README.md index 1626ef2de..23c7f74f7 100644 --- a/health-check/README.md +++ b/health-check/README.md @@ -1,5 +1,7 @@ --- -title: Health Check +title: "Health Check Pattern in Java: Monitoring System Health for Optimal Operation" +shortTitle: Health Check +description: "Learn about the Health Check pattern in Java, a vital design for monitoring system health and ensuring reliability in microservices and distributed systems. Discover examples, applications, and benefits." category: Behavioral language: en tag: @@ -14,23 +16,23 @@ tag: * Health Monitoring * Service Health Check -## Intent +## Intent of Health Check Design Pattern -The Health Check pattern is designed to proactively monitor the health of individual software components or services, allowing for quick identification and remediation of issues that may affect overall system functionality. +The Health Check pattern in Java is designed to proactively monitor the health of individual software components or services, allowing for quick identification and remediation of issues that may affect overall system functionality in microservices architectures. -## Explanation +## Detailed Explanation of Health Check Pattern with Real-World Examples Real-world example -> Consider a hospital where patient monitoring systems are used to ensure the health of patients. Each monitoring device periodically checks the vital signs of a patient (such as heart rate, blood pressure, and oxygen levels) and reports back to a central system. If any device detects abnormal vital signs, it triggers an alert for immediate medical attention. Similarly, in software, a Health Check pattern allows each service to periodically report its status to a central monitoring system. If a service is found to be unhealthy, the system can take corrective actions such as alerting administrators, restarting the service, or redirecting traffic to healthy instances, thereby ensuring continuous and reliable operation. +> Consider a hospital where patient monitoring systems are used to ensure the health of patients. Each monitoring device periodically checks the vital signs of a patient and reports back to a central system. Similarly, in Java-based software systems, a Health Check pattern allows each service to periodically report its status to a central monitoring system. If any device detects abnormal vital signs, it triggers an alert for immediate medical attention. Similarly, in software, a Health Check pattern allows each service to periodically report its status to a central monitoring system. If a service is found to be unhealthy, the system can take corrective actions such as alerting administrators, restarting the service, or redirecting traffic to healthy instances, thereby ensuring continuous and reliable operation. In plain words > The Health Check Pattern is like a regular doctor's visit for services in a microservices architecture. It helps in early detection of issues and ensures that services are healthy and available. -## Programmatic Example +## Programmatic Example of Health Check Pattern in Java -The Health Check design pattern is a pattern that allows a system to proactively monitor the health of its components. This pattern is particularly useful in distributed systems where the health of individual components can affect the overall health of the system. +The Health Check design pattern is particularly useful in distributed systems where the health of individual components can affect the overall health of the system. Using Spring Boot Actuator, developers can easily implement health checks in Java applications. In the provided code, we can see an example of the Health Check pattern in the `App` class and the use of Spring Boot's Actuator. @@ -75,18 +77,20 @@ In this example, the `check` method contains the logic for the health check. If This is a basic example of the Health Check pattern, where health checks are built into the system and can be easily accessed and monitored. -## Applicability +## When to Use the Health Check Pattern in Java -* Use when building microservices or distributed systems where it is crucial to monitor the health of each service. +* Use when building Java microservices or distributed systems where it is crucial to monitor the health of each service. * Suitable for scenarios where automated systems need to determine the operational status of services to perform load balancing, failover, or recovery operations. -## Known Uses +## Real-World Applications of Health Check Pattern in Java + +Known uses of the Health Check pattern in Java include * Kubernetes liveness and readiness probes * AWS elastic load balancing health checks -* Spring Boot Actuator +* Spring Boot Actuator integrations -## Consequences +## Benefits and Trade-offs of Health Check Pattern Benefits: @@ -99,12 +103,12 @@ Trade-offs: * Additional overhead for implementing and maintaining health check mechanisms. * May introduce complexity in handling false positives and negatives in health status reporting. -## Related Patterns +## Related Java Design Patterns * [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/): Both patterns enhance system resilience; while Health Check monitors health status, Circuit Breaker protects a system from repeated failures. * [Observer](https://java-design-patterns.com/patterns/observer/): Health Check can be seen as a specific use case of the Observer pattern, where the subject being observed is the system’s health. -## Credits +## References and Credits * [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O) * [Release It! Design and Deploy Production-Ready Software](https://amzn.to/3Uul4kF) diff --git a/hexagonal/README.md b/hexagonal-architecture/README.md similarity index 82% rename from hexagonal/README.md rename to hexagonal-architecture/README.md index 6bc47902e..cbb9182b2 100644 --- a/hexagonal/README.md +++ b/hexagonal-architecture/README.md @@ -1,25 +1,27 @@ --- -title: Hexagonal Architecture +title: "Hexagonal Architecture Pattern in Java: Decoupling Core Logic for Enhanced Flexibility" +shortTitle: Hexagonal Architecture +description: "Explore the Hexagonal Architecture pattern in Java. Learn how it decouples core logic from external interfaces, enhances maintainability, and improves testability with practical examples." category: Architectural language: en tag: - - Decoupling - - Layered architecture + - Decoupling + - Layered architecture --- ## Also known as * Ports and Adapters -## Intent +## Intent of Hexagonal Architecture Design Pattern -Hexagonal Architecture, often applied within the Java ecosystem, is designed to promote the decoupling of application's core logic from external interfaces, such as databases, user interfaces, or third-party services, thus allowing an application to be at the center of input/output systems. +Hexagonal Architecture, also known as Ports and Adapters, is a design pattern in Java that promotes decoupling of core business logic from external interfaces like databases and user interfaces. This architectural approach enhances maintainability and testability of software systems. -## Explanation +## Detailed Explanation of Hexagonal Architecture Pattern with Real-World Examples Real-world example -> A real-world analogous example of Hexagonal Architecture can be seen in online banking systems. In such systems, the core banking logic (like processing transactions, managing accounts, and calculating interest) represents the application's core. This core is then surrounded by various adapters that allow the system to interact with different external interfaces without affecting the business logic. For instance, customers might access their accounts through a web interface, a mobile app, or even through ATM services. Meanwhile, the banking system also needs to interface with external services for credit checks, fraud detection, and interbank transactions. Each of these interfaces interacts with the core banking logic through specific adapters designed to translate the external calls to and from the application's internal APIs. This setup allows the bank to modify or extend its external interfaces without having to alter the core business logic, enhancing flexibility and maintainability. +> In online banking systems, Hexagonal Architecture allows core banking logic to remain unaffected by changes in user interfaces or third-party services. This decoupling ensures the system's maintainability and flexibility. In such systems, the core banking logic (like processing transactions, managing accounts, and calculating interest) represents the application's core. This core is then surrounded by various adapters that allow the system to interact with different external interfaces without affecting the business logic. For instance, customers might access their accounts through a web interface, a mobile app, or even through ATM services. Meanwhile, the banking system also needs to interface with external services for credit checks, fraud detection, and interbank transactions. Each of these interfaces interacts with the core banking logic through specific adapters designed to translate the external calls to and from the application's internal APIs. This setup allows the bank to modify or extend its external interfaces without having to alter the core business logic, enhancing flexibility and maintainability. In plain words @@ -29,10 +31,12 @@ Wikipedia says > The hexagonal architecture, or ports and adapters architecture, is an architectural pattern used in software design. It aims at creating loosely coupled application components that can be easily connected to their software environment by means of ports and adapters. This makes components exchangeable at any level and facilitates test automation. -## Programmatic Example +## Programmatic Example of Hexagonal Architecture Pattern in Java The Hexagonal Architecture, also known as Ports and Adapters, is a design pattern that aims to create a loosely coupled application where the core business logic is isolated from external interfaces like databases, user interfaces, or third-party services. This allows the core application to be independent and easily testable. +The Java code example below illustrates how Hexagonal Architecture isolates core business logic using dependency injection, making the application highly testable and independent from external components. + In the provided code, we can see an example of the Hexagonal Architecture pattern in the `App` class and the use of Google's Guice for dependency injection. The `App` class is the entry point of the application. It creates an instance of `LotteryAdministration` and `LotteryService` through dependency injection and uses them to handle various tasks. @@ -164,25 +168,25 @@ Running the main function of App class produces the following output: In this example, the `LotteryAdministration` and `LotteryService` classes are the core of the application. They interact with external interfaces like `LotteryTicketRepository`, `LotteryEventLog`, and `WireTransfers` through dependency injection, keeping the core business logic decoupled from external concerns. This is a basic example of the Hexagonal Architecture pattern, where the core application is at the center of input/output systems. -## Class diagram +## Detailed Explanation of Hexagonal Architecture Pattern with Real-World Examples ![Hexagonal Architecture class diagram](./etc/hexagonal.png) -## Applicability +## When to Use the Hexagonal Architecture Pattern in Java -This pattern is particularly effective in environments where: +Hexagonal Architecture is particularly beneficial in scenarios: * The application needs to interact with multiple external systems. * There is a requirement for high testability and maintainability. * The application should remain unaffected by changes in external interfaces. -## Known Uses +## Real-World Applications of Hexagonal Architecure Pattern in Java * Implemented extensively within enterprise applications that leverage frameworks like Spring. * Used in microservices architectures to maintain clear boundaries and protocols between services. * Adopted in systems that require integration with various databases or external APIs without impacting the business logic. -## Consequences +## Benefits and Trade-offs of Hexagonal Architecture Pattern Benefits: @@ -195,12 +199,12 @@ Trade-offs: * Complexity: Introduces more abstractions and layers, which can complicate the system design and understanding. * Overhead: Might be an over-engineering for simple applications, where simpler architectural patterns could suffice. -## Related Patterns +## Related Java Design Patterns * [Layered Architecture](https://java-design-patterns.com/patterns/layers/): Shares the concept of organizing code into responsibilities; however, Hexagonal emphasizes port-based interaction with external elements. * Microservices: Often used in conjunction with Hexagonal Architecture to define clear boundaries and protocols between services. -## Credits +## References and Credits * [Implementing Domain-Driven Design](https://amzn.to/4dmBjrB) * [Building Microservices](https://amzn.to/3UACtrU) diff --git a/hexagonal/etc/hexagonal.png b/hexagonal-architecture/etc/hexagonal.png similarity index 100% rename from hexagonal/etc/hexagonal.png rename to hexagonal-architecture/etc/hexagonal.png diff --git a/hexagonal/etc/hexagonal.ucls b/hexagonal-architecture/etc/hexagonal.ucls similarity index 100% rename from hexagonal/etc/hexagonal.ucls rename to hexagonal-architecture/etc/hexagonal.ucls diff --git a/hexagonal/etc/hexagonal.urm.puml b/hexagonal-architecture/etc/hexagonal.urm.puml similarity index 100% rename from hexagonal/etc/hexagonal.urm.puml rename to hexagonal-architecture/etc/hexagonal.urm.puml diff --git a/hexagonal/pom.xml b/hexagonal-architecture/pom.xml similarity index 98% rename from hexagonal/pom.xml rename to hexagonal-architecture/pom.xml index 1c49875b0..943e74654 100644 --- a/hexagonal/pom.xml +++ b/hexagonal-architecture/pom.xml @@ -32,7 +32,7 @@ java-design-patterns 1.26.0-SNAPSHOT - hexagonal + hexagonal-architecture org.junit.jupiter diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/App.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/App.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/App.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/App.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java similarity index 100% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/AppTest.java similarity index 100% rename from hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java rename to hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/AppTest.java diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java similarity index 100% rename from hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java rename to hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java similarity index 100% rename from hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java rename to hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java similarity index 100% rename from hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java rename to hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java similarity index 100% rename from hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java rename to hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java similarity index 100% rename from hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java rename to hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java similarity index 100% rename from hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java rename to hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java similarity index 100% rename from hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java rename to hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java similarity index 100% rename from hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java rename to hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java similarity index 100% rename from hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java rename to hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java similarity index 100% rename from hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java rename to hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java similarity index 100% rename from hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java rename to hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java similarity index 100% rename from hexagonal/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java rename to hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java diff --git a/identity-map/README.md b/identity-map/README.md index ca309e763..e2c5318bb 100644 --- a/identity-map/README.md +++ b/identity-map/README.md @@ -1,25 +1,27 @@ --- -title: Identity Map +title: "Identity Map Pattern in Java: Managing Object Identity for Efficiency" +shortTitle: Identity Map +description: "Learn about the Identity Map pattern in Java. This design pattern prevents duplicate objects in memory, improving performance and consistency in your applications. Explore implementation examples, benefits, and best practices." category: Behavioral language: en tag: - - Data access - - Decoupling - - Enterprise patterns - - Object mapping - - Persistence - - Performance + - Data access + - Decoupling + - Enterprise patterns + - Object mapping + - Persistence + - Performance --- -## Intent +## Intent of Identity Map Design Pattern -The Identity Map design pattern aims to ensure that each object gets loaded only once by keeping every loaded object in a map. It looks up objects using the map when referring to them, thus avoiding duplicate objects in memory. +The Identity Map design pattern in Java aims to ensure that each object gets loaded only once by keeping every loaded object in a map, enhancing database performance and memory management. -## Explanation +## Detailed Explanation of Identity Map Pattern with Real-World Examples Real-world example -> Imagine you are organizing a conference and have a registration desk where every attendee must check in. To avoid unnecessary delays and confusion, each attendee's details are entered into a computer system the first time they check in. If the same attendee comes to the desk again, the system quickly retrieves their details without requiring them to re-submit the same information. This ensures each attendee's information is handled efficiently and consistently, similar to how the Identity Map pattern ensures that an object is loaded only once and reused throughout the application. +> Imagine you are organizing a conference and have a registration desk where every attendee must check in. This scenario illustrates the Identity Map pattern in Java which prevents duplicate objects. To avoid unnecessary delays and confusion, each attendee's details are entered into a computer system the first time they check in. If the same attendee comes to the desk again, the system quickly retrieves their details without requiring them to re-submit the same information. This ensures each attendee's information is handled efficiently and consistently, similar to how the Identity Map pattern ensures that an object is loaded only once and reused throughout the application. In plain words @@ -29,9 +31,11 @@ Wikipedia says > In the design of DBMS, the identity map pattern is a database access design pattern used to improve performance by providing a context-specific, in-memory cache to prevent duplicate retrieval of the same object data from the database. -**Programmatic Example** +## Programmatic Example of Identity Map Pattern in Java -For the purpose of this demonstration assume we have already created a database instance **db**. Let's first look at the implementation of a person entity, and it's fields: +For the purpose of this demonstration in Java programming, assume we have already created a database instance, showcasing the Identity Map pattern to avoid duplicate objects in memory. + +Let's first look at the implementation of `Person` entity, and it's fields: ```java @EqualsAndHashCode(onlyExplicitlyIncluded = true) @@ -175,20 +179,20 @@ Running the example produces the following console output: 11:19:43.780 [main] INFO com.iluwatar.identitymap.App -- Person ID is : 2 ; Person Name is : Thomas ; Phone Number is :42273631 ``` -## Applicability +## When to Use the Identity Map Pattern in Java -This pattern is used in scenarios where multiple accesses to the same data occur within a single session or transaction, especially in complex systems where object identity needs to be preserved across transactions or requests in a Java application. +The Identity Map design pattern is used in Java applications where multiple accesses to the same data occur within a single session or transaction, ensuring efficient object mapping and consistency. -## Tutorials +## Identity Map Pattern Java Tutorials * [Identity Map Pattern (Source Code Examples)](https://www.sourcecodeexamples.net/2018/04/identity-map-pattern.html) -## Known Uses +## Real-World Applications of Identity Map Pattern in Java -* ORM (Object-Relational Mapping) frameworks often implement Identity Maps to handle database interactions more efficiently. +* ORM (Object-Relational Mapping) frameworks in Java often implement Identity Maps to handle database interactions more efficiently, demonstrating the pattern’s importance in Java design patterns. * Enterprise applications to maintain consistent data states across different business processes. -## Consequences +## Benefits and Trade-offs of Identity Map Pattern Benefits: @@ -201,12 +205,12 @@ Trade-offs: * Increases complexity in object management and persistence logic. * Can lead to stale data if not managed correctly, especially in concurrent environments. -## Related Patterns +## Related Java Design Patterns * [Data Mapper](https://java-design-patterns.com/patterns/data-mapper/): Separates persistence logic from domain logic. Identity Map can be used by a Data Mapper to ensure that each object is loaded only once, enhancing performance and data consistency. * [Unit of Work](https://java-design-patterns.com/patterns/unit-of-work/): Coordinates the actions of multiple objects by keeping track of changes and handling transactional consistency. Identity Map is used within the Unit of Work to track the objects being affected by a transaction. -## Credits +## References and Credits * [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) * [Java Persistence with Hibernate](https://amzn.to/4aUfyhd) diff --git a/intercepting-filter/README.md b/intercepting-filter/README.md index 7258f544c..6bf0ec488 100644 --- a/intercepting-filter/README.md +++ b/intercepting-filter/README.md @@ -1,21 +1,23 @@ --- -title: Intercepting Filter +title: "Intercepting Filter Pattern in Java: Enhancing Request Processing in Web Applications" +shortTitle: Intercepting Filter +description: "Learn about the Intercepting Filter Pattern in Java. Discover how to design, implement, and use this pattern to enhance web request handling with practical examples and detailed explanations." category: Architectural language: en tag: - - API design - - Decoupling - - Layered architecture - - Performance - - Security - - Web development + - API design + - Decoupling + - Layered architecture + - Performance + - Security + - Web development --- -## Intent +## Intent of Intercepting Filter Design Pattern -The Intercepting Filter pattern is intended to provide a pluggable framework for preprocessing and postprocessing web requests and responses. It allows different filters to process client requests and server responses in a configurable, decoupled manner. +The Intercepting Filter Pattern in Java is a powerful design pattern that allows for efficient web request handling. This pattern enables the application of multiple filters in a filter chain to process and modify requests and responses. -## Explanation +## Detailed Explanation of Intercepting Filter Pattern with Real-World Examples Real-world example @@ -29,11 +31,11 @@ Wikipedia says > Intercepting Filter is a Java pattern which creates pluggable filters to process common services in a standard manner without requiring changes to core request processing code. -## Programmatic Example +## Programmatic Example of Intercepting Filter Pattern in Java -Intercepting Filter is a pattern that creates pluggable filters to process common services in a standard manner without requiring changes to core request processing code. These filters can perform tasks such as authentication, logging, data compression, and encryption. +In this article, we delve into the Intercepting Filter Pattern and provide a Java example to illustrate its use. This pattern is essential for Java web development, offering a modular approach to handling common services such as logging, authentication, and data compression. -In the provided code, we can see an example of the Intercepting Filter pattern in the `App`, `FilterManager`, `Client`, and various `Filter` classes. +The Java implementation of the Intercepting Filter Pattern includes classes like `FilterManager` and `Client`, which facilitate the management and application of filters. Each filter in the chain performs specific tasks, ensuring a clean and efficient design. The `App` class is the entry point of the application. It creates an instance of `FilterManager`, adds various filters to it, and sets it to a `Client`. @@ -114,26 +116,26 @@ public class NameFilter extends AbstractFilter { In this example, the `App` class sets up a `FilterManager` with various filters and assigns it to a `Client`. When the `Client` sends a request, the `FilterManager` applies all the filters to the request. This is a basic example of the Intercepting Filter pattern, where common processing tasks are encapsulated in filters and applied to requests in a standard manner. -## Applicability +## When to Use the Intercepting Filter Pattern in Java Use the Intercepting Filter pattern when -* Use the Intercepting Filter pattern when you need to apply pre-processing and post-processing steps to requests and responses, typically in web applications. +* In Java web applications to manage cross-cutting concerns. +* When you need to apply pre-processing and post-processing steps to requests and responses, typically in web applications. * Suitable for handling cross-cutting concerns such as logging, authentication, data compression, and encryption transparently. -## Tutorials +## Intercepting Filter Pattern Java Tutorials * [Introduction to Intercepting Filter Pattern in Java (Baeldung)](https://www.baeldung.com/intercepting-filter-pattern-in-java) * [Design Pattern - Intercepting Filter Pattern (TutorialsPoint)](http://www.tutorialspoint.com/design_pattern/intercepting_filter_pattern.htm) -## Known Uses +## Real-World Applications of Intercepting Filter Pattern in Java -* Web servers like Apache Tomcat and Java EE web containers often use this pattern to implement filters that manipulate byte streams from requests and responses. -* Frameworks like Spring MVC utilize this pattern to manage interceptors that add behavior to web requests. +* Frameworks like Spring MVC and web servers such as Apache Tomcat utilize the Intercepting Filter Pattern to enhance Java web development. This pattern's ability to centralize control and streamline web request handling makes it a go-to choice for developers. * [javax.servlet.FilterChain](https://tomcat.apache.org/tomcat-8.0-doc/servletapi/javax/servlet/FilterChain.html) and [javax.servlet.Filter](https://tomcat.apache.org/tomcat-8.0-doc/servletapi/javax/servlet/Filter.html) * [Struts 2 - Interceptors](https://struts.apache.org/core-developers/interceptors.html) -## Consequences +## Benefits and Trade-offs of Intercepting Filter Pattern Benefits: @@ -146,12 +148,12 @@ Trade-offs: * Introducing many filters can lead to performance overhead due to the processing of each request and response through multiple filters. * Debugging and tracing the request flow through multiple filters can be complex. -## Related Patterns +## Related Java Design Patterns * [Decorator](https://java-design-patterns.com/patterns/decorator/): Filters in the Intercepting Filter pattern can be considered as decorators that add additional responsibilities to request handling. They modify the request/response without altering their fundamental behavior. * [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Filters are linked in a chain, where each filter processes the request or response and optionally passes it to the next filter in the chain, similar to how responsibilities are passed along in the Chain of Responsibility pattern. -## Credits +## References and Credits * [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap) * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) diff --git a/interpreter/README.md b/interpreter/README.md index c470b87ed..0eeb035dc 100644 --- a/interpreter/README.md +++ b/interpreter/README.md @@ -1,26 +1,28 @@ --- -title: Interpreter +title: "Interpreter Pattern in Java: Building Custom Parsers for Java Applications" +shortTitle: Interpreter +description: "Explore the Interpreter Design Pattern in Java with real-world examples, class diagrams, and step-by-step implementation. Learn when and how to use this powerful behavioral pattern." category: Behavioral language: en tag: - - Abstraction - - Data transformation - - Decoupling - - Domain - - Gang of Four - - Polymorphism - - Runtime + - Abstraction + - Data transformation + - Decoupling + - Domain + - Gang of Four + - Polymorphism + - Runtime --- -## Intent +## Intent of Interpreter Design Pattern -The Interpreter pattern is used to define a grammatical representation for a language and provides an interpreter to deal with this grammar. +The Interpreter design pattern is used to define a grammatical representation for a language and provides an interpreter to handle this grammar. This pattern is useful in scenarios where a specific set of rules or grammar needs to be interpreted and acted upon, such as in arithmetic expressions or scripting languages. -## Explanation +## Detailed Explanation of Interpreter Pattern with Real-World Examples Real-world example -> Consider a calculator application designed to interpret and calculate expressions entered by users. The application uses the Interpreter pattern to parse and evaluate arithmetic expressions such as "5 + 3 * 2". Here, the Interpreter translates each part of the expression into objects that represent numbers and operations (like addition and multiplication). These objects follow a defined grammar that allows the application to understand and compute the result correctly based on the rules of arithmetic. Each element of the expression corresponds to a class in the program's structure, simplifying the parsing and evaluation process for any inputted arithmetic formula. +> Consider a calculator application designed to interpret and calculate expressions entered by users. The application uses the Interpreter pattern in Java to parse and evaluate arithmetic expressions such as "5 + 3 * 2". Here, the Interpreter translates each part of the expression into objects that represent numbers and operations. These objects follow a defined grammar that allows the application to understand and compute the result correctly based on the rules of arithmetic. Each element of the expression corresponds to a class in the program's structure, simplifying the parsing and evaluation process for any inputted arithmetic formula. In plain words @@ -30,9 +32,9 @@ Wikipedia says > In computer programming, the interpreter pattern is a design pattern that specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialized computer language. The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence for a client. -**Programmatic example** +## Programmatic Example of Interpreter Pattern in Java -To be able to interpret basic math, we need a hierarchy of expressions. The basic abstraction for it is the `Expression` class. +To be able to interpret basic math in Java, we need a hierarchy of expressions. The `Expression` class is the base, and concrete implementations like `NumberExpression` handle specific parts of the grammar. The Interpreter pattern in Java simplifies parsing and evaluating arithmetic expressions by translating them into a structured format that the application can process. ```java public abstract class Expression { @@ -172,18 +174,18 @@ Executing the program produces the following console output. 13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- result: 8 ``` -## Class diagram +## Detailed Explanation of Interpreter Pattern with Real-World Examples ![Interpreter](./etc/interpreter_1.png "Interpreter") -## Applicability +## When to Use the Interpreter Pattern in Java -Use the Interpreter pattern when there is a language to interpret, and you can represent statements in the language as abstract syntax trees. The Interpreter pattern works best when +Use the Interpreter design pattern when there is a language to interpret, and you can represent statements in the language as abstract syntax trees. The Interpreter pattern works best when * The grammar is simple. For complex grammars, the class hierarchy for the grammar becomes large and unmanageable. Tools such as parser generators are a better alternative in such cases. They can interpret expressions without building abstract syntax trees, which can save space and possibly time. * Efficiency is not a critical concern. The most efficient interpreters are usually not implemented by interpreting parse trees directly but by first translating them into another form. For example, regular expressions are often transformed into state machines. But even then, the translator can be implemented by the Interpreter pattern, so the pattern is still applicable. -## Known uses +## Real-World Applications of Interpreter Pattern in Java * [java.util.Pattern](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) * [java.text.Normalizer](http://docs.oracle.com/javase/8/docs/api/java/text/Normalizer.html) @@ -191,7 +193,7 @@ Use the Interpreter pattern when there is a language to interpret, and you can r * [javax.el.ELResolver](http://docs.oracle.com/javaee/7/api/javax/el/ELResolver.html) * SQL parsers in various database management systems. -## Consequences +## Benefits and Trade-offs of Interpreter Pattern Benefits: @@ -203,12 +205,12 @@ Trade-offs: * Can become complex and inefficient for large grammars. * Each rule in the grammar results in a class, leading to a large number of classes for complex grammars. -## Related Patterns +## Related Java Design Patterns * [Composite](https://java-design-patterns.com/patterns/composite/): Often used together, where the Interpreter pattern leverages the Composite pattern to represent the grammar as a tree structure. * [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Useful for sharing state to reduce memory usage in the Interpreter pattern, particularly for interpreters that deal with repetitive elements in a language. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) diff --git a/iterator/README.md b/iterator/README.md index 4bebff534..49bca61a0 100644 --- a/iterator/README.md +++ b/iterator/README.md @@ -1,25 +1,27 @@ --- -title: Iterator +title: "Iterator Pattern in Java: Mastering Sequential Element Access" +shortTitle: Iterator +description: "Learn how to implement the Iterator Design Pattern in Java. Access elements of a collection sequentially without exposing its underlying structure. Explore real-world examples, code snippets, and benefits of using iterators." category: Behavioral language: en tag: - - Data access - - Data transformation - - Decoupling - - Gang of Four - - Object composition - - Polymorphism + - Data access + - Data transformation + - Decoupling + - Gang of Four + - Object composition + - Polymorphism --- ## Also known as * Cursor -## Intent +## Intent of Iterator Design Pattern -The Iterator pattern provides a way to access elements of an aggregate object sequentially without exposing its underlying representation. +The Iterator Design Pattern in Java provides a way to access elements of an aggregate object sequentially without exposing its underlying representation. This behavioral pattern is crucial for efficient collection traversal. -## Explanation +## Detailed Explanation of Iterator Pattern with Real-World Examples Real-world example @@ -27,15 +29,15 @@ Real-world example In plain words -> The Iterator design pattern provides a way to access the elements of a collection sequentially without exposing the underlying structure of the collection. +> The Java Iterator Design Pattern provides a method to sequentially access elements of a collection without exposing its underlying structure. This pattern is widely used in Java programming for efficient data access. Wikipedia says > In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements. -**Programmatic Example** +## Programmatic Example of Iterator Pattern in Java -The main class in our example is the `TreasureChest` that contains items. +The main class in our Java Iterator Design Pattern example is the `TreasureChest` that contains items. This demonstrates how to implement and use iterators for efficient collection traversal in Java. ```java public class TreasureChest { @@ -207,26 +209,26 @@ Program output: 13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 14 ``` -## Applicability +## When to Use the Iterator Pattern in Java -Use the Iterator pattern +Use the Iterator design pattern in Java * To access an aggregate object's contents without exposing its internal representation. * To support multiple traversals of aggregate objects. * To provide a uniform interface for traversing different aggregate structures. -## Tutorials +## Iterator Pattern Java Tutorials * [Java - How to Use Iterator? (TutorialsPoint)](http://www.tutorialspoint.com/java/java_using_iterator.htm) -## Known uses +## Real-World Applications of Iterator Pattern in Java * Java Collections Framework utilizes iterators extensively to allow different ways to traverse through collections. * Databases often use iterators to navigate through data records fetched through SQL queries. * [java.util.Iterator](http://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html) * [java.util.Enumeration](http://docs.oracle.com/javase/8/docs/api/java/util/Enumeration.html) -## Consequences +## Benefits and Trade-offs of Iterator Pattern Benefits: @@ -238,13 +240,13 @@ Trade-offs: * Overhead of using an iterator object may slightly reduce performance compared to direct traversal methods. * Complex aggregate structures may require complex iterators that can be difficult to manage or extend. -## Related Patterns +## Related Java Design Patterns * [Composite](https://java-design-patterns.com/patterns/composite/): Iterators are often used to traverse Composite trees. * [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Used to create appropriate iterators for different data structures. * [Visitor](https://java-design-patterns.com/patterns/visitor/): Can be used with Iterator to apply operations over elements of an object structure. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) diff --git a/layered-architecture/README.md b/layered-architecture/README.md index 17c89c208..9fb1fc81f 100644 --- a/layered-architecture/README.md +++ b/layered-architecture/README.md @@ -1,28 +1,30 @@ --- -title: Layered Architecture +title: "Layered Architecture Pattern in Java: Building Scalable and Maintainable Applications" +shortTitle: Layered Architecture +description: "Explore the Layered Architecture design pattern in Java. Learn its benefits, real-world examples, use cases, and how it enhances maintainability and scalability in enterprise applications." category: Architectural language: en tag: - - Abstraction - - Decoupling - - Enterprise patterns - - Layered architecture - - Scalability + - Abstraction + - Decoupling + - Enterprise patterns + - Layered architecture + - Scalability --- ## Also known as * N-Tier Architecture -## Intent +## Intent of Layered Architecture Design Pattern -The Layered Architecture pattern helps organize applications into groups of subtasks at different levels of abstraction, facilitating independent development and maintenance of each layer. +The Layered Architecture design pattern helps organize applications into groups of subtasks at different levels of abstraction, facilitating independent development and maintenance of each layer. -## Explanation +## Detailed Explanation of Layered Architecture Pattern with Real-World Examples Real-world example -> Imagine constructing a modern high-rise building, which is analogous to using the Layered Architecture pattern in software development. Just as a building is divided into layers such as the foundation, structural floors, residential floors, and the rooftop, each with specific functions and built using different materials and techniques, a software application can be similarly structured. +> Imagine constructing a modern high-rise building, analogous to using the Layered Architecture design pattern in software development. This pattern allows each software layer, such as the data layer, service layer, and presentation layer, to support seamless interaction while maintaining independence, enhancing maintainability and scalability. Just as a building is divided into layers such as the foundation, structural floors, residential floors, and the rooftop, each with specific functions and built using different materials and techniques, a software application can be similarly structured. > > In this analogy, the foundation represents the data layer, responsible for managing database operations. The structural floors are akin to the service layer, which contains business logic and rules. The residential floors parallel the presentation layer, which deals with user interfaces and interactions. Finally, the rooftop could be seen as the API layer, allowing external systems to communicate with the application. > @@ -36,7 +38,7 @@ Wikipedia says > In software engineering, multitier architecture (often referred to as n-tier architecture) or multilayered architecture is a client–server architecture in which presentation, application processing, and data management functions are physically separated. -**Programmatic Example** +## Programmatic Example of Layered Architecture in Java On the data layer, we keep our cake building blocks. `Cake` consist of layers and topping. @@ -84,11 +86,11 @@ public class CakeViewImpl implements View { } ``` -## Class diagram +## Detailed Explanation of Layered Architecture Pattern with Real-World Examples ![Layered Architecture](./etc/layers.png "Layered Architecture") -## Applicability +## When to Use the Layered Architecture Pattern in Java This pattern is suitable for structuring applications that can be divided into groups where each group has a specific role or responsibility. Common in enterprise applications, it simplifies dependencies, enhances maintainability, and supports scaling and technology stack segregation. @@ -98,12 +100,12 @@ Use the Layers architecture when * You want to prevent a change from propagating throughout the application. * You want to make your application more maintainable and testable. -## Known Uses +## Real-World Applications of Layered Architecture Pattern in Java * Web applications where the presentation, business logic, and data access layers are distinctly separated. * Enterprise systems where core functionalities are isolated from interface applications and databases. -## Consequences +## Benefits and Trade-offs of Layered Architecture Pattern Benefits @@ -117,12 +119,12 @@ Trade-offs * Complexity in layer management * Challenges in designing an effective layer distribution. -## Related Patterns +## Related Java Design Patterns * [Model-View-Controller](https://java-design-patterns.com/patterns/model-view-controller/): Shares separation of concerns by dividing application into input, processing, and output. Layered Architecture often implements an MVC within its presentation layer. * Service-Oriented Architecture (SOA): Both patterns emphasize modularization but SOA focuses more on distributed services that can be reused across different systems. -## Credits +## References and Credits * [Clean Architecture: A Craftsman's Guide to Software Structure and Design](https://amzn.to/3UoKkaR) * [Java Design Pattern Essentials](https://amzn.to/4drLhHU) diff --git a/lazy-loading/README.md b/lazy-loading/README.md index 88daa7878..ea761250c 100644 --- a/lazy-loading/README.md +++ b/lazy-loading/README.md @@ -1,29 +1,31 @@ --- -title: Lazy Loading +title: "Lazy Loading Pattern in Java: Enhancing Performance with On-Demand Object Initialization" +shortTitle: Lazy Loading +description: "Learn how to implement the Lazy Loading design pattern in Java to optimize memory usage and improve application startup times. Discover practical examples, benefits, and best practices for efficient resource management." category: Performance optimization language: en tag: - - Instantiation - - Memory management - - Optimization - - Performance - - Persistence - - Resource management + - Instantiation + - Memory management + - Optimization + - Performance + - Persistence + - Resource management --- ## Also known as * Lazy Initialization -## Intent +## Intent of Lazy Loading Design Pattern -The Lazy Loading pattern defers object initialization until the object is actually needed, minimizing memory usage and reducing startup times. +The Lazy Loading design pattern in Java defers object initialization until the object is actually needed, minimizing memory usage and reducing startup times. This technique is crucial for optimizing Java application performance. -## Explanation +## Detailed Explanation of Lazy Loading Pattern with Real-World Examples Real-world example -> A real-world analogy for Lazy Loading is using lights in a smart home. Instead of switching all lights on at once when someone enters the house, motion sensors detect and turn on lights only in rooms being used. This approach conserves electricity by activating lights only when and where they're needed, similar to how Lazy Loading delays the initialization of objects until they're actually required. +> A real-world analogy for the Lazy Loading pattern in Java is using lights in a smart home. Instead of switching all lights on at once when someone enters the house, motion sensors detect and turn on lights only in rooms being used. This mirrors how Java developers can optimize performance by delaying object creation. In plain words @@ -33,7 +35,7 @@ Wikipedia says > Lazy loading (also known as asynchronous loading) is a technique used in computer programming, especially web design and web development, to defer initialization of an object until it is needed. It can contribute to efficiency in the program's operation if properly and appropriately used. This makes it ideal in use cases where network content is accessed and initialization times are to be kept at a minimum, such as in the case of web pages. For example, deferring loading of images on a web page until they are needed for viewing can make the initial display of the web page faster. The opposite of lazy loading is eager loading. -**Programmatic Example** +## Programmatic Example of Lazy Loading Pattern in Java The Lazy Loading design pattern is a performance optimization technique that delays the initialization of an object or a costly computation until it's absolutely necessary. This pattern can significantly improve the performance of your application by avoiding unnecessary computation and reducing memory usage. @@ -133,7 +135,7 @@ public class Java8Holder { In this example, the `App` class retrieves a `Heavy` object from `HolderNaive`, `HolderThreadSafe`, and `Java8Holder`. These classes delay the creation of the `Heavy` object until it's actually needed, demonstrating the Lazy Loading pattern. -## Applicability +## When to Use the Lazy Loading Pattern in Java Use Lazy Loading when: @@ -141,13 +143,13 @@ Use Lazy Loading when: * You need to delay object creation to optimize memory usage or improve startup times. * Loading data or resources should happen just-in-time rather than at application startup. -## Known Uses +## Real-World Applications of Lazy Loading Pattern in Java -* Hibernate (Java ORM Framework): Delays loading of related objects until they are accessed. +* Hibernate (Java ORM Framework): Delays loading of related objects until they are accessed, leveraging the Lazy Loading pattern to optimize Java application performance. * JPA annotations @OneToOne, @OneToMany, @ManyToOne, @ManyToMany and fetch = FetchType.LAZY * Spring Framework (Dependency Injection): Loads beans only when required, reducing application startup time. -## Consequences +## Benefits and Trade-offs of Lazy Loading Pattern Benefits: @@ -159,13 +161,13 @@ Trade-offs: * Complexity in implementation if objects are interdependent. * Risk of latency spikes if initialization occurs at an unexpected point. -## Related Patterns +## Related Java Design Patterns * [Proxy](https://java-design-patterns.com/patterns/proxy/): Can act as a placeholder for lazy-loaded objects, deferring their actual loading until necessary. * Virtual Proxy: Specific type of Proxy that handles object creation on demand. * [Singleton](https://java-design-patterns.com/patterns/singleton/): Often combined with Lazy Loading to ensure only one instance of an object is created and loaded lazily. -## Credits +## References and Credits * [J2EE Design Patterns](https://amzn.to/4dpzgmx) * [Java Performance: The Definitive Guide: Getting the Most Out of Your Code](https://amzn.to/3Wu5neF) diff --git a/leader-election/README.md b/leader-election/README.md index d3b5e7e81..282ea9bac 100644 --- a/leader-election/README.md +++ b/leader-election/README.md @@ -1,13 +1,15 @@ --- -title: Leader Election +title: "Leader Election Pattern in Java: Mastering Node Coordination and Consensus" +shortTitle: Leader Election +description: "Learn how the Leader Election design pattern helps Java applications maintain consistency, fault tolerance, and scalability in distributed systems. Discover examples, use cases, and implementation details." category: Concurrency language: en tag: - - API design - - Cloud distributed - - Fault tolerance - - Scalability - - Synchronization + - API design + - Cloud distributed + - Fault tolerance + - Scalability + - Synchronization --- ## Also known as @@ -15,15 +17,15 @@ tag: * Coordinator Election * Master Election -## Intent +## Intent of Leader Election Design Pattern -Enable a system to elect a leader from a group of nodes, ensuring that the leader is consistently recognized and able to coordinate tasks while the other nodes remain followers. +The Leader Election design pattern is crucial for enabling a system to elect a leader from a group of nodes, ensuring the leader is consistently recognized and able to coordinate tasks while other nodes remain followers. This pattern is fundamental in distributed systems, particularly for achieving fault tolerance and high availability. -## Explanation +## Detailed Explanation of Leader Election Pattern with Real-World Examples Real-world example -> A real-world analogy to the leader election pattern is the election of a team captain in sports. In this analogy, all team members (nodes) participate in the election process, following a set of agreed-upon rules (protocol). Once a captain (leader) is chosen, they assume responsibility for coordinating strategies, giving directions, and representing the team in discussions. If the captain is injured or unavailable, the team holds a new election or appoints a vice-captain (failover mechanism) to ensure that leadership and direction are maintained consistently. +> A real-world analogy to the Leader Election pattern is the election of a team captain in sports. All team members (nodes) participate in the election process, following a set of agreed-upon rules (protocol). Once a captain (leader) is chosen, they assume responsibility for coordinating strategies, giving directions, and representing the team in discussions. If the captain is injured or unavailable, the team holds a new election or appoints a vice-captain (failover mechanism) to ensure that leadership and direction are maintained consistently. In plain words @@ -33,7 +35,7 @@ Wikipedia says > In distributed computing, leader election is the process of designating a single process as the organizer of some task distributed among several computers (nodes). Before the task has begun, all network nodes are either unaware which node will serve as the "leader" (or coordinator) of the task, or unable to communicate with the current coordinator. After a leader election algorithm has been run, however, each node throughout the network recognizes a particular, unique node as the task leader. -**Programmatic Example** +## Programmatic Example of Leader Election Pattern in Java The Leader Election pattern is a design approach that enables a distributed system to select one node as the coordinator or leader to manage tasks and maintain order, while other nodes operate as followers. This pattern is particularly useful in distributed systems where one node needs to act as a central coordinator for a specific function or decision-making process. @@ -135,25 +137,25 @@ The `RingApp` class implements the Ring algorithm for leader election. In this a These examples demonstrate how the Leader Election pattern can be implemented in different ways to suit the specific requirements of a distributed system. -## Class diagram +## Detailed Explanation of Leader Election Pattern with Real-World Examples ![Leader Election](./etc/leader-election.urm.png "Leader Election pattern class diagram") -## Applicability +## When to Use the Leader Election Pattern in Java -Use this pattern in Java applications where: +Use the Leader Election pattern in Java applications where: * A distributed system needs one node to act as the central coordinator for a specific function or decision-making process. * High availability is essential, and the leader should be replaceable in case of failure. * Coordination is required across different nodes in a cluster, particularly in cloud environments. -## Known Uses +## Real-World Applications of Leader Election Pattern in Java * Apache ZooKeeper: Provides leader election for distributed services. * Kubernetes: Elects a leader pod to manage stateful workloads. * Hazelcast: Distributed data grid uses leader election for cluster management. -## Consequences +## Benefits and Trade-offs of Leader Election Pattern Benefits: @@ -167,13 +169,13 @@ Trade-offs: * Overhead: Election processes may introduce performance overhead. * Single Point of Failure: Even with redundancy, the leader can become a bottleneck if not carefully designed. -## Related Patterns +## Related Java Design Patterns * [Observer](https://java-design-patterns.com/patterns/observer/): Followers can observe changes from the leader to stay updated. * [Singleton](https://java-design-patterns.com/patterns/singleton/): The leader functions as a single instance, acting as a unique decision-maker. * [State](https://java-design-patterns.com/patterns/state/): Helps in managing state transitions, particularly in switching leadership roles. -## Credits +## References and Credits * [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/3y6yv1z) * [Distributed Systems: Principles and Paradigms](https://amzn.to/3UN2vbH) diff --git a/leader-followers/README.md b/leader-followers/README.md index df3e790c5..0479ae232 100644 --- a/leader-followers/README.md +++ b/leader-followers/README.md @@ -1,19 +1,21 @@ --- -title: Leader/Followers +title: "Leader-Followers Pattern in Java: Enhancing Efficiency with Dynamic Worker Allocation" +shortTitle: Leader-Followers +description: "Discover the Leader-Followers design pattern for efficient thread management and synchronization. Learn how to optimize resource usage and improve system performance with detailed examples and applications." category: Concurrency language: en tag: - - Decoupling - - Performance - - Synchronization - - Thread management + - Decoupling + - Performance + - Synchronization + - Thread management --- -## Intent +## Intent of Leader/Followers Design Pattern -To manage a set of worker threads efficiently, where multiple threads take turns sharing a set of event sources in order to utilize fewer resources than one-thread-per-source. +To efficiently manage a set of worker threads, the Leader-Followers pattern enables multiple threads to take turns sharing a set of event sources, optimizing resource utilization and improving performance compared to a one-thread-per-source approach. -## Explanation +## Detailed Explanation of Leader/Followers Pattern with Real-World Examples Real-world Example @@ -21,15 +23,15 @@ Real-world Example In plain words -> The Leader and Followers design pattern utilizes a single leader thread to distribute work among multiple follower threads, effectively managing task delegation and thread synchronization to maximize resource efficiency. +> The Leader-Followers design pattern utilizes a single leader thread to distribute work among multiple follower threads, effectively managing task delegation, thread synchronization, and improving resource efficiency in concurrent programming. [martinfowler.com](https://martinfowler.com/articles/patterns-of-distributed-systems/leader-follower.html) says > Select one server in the cluster as a leader. The leader is responsible for taking decisions on behalf of the entire cluster and propagating the decisions to all the other servers. -## Programmatic Example +## Programmatic Example of Leader-Followers Pattern in Java -The Leader/Followers pattern is a concurrency pattern where one thread (the leader) waits for work to arrive, de-multiplexes, dispatches, and processes the work. Once the leader finishes processing the work, it promotes one of the follower threads to be the new leader. This pattern is useful for enhancing CPU cache affinity, minimizing locking overhead, and reducing event dispatching latency. +The Leader-Followers pattern is a concurrency design pattern where one thread (the leader) waits for work to arrive, de-multiplexes, dispatches, and processes the work, thereby enhancing CPU cache affinity and reducing event dispatching latency. Once the leader finishes processing the work, it promotes one of the follower threads to be the new leader. This pattern is useful for enhancing CPU cache affinity, minimizing locking overhead, and reducing event dispatching latency. In the provided code, we have a `WorkCenter` class that manages a group of `Worker` threads. One of these workers is designated as the leader and is responsible for receiving and processing tasks. Once a task is processed, the leader promotes a new leader from the remaining workers. @@ -136,17 +138,17 @@ public class App { This is a basic example of the Leader/Followers pattern. The leader worker processes tasks and promotes a new leader once it finishes a task. The new leader then starts processing the next task, and the cycle continues. -## Applicability +## When to Use the Leader/Followers Pattern in Java -* Useful in scenarios where programs need to handle multiple services on a single thread to avoid resource thrashing and to improve scalability. +* The Leader-Followers pattern is useful in scenarios requiring efficient handling of multiple services on a single thread, avoiding resource thrashing, and improving scalability in concurrent programming environments. * Applicable in server environments where multiple client requests must be handled concurrently with minimal resource consumption. -## Known Uses +## Real-World Applications of Leader-Followers Pattern in Java * Network servers handling multiple incoming connections. * Event-driven applications that manage a large number of input/output sources. -## Consequences +## Benefits and Trade-offs of Leader/Followers Pattern Benefits: @@ -158,12 +160,12 @@ Trade-offs: * Increased complexity in managing the synchronization between leader and followers. * Potential for underutilization of resources if not correctly implemented. -## Related Patterns +## Related Java Design Patterns * [Half-Sync/Half-Async](https://java-design-patterns.com/patterns/half-sync-half-async/): Leader and Followers can be seen as a variation where the synchronization aspect is divided between the leader (synchronous handling) and followers (waiting asynchronously). * [Thread Pool](https://java-design-patterns.com/patterns/thread-pool/): Both patterns manage a pool of worker threads, but Thread Pool assigns tasks to any available thread rather than using a leader to distribute work. -## Credits +## References and Credits * [Java Concurrency in Practice](https://amzn.to/4aRMruW) * [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V) diff --git a/lockable-object/README.md b/lockable-object/README.md index 09ac9e857..9ae3caf52 100644 --- a/lockable-object/README.md +++ b/lockable-object/README.md @@ -1,13 +1,15 @@ --- -title: Lockable Object +title: "Lockable Object Pattern in Java: Implementing Robust Synchronization Mechanisms" +shortTitle: Lockable Object +description: "Learn about the Lockable Object design pattern in Java. Explore its usage, real-world examples, benefits, and how it ensures thread safety and resource management in multithreaded environments." category: Concurrency language: en tag: - - Decoupling - - Encapsulation - - Security - - Synchronization - - Thread management + - Decoupling + - Encapsulation + - Security + - Synchronization + - Thread management --- ## Also known as @@ -15,15 +17,15 @@ tag: * Resource Lock * Mutual Exclusion Object -## Intent +## Intent of Lockable Object Design Pattern -The Lockable Object pattern aims to control access to a shared resource in a multithreaded environment by providing a mechanism for resource locking, ensuring that only one thread can access the resource at a time. +The Lockable Object pattern in Java aims to control access to a shared resource in a multithreaded environment, ensuring thread safety by providing a mechanism for resource locking, ensuring that only one thread can access the resource at a time. -## Explanation +## Detailed Explanation of Lockable Object Pattern with Real-World Examples Real-world example -> Imagine a shared printer in a busy office as an analogous real-world example of the Lockable Object design pattern. Multiple employees need to print documents throughout the day, but the printer can only handle one print job at a time. To manage this, there's a locking system in place—much like a lockable object in programming—that ensures when one person is printing, others must wait their turn. This prevents print jobs from overlapping or interfering with each other, ensuring that each document is printed correctly and in the order it was sent, mirroring the concept of thread synchronization and resource locking in software development. +> Imagine a shared printer in a busy office as an analogous real-world example of the Lockable Object design pattern in Java. This pattern ensures that only one thread can access the resource at a time, thus maintaining concurrency control and synchronization. Multiple employees need to print documents throughout the day, but the printer can only handle one print job at a time. To manage this, there's a locking system in place—much like a lockable object in programming—that ensures when one person is printing, others must wait their turn. This prevents print jobs from overlapping or interfering with each other, ensuring that each document is printed correctly and in the order it was sent, mirroring the concept of thread synchronization and resource locking in software development. In plain words @@ -33,9 +35,9 @@ Wikipedia says > In computer science, a lock or mutex (from mutual exclusion) is a synchronization primitive that prevents state from being modified or accessed by multiple threads of execution at once. Locks enforce mutual exclusion concurrency control policies, and with a variety of possible methods there exist multiple unique implementations for different applications. -**Programmatic Example** +## Programmatic Example of Lockable Object Pattern in Java -The Lockable Object pattern is a concurrency pattern that allows only one thread to access a shared resource at a time. Instead of using the `synchronized` keyword on the methods to be synchronized, the object which implements the Lockable interface handles the request. +The Lockable Object pattern is a concurrency control design pattern in Java that allows only one thread to access a shared resource at a time, ensuring mutual exclusion and preventing data corruption. Instead of using the `synchronized` keyword on the methods to be synchronized, the object which implements the Lockable interface handles the request. In this example, we have a `SwordOfAragorn` object that implements the `Lockable` interface. Multiple `Creature` objects, represented by `Elf`, `Orc`, and `Human` classes, are trying to acquire the sword. Each `Creature` is wrapped in a `Feind` object that implements `Runnable`, allowing each creature to attempt to acquire the sword in a separate thread. @@ -125,20 +127,20 @@ public class App implements Runnable { This example demonstrates the Lockable Object pattern by showing how multiple threads can attempt to acquire a lock on a shared resource, with only one thread being able to acquire the lock at a time. -## Class diagram +## Detailed Explanation of Lockable Object Pattern with Real-World Examples ![Lockable Object](./etc/lockable-object.urm.png "Lockable Object class diagram") -## Applicability +## When to Use the Lockable Object Pattern in Java -* Use the Lockable Object pattern when you need to prevent data corruption by multiple threads accessing a shared resource concurrently. +* Use the Lockable Object pattern in Java when you need to prevent data corruption by multiple threads accessing a shared resource concurrently, ensuring thread safety and robust shared resource management. * Suitable for systems where thread safety is critical and data integrity must be maintained across various operations. -## Known Uses +## Real-World Applications of Lockable Object Pattern in Java * Java’s synchronized keyword and the Lock interfaces in the java.util.concurrent.locks package implement lockable objects to manage synchronization. -## Consequences +## Benefits and Trade-offs of Lockable Object Pattern Benefits: @@ -150,12 +152,12 @@ Trade-offs: * Can lead to decreased performance due to overhead of acquiring and releasing locks. * Potential for deadlocks if not implemented and managed carefully. -## Related Patterns +## Related Java Design Patterns * [Monitor Object](https://java-design-patterns.com/patterns/monitor/): Both patterns manage access to shared resources; Monitor Object combines synchronization and encapsulation of the condition variable. * [Read/Write Lock](https://java-design-patterns.com/patterns/reader-writer-lock/): Specialization of Lockable Object for scenarios where read operations outnumber write operations. -## Credits +## References and Credits * [Java Concurrency in Practice](https://amzn.to/4aRMruW) * [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V) diff --git a/marker/.gitignore b/marker-interface/.gitignore similarity index 100% rename from marker/.gitignore rename to marker-interface/.gitignore diff --git a/marker/README.md b/marker-interface/README.md similarity index 71% rename from marker/README.md rename to marker-interface/README.md index 627c7b83f..1d242f5bc 100644 --- a/marker/README.md +++ b/marker-interface/README.md @@ -1,11 +1,13 @@ --- -title: Marker Interface +title: "Marker Interface Pattern in Java: Defining Behavior Through Empty Interfaces" +shortTitle: Marker Interface +description: "Explore the Marker Interface pattern in Java, its benefits, real-world examples, and common uses. Learn how to use marker interfaces for metadata and special class behaviors." category: Structural language: en tag: - - Encapsulation - - Interface - - Polymorphism + - Encapsulation + - Interface + - Polymorphism --- ## Also known as @@ -13,21 +15,21 @@ tag: * Marker * Tagging Interface -## Intent +## Intent of Marker Interface Design Pattern -The Marker Interface pattern is used to convey metadata about a class in a type-safe manner. Interfaces in Java that have no method declarations are known as marker interfaces. They are used to indicate that a class implementing such an interface possesses some special behavior or capability. +The Marker Interface pattern in Java is used to convey metadata about a class in a type-safe manner. Interfaces in Java that have no method declarations are known as marker interfaces. They are used to indicate that a class implementing such an interface possesses some special behavior or capability. -## Explanation +## Detailed Explanation of Marker Interface Pattern with Real-World Examples Real-world example -> Consider a scenario in a library system where certain books are rare and need special handling procedures, such as restricted check-outs or specific storage conditions. Analogous to the Marker Interface pattern, we could have a marker interface called `RareBook`. Books in the library catalog that implement this interface are flagged as requiring special treatment but don't necessarily have different methods from other books. +> Consider a scenario in a Java library system where certain books are rare and need special handling procedures, such as restricted check-outs or specific storage conditions. Analogous to the Marker Interface pattern, we could have a marker interface called `RareBook`. Books in the library catalog that implement this interface are flagged as requiring special treatment but don't necessarily have different methods from other books. > > When a library staff member processes transactions or handles storage, the system checks if a book implements the `RareBook` interface. If it does, the system automatically enforces rules like "Do not allow check-outs for more than three days" or "Store in a temperature-controlled environment." This use of the marker interface effectively communicates special requirements without altering how books are generally managed, serving simply as a marker for special conditions. In plain words -> The Marker Interface design pattern uses empty interfaces to signal or define certain properties and behaviors of objects in a type-safe way, without requiring specific method implementations. +> The Marker Interface design pattern in Java uses empty interfaces to signal or define certain properties and behaviors of objects in a type-safe way, without requiring specific method implementations. Wikipedia says @@ -35,11 +37,11 @@ Wikipedia says > > To use this pattern, a class implements a marker interface (also called tagging interface) which is an empty interface, and methods that interact with instances of that class test for the existence of the interface. Whereas a typical interface specifies functionality (in the form of method declarations) that an implementing class must support, a marker interface need not do so. The mere presence of such an interface indicates specific behavior on the part of the implementing class. Hybrid interfaces, which both act as markers and specify required methods, are possible but may prove confusing if improperly used. -**Programmatic example** +## Programmatic Example of Marker Interface Pattern in Java The Marker Interface design pattern is a design pattern in computer science that is used with languages that provide run-time type information about objects. It provides a means to associate metadata with a class where the language does not have explicit support for such metadata. -In the given code, the `Permission` interface acts as a marker interface. Classes that implement this interface are marked as having special permissions. Let's break down the code to understand how this pattern is implemented. +In the given Java code example, the Permission interface acts as a marker interface. Classes that implement this interface are marked as having special permissions. Let's break down the code to understand how this pattern is implemented. First, we define the `Permission` interface. This interface doesn't have any methods, making it a marker interface. @@ -99,16 +101,16 @@ public class App { In this way, the Marker Interface pattern allows us to associate metadata (in this case, special permissions) with a class in a type-safe manner. -## Applicability +## When to Use the Marker Interface Pattern in Java Marker interfaces are applicable in scenarios where you want to impose a special behavior or capability on a class, but don't want to force the class to define specific methods. This pattern is commonly used to indicate that a class conforms to a particular contract without needing to implement methods. -## Known uses +## Real-World Applications of Marker Interface Pattern in Java * java.io.Serializable: Classes that implement this interface are capable of being serialized by the Java runtime. * java.lang.Cloneable: Classes that implement this interface can be cloned using the clone method in Java. -## Consequences +## Benefits and Trade-offs of Marker Interface Pattern Benefits: @@ -120,7 +122,7 @@ Trade-offs: * Can lead to empty interfaces in the codebase, which some may consider as not clean or clear in purpose. * Does not enforce any method implementations, which can lead to runtime errors if not properly handled. -## Credits +## References and Credits * [Effective Java](https://amzn.to/4cGk2Jz) * [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525) diff --git a/marker/etc/MarkerDiagram.png b/marker-interface/etc/MarkerDiagram.png similarity index 100% rename from marker/etc/MarkerDiagram.png rename to marker-interface/etc/MarkerDiagram.png diff --git a/marker/etc/MarkerDiagram.ucls b/marker-interface/etc/MarkerDiagram.ucls similarity index 100% rename from marker/etc/MarkerDiagram.ucls rename to marker-interface/etc/MarkerDiagram.ucls diff --git a/marker/etc/marker.urm.puml b/marker-interface/etc/marker.urm.puml similarity index 100% rename from marker/etc/marker.urm.puml rename to marker-interface/etc/marker.urm.puml diff --git a/marker/pom.xml b/marker-interface/pom.xml similarity index 98% rename from marker/pom.xml rename to marker-interface/pom.xml index 89489976b..43ee4bf78 100644 --- a/marker/pom.xml +++ b/marker-interface/pom.xml @@ -32,7 +32,7 @@ 1.26.0-SNAPSHOT 4.0.0 - marker + marker-interface org.junit.jupiter diff --git a/marker/src/main/java/App.java b/marker-interface/src/main/java/App.java similarity index 100% rename from marker/src/main/java/App.java rename to marker-interface/src/main/java/App.java diff --git a/marker/src/main/java/Guard.java b/marker-interface/src/main/java/Guard.java similarity index 100% rename from marker/src/main/java/Guard.java rename to marker-interface/src/main/java/Guard.java diff --git a/marker/src/main/java/Permission.java b/marker-interface/src/main/java/Permission.java similarity index 100% rename from marker/src/main/java/Permission.java rename to marker-interface/src/main/java/Permission.java diff --git a/marker/src/main/java/Thief.java b/marker-interface/src/main/java/Thief.java similarity index 100% rename from marker/src/main/java/Thief.java rename to marker-interface/src/main/java/Thief.java diff --git a/marker/src/test/java/AppTest.java b/marker-interface/src/test/java/AppTest.java similarity index 100% rename from marker/src/test/java/AppTest.java rename to marker-interface/src/test/java/AppTest.java diff --git a/marker/src/test/java/GuardTest.java b/marker-interface/src/test/java/GuardTest.java similarity index 100% rename from marker/src/test/java/GuardTest.java rename to marker-interface/src/test/java/GuardTest.java diff --git a/marker/src/test/java/ThiefTest.java b/marker-interface/src/test/java/ThiefTest.java similarity index 100% rename from marker/src/test/java/ThiefTest.java rename to marker-interface/src/test/java/ThiefTest.java diff --git a/master-worker/README.md b/master-worker/README.md index 2b8d4f856..1b8f7cfef 100644 --- a/master-worker/README.md +++ b/master-worker/README.md @@ -1,11 +1,13 @@ --- -title: Master-Worker +title: "Master-Worker Pattern in Java: Coordinating Concurrent Processing with Ease" +shortTitle: Master-Worker +description: "Discover the Master-Worker design pattern in Java. Learn how it improves concurrency, scalability, and performance through parallel task processing. Includes real-world examples and code snippets." category: Concurrency language: en tag: - - Multithreading - - Performance - - Scalability + - Multithreading + - Performance + - Scalability --- ## Also known as @@ -13,15 +15,15 @@ tag: * Master-Slave * Controller-Worker -## Intent +## Intent of Master-Worker Design Pattern -The Master-Worker pattern is designed to perform parallel computations through the division of labor between coordinating 'master' processes and multiple 'worker' processes. +The Master-Worker design pattern is designed to perform parallel computations by distributing tasks between a master process and multiple worker processes. This pattern enhances concurrency, performance, and scalability in software systems. -## Explanation +## Detailed Explanation of Master-Worker Pattern with Real-World Examples Real-world example -> Imagine a large restaurant kitchen where the head chef acts as the "master" and the line cooks serve as "workers." The head chef receives the orders from the dining area and breaks down each order into specific tasks, such as grilling meat, preparing salads, and cooking desserts. Each task is assigned to a different line cook based on their expertise and current workload. The line cooks work in parallel to prepare their portion of the order, while the head chef oversees the process, ensuring everything is prepared correctly and timely. Once each component of the order is ready, the head chef gathers all parts, gives them a final check, and then plates the dishes for service. This kitchen operation mimics the Master-Worker pattern by distributing and managing tasks to optimize efficiency and output. +> The Master-Worker pattern optimizes parallel task processing and throughput. For instance, in a restaurant kitchen, the head chef (master) delegates tasks to line cooks (workers), who work concurrently to prepare the order. The head chef receives the orders from the dining area and breaks down each order into specific tasks, such as grilling meat, preparing salads, and cooking desserts. Each task is assigned to a different line cook based on their expertise and current workload. The line cooks work in parallel to prepare their portion of the order, while the head chef oversees the process, ensuring everything is prepared correctly and timely. Once each component of the order is ready, the head chef gathers all parts, gives them a final check, and then plates the dishes for service. This kitchen operation mimics the Master-Worker pattern by distributing and managing tasks to optimize efficiency and output. In plain words @@ -31,9 +33,9 @@ Wikipedia says > Master–slave is a model of asymmetric communication or control where one device or process (the master) controls one or more other devices or processes (the slaves) and serves as their communication hub. In some systems, a master is selected from a group of eligible devices, with the other devices acting in the role of slaves. -**Programmatic Example** +## Programmatic Example of Master-Worker Pattern in Java -The Master-Worker pattern is a design pattern that is used for parallel processing. It involves a master component that divides a task into subtasks and distributes them among worker components. The workers process the subtasks independently and return the results to the master, which then aggregates the results to form the final output. +In the provided code, the `MasterWorker` class initiates the concurrent computation process. The `Master` class divides the work among `Worker` objects, each performing its task in parallel, thus optimizing task processing and enhancing system efficiency. ```java // The MasterWorker class acts as the main entry point for the Master-Worker system. @@ -105,23 +107,23 @@ public abstract class Result { The `Input` class has a `divideData` method that is used to divide the input data into subtasks. The `Result` class simply encapsulates the result data. -## Applicability +## When to Use the Master-Worker Pattern in Java * Suitable for scenarios where a task can be decomposed into smaller, independent tasks. * Useful in applications requiring concurrent execution to enhance performance. * Applicable in distributed computing where tasks need to be processed by multiple processors or machines. -## Tutorials +## Master-Worker Pattern Java Tutorials * [Master-Worker Pattern (Gigaspaces)](https://docs.gigaspaces.com/sbp/master-worker-pattern.html) -## Known Uses +## Real-World Applications of Master-Worker Pattern in Java * Implemented in distributed systems to manage tasks across different computing resources. * Used in server architectures to process multiple client requests simultaneously. * Utilized in scientific computation frameworks where large datasets require parallel processing. -## Consequences +## Benefits and Trade-offs of Master-Worker Pattern Benefits: @@ -134,13 +136,13 @@ Trade-offs: * Complexity in managing synchronization and state consistency between master and workers. * Overhead of managing communication between master and workers, especially in distributed environments. -## Related Patterns +## Related Java Design Patterns * Task Parallelism and Data Parallelism: Master-Worker utilizes these patterns to divide work into tasks or data segments. * [Producer-Consumer](https://java-design-patterns.com/patterns/producer-consumer/): Similar in structure but focuses on balancing production and consumption rates; Master-Worker is more about task distribution and aggregation. * [Pipeline](https://java-design-patterns.com/patterns/pipeline/): Both organize processing steps but Pipeline arranges them linearly whereas Master-Worker may not impose such a sequence. -## Credits +## References and Credits * [Distributed Systems: Principles and Paradigms](https://amzn.to/3UN2vbH) * [Java Concurrency in Practice](https://amzn.to/4aRMruW) diff --git a/mediator/README.md b/mediator/README.md index d647b6926..628d976e0 100644 --- a/mediator/README.md +++ b/mediator/README.md @@ -1,23 +1,25 @@ --- -title: Mediator +title: "Mediator Pattern in Java: Simplifying Object Communications in Complex Systems" +shortTitle: Mediator +description: "Learn how the Mediator Design Pattern reduces complexity in object communication and improves system maintainability with a centralized mediator in Java. Explore examples and implementation." category: Behavioral language: en tag: - - Decoupling - - Gang Of Four - - Messaging - - Object composition + - Decoupling + - Gang Of Four + - Messaging + - Object composition --- ## Also known as * Controller -## Intent +## Intent of Mediator Design Pattern The Mediator design pattern is intended to reduce the complexity of communication between multiple objects or classes in a system. It achieves this by providing a centralized mediator class that handles the interactions between different classes, thus reducing their direct dependencies on each other. -## Explanation +## Detailed Explanation of Mediator Pattern with Real-World Examples Real-world example @@ -31,9 +33,9 @@ Wikipedia says > In software engineering, the mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program's running behavior. In object-oriented programming, programs often consist of many classes. Business logic and computation are distributed among these classes. However, as more classes are added to a program, especially during maintenance and/or refactoring, the problem of communication between these classes may become more complex. This makes the program harder to read and maintain. Furthermore, it can become difficult to change the program, since any change may affect code in several other classes. With the mediator pattern, communication between objects is encapsulated within a mediator object. Objects no longer communicate directly with each other, but instead communicate through the mediator. This reduces the dependencies between communicating objects, thereby reducing coupling. -**Programmatic Example** +## Programmatic Example of Mediator Pattern in Java -In this example, the mediator encapsulates how a set of objects interact. Instead of referring to each other directly they use the mediator interface. +In this example, the mediator encapsulates how a set of objects interact. Instead of referring to each other directly, they use the mediator interface. The party members `Rogue`, `Wizard`, `Hobbit`, and `Hunter` all inherit from the `PartyMemberBase`implementing the `PartyMember` interface. @@ -173,11 +175,11 @@ Here's the console output from running the example. 14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Rogue arrives for dinner ``` -## Class diagram +## Detailed Explanation of Mediator Pattern with Real-World Examples ![Mediator](./etc/mediator_1.png "Mediator") -## Applicability +## When to Use the Mediator Pattern in Java Use the Mediator pattern when @@ -185,7 +187,7 @@ Use the Mediator pattern when * Reusing an object is difficult because it refers to and communicates with many other objects * A behavior that's distributed between several classes should be customizable without a lot of subclassing -## Known uses +## Real-World Applications of Mediator Pattern in Java * All scheduleXXX() methods of [java.util.Timer](http://docs.oracle.com/javase/8/docs/api/java/util/Timer.html) * [java.util.concurrent.Executor#execute()](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-) @@ -195,7 +197,7 @@ Use the Mediator pattern when * Java Message Service (JMS) uses mediators to handle message exchanges between clients and servers. * JavaBeans property change support class (java.beans.PropertyChangeSupport) acts as a mediator by handling communication between beans regarding property changes. -## Consequences +## Benefits and Trade-offs of Mediator Pattern Benefits: @@ -206,13 +208,13 @@ Trade-offs: * Mediator can become a god object coupled with all classes in the system, gaining too much responsibility and complexity. -## Related Patterns +## Related Java Design Patterns * [Observer](https://java-design-patterns.com/patterns/observer/): Often used together, where the mediator pattern can use the observer pattern to notify various objects about state changes. Mediators effectively act as a channel of communication managed by an observer. * [Facade](https://java-design-patterns.com/patterns/facade/): Mediator simplifies communication between components, similar to how a facade simplifies a subsystem interface, but a mediator’s colleagues can communicate back to the mediator. * [Command](https://java-design-patterns.com/patterns/command/): Commands can be mediated as they are dispatched to their receivers, encapsulating a request as an object. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) diff --git a/memento/README.md b/memento/README.md index 43e6f799f..c1c5372b2 100644 --- a/memento/README.md +++ b/memento/README.md @@ -1,14 +1,16 @@ --- -title: Memento +title: "Memento Pattern in Java: Preserving Object State for Undo Operations" +shortTitle: Memento +description: "Learn how to implement the Memento design pattern in Java to capture and restore object state without violating encapsulation. Ideal for undo functionality in applications." category: Behavioral language: en tag: - - Encapsulation - - Gang of Four - - Memory management - - Object composition - - State tracking - - Undo + - Encapsulation + - Gang of Four + - Memory management + - Object composition + - State tracking + - Undo --- ## Also known as @@ -16,15 +18,15 @@ tag: * Snapshot * Token -## Intent +## Intent of Memento Design Pattern -Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later. +The Memento design pattern in Java allows developers to capture and restore an object's internal state without violating encapsulation. -## Explanation +## Detailed Explanation of Memento Pattern with Real-World Examples Real-world example -> Imagine a text editor application that allows users to write and edit documents. The text editor uses the Memento design pattern to implement its undo and redo functionality. Each time a user makes a change to the document, the editor creates a snapshot (memento) of the current state of the document. These snapshots are stored in a history list. When the user clicks the undo button, the editor restores the document to the state saved in the most recent memento. This process allows users to revert to previous versions of their document without exposing or altering the internal data structures of the editor. +> A text editor application can utilize the Memento design pattern in Java to enable undo and redo functionalities. By capturing the current state of a document as a memento each time a change is made, the application can easily restore the document to any previous state. The snapshots are stored in a history list. When the user clicks the undo button, the editor restores the document to the state saved in the most recent memento. This process allows users to revert to previous versions of their document without exposing or altering the internal data structures of the editor. In plain words @@ -34,9 +36,9 @@ Wikipedia says > The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback). -**Programmatic Example** +## Programmatic Example of Memento Pattern in Java -We are working on an astrology application where we need to analyze star properties over time. We are creating snapshots of star states using the Memento pattern. +In our astrology application, we use the Memento pattern to capture and restore the state of star objects. Each state is saved as a memento, allowing us to revert to previous states as needed. Let's first define the types of stars we are capable to handle. @@ -159,19 +161,18 @@ Program output: 14:09:15.881 [main] INFO com.iluwatar.memento.App -- sun age: 10000000 years mass: 500000 tons ``` -## Applicability +## When to Use the Memento Pattern in Java Use the Memento pattern when -* A snapshot of an object's state must be saved so that it can be restored to that state later, and -* A direct interface to obtaining the state would expose implementation details and break the object's encapsulation +* You need to capture an object's state in Java and restore it later without exposing its internal structure. This is crucial for maintaining encapsulation and simplifying the management of object states. +* A direct interface to obtaining the state would expose implementation details and break the object's encapsulation. -## Known uses +## Real-World Applications of Memento Pattern in Java -* Java Util Package: Various classes in the Java Util Package, such as java.util.Date and java.util.Calendar, can be reverted to previous states using similar principles, though not implemented directly as the Memento Pattern. -* Undo mechanisms in software: Text editors and graphic editors often use this pattern to implement undo actions. +The Memento pattern is used in various Java applications, including the java.util.Date and java.util.Calendar classes, which can revert to previous states. It's also common in text editors and graphic editors for undo mechanisms. -## Consequences +## Benefits and Trade-offs of Memento Pattern Benefits: @@ -183,12 +184,12 @@ Trade-offs: * Can be expensive in terms of memory if a large number of states are saved. * Care must be taken to manage the lifecycle of mementos to avoid memory leaks. -## Related Patterns +## Related Java Design Patterns * [Command](https://java-design-patterns.com/patterns/command/): Often used together; commands store state for undoing operations in mementos. * [Prototype](https://java-design-patterns.com/patterns/prototype/): Mementos may use prototyping to store the state. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) diff --git a/metadata-mapping/README.md b/metadata-mapping/README.md index fc5caab15..bd2342709 100644 --- a/metadata-mapping/README.md +++ b/metadata-mapping/README.md @@ -1,19 +1,21 @@ --- -title: Metadata Mapping +title: "Metadata Mapping Pattern in Java: Bridging Objects and Data Stores Seamlessly" +shortTitle: Metadata Mapping +description: "Explore the Metadata Mapping Design Pattern for managing the mapping between database records and objects in Java applications. Learn implementation with Hibernate, use cases, benefits, and best practices." category: Data access language: en tag: - - Decoupling - - Enterprise patterns - - Object mapping - - Persistence + - Decoupling + - Enterprise patterns + - Object mapping + - Persistence --- -## Intent +## Intent of Metadata Mapping Design Pattern -Metadata Mapping is designed to manage the mapping between database records and objects in a way that keeps the database schema and object model decoupled and manageable. +Metadata Mapping Design Pattern is designed to manage the mapping between database records and Java objects in a way that keeps the database schema and object model decoupled and manageable. -## Explanation +## Detailed Explanation of Metadata Mapping Pattern with Real-World Examples Real-world example @@ -27,7 +29,7 @@ Wikipedia says > Create a "virtual [object database](https://en.wikipedia.org/wiki/Object_database)" that can be used from within the programming language. -**Programmatic Example** +## Programmatic Example of Metadata Mapping Pattern in Java Hibernate ORM Tool uses Metadata Mapping Pattern to specify the mapping between classes and tables either using XML or annotations in code. @@ -225,16 +227,16 @@ Console output: 14:44:18.551 [main] INFO o.hibernate.orm.connections.pooling - HHH10001008: Cleaning up connection pool [jdbc:h2:mem:metamapping] ``` -## Applicability +## When to Use the Metadata Mapping Pattern in Java -Use this pattern when you need to bridge the gap between an object-oriented domain model and a relational database, without hard-coding database queries into the domain logic. +Use the Metadata Mapping Design Pattern when you need to bridge the gap between an object-oriented domain model and a relational database in Java applications, without hard-coding database queries into the domain logic. -## Known Uses +## Real-World Applications of Metadata Mapping Pattern in Java -* Object-Relational Mapping (ORM) frameworks like Hibernate, JPA, EclipseLink and MyBatis. +* Object-Relational Mapping (ORM) frameworks like Hibernate, JPA, EclipseLink, and MyBatis frequently utilize the Metadata Mapping Design Pattern to map Java objects to database tables. * Mapping database rows to domain objects in enterprise applications. -## Consequences +## Benefits and Trade-offs of Metadata Mapping Pattern Benefits: @@ -247,13 +249,13 @@ Trade-offs: * Adds complexity due to an additional layer of abstraction. * Can impact performance if not properly optimized. -## Related Patterns +## Related Java Design Patterns * [Data Mapper](https://java-design-patterns.com/patterns/data-mapper/): Metadata Mapping is often used within the broader Data Mapper pattern to facilitate the mapping process. * Active Record: Differently from Active Record, Metadata Mapping separates the data access logic from the domain entities. * [Repository](https://java-design-patterns.com/patterns/repository/): Works well with the Repository pattern by abstracting data access further, allowing more complex domain logic to be cleanly separated from data mapping. -## Credits +## References and Credits * [J2EE Design Patterns](https://amzn.to/4dpzgmx) * [Java Persistence with Hibernate](https://amzn.to/44tP1ox) diff --git a/microservices-aggregrator/README.md b/microservices-aggregrator/README.md index 084eaf569..69d991ba4 100644 --- a/microservices-aggregrator/README.md +++ b/microservices-aggregrator/README.md @@ -1,30 +1,32 @@ --- -title: Microservices Aggregator +title: "Microservices Aggregator Pattern in Java: Building Efficient Composite Services in Java" +shortTitle: Microservices Aggregator +description: "Learn about the Microservices Aggregator Design Pattern with Java examples. Understand its intent, real-world applications, benefits, and trade-offs for scalable system design." category: Architectural language: en tag: - - API design - - Client-server - - Data processing - - Decoupling - - Integration - - Microservices - - Scalability + - API design + - Client-server + - Data processing + - Decoupling + - Integration + - Microservices + - Scalability --- ## Also known as * API Composition -## Intent +## Intent of Microservices Aggregator Design Pattern -To aggregate responses from multiple microservices and return a consolidated response to the client. +The Microservices Aggregator pattern helps aggregate responses from multiple microservices into a single unified response, optimizing client-server interactions in scalable systems. -## Explanation +## Detailed Explanation of Microservices Aggregator Pattern with Real-World Examples Real-world example -> Imagine an online travel booking platform. When a user searches for a vacation package, the platform needs to gather information from several different services: flights, hotels, car rentals, and local attractions. Instead of the user making separate requests to each service, the platform employs an Aggregator Microservice. This microservice calls each of these services, collects their responses, and then consolidates the information into a single, unified response that is sent back to the user. This simplifies the user experience by providing all necessary travel details in one place and reduces the number of direct interactions the user needs to have with the underlying services. +> In a travel booking platform, an Aggregator Microservice consolidates data from flights, hotels, and car rentals microservices, providing a seamless user experience and enhancing scalability. Instead of the user making separate requests to each service, the platform employs an Aggregator Microservice. This microservice calls each of these services, collects their responses, and then consolidates the information into a single, unified response that is sent back to the user. This simplifies the user experience by providing all necessary travel details in one place and reduces the number of direct interactions the user needs to have with the underlying services. In plain words @@ -34,9 +36,9 @@ Stack Overflow says > Microservices Aggregator invokes multiple services to achieve the functionality required by the application. -**Programmatic Example** +## Programmatic Example of Microservices Aggregator Pattern in Java -Our web marketplace needs information about products and their current inventory. It makes a call to an aggregator service, which, in turn, calls the product information and product inventory microservices, returning the combined information. +Our web marketplace utilizes an Aggregator microservice to fetch combined product and inventory information from separate microservices, ensuring efficient data processing and improved system performance. Let's start from the data model. Here's our `Product`. @@ -102,11 +104,11 @@ curl http://localhost:50004/product {"title":"The Product Title.","productInventories":5} ``` -## Applicability +## When to Use the Microservices Aggregator Pattern in Java -The Microservices Aggregator Design Pattern is particularly useful in scenarios where a client requires a composite response that is assembled from data provided by multiple microservices. Common use cases include e-commerce applications where product details, inventory, and reviews might be provided by separate services, or in dashboard applications where aggregated data from various services is displayed in a unified view. +The Microservices Aggregator pattern is ideal for scenarios requiring composite responses from multiple microservices, such as in e-commerce and dashboard applications where aggregated data enhances user experience and system efficiency. -## Consequences +## Benefits and Trade-offs of Microservices Aggregator Pattern Benefits: @@ -120,13 +122,13 @@ Trade-offs: * Single Point of Failure: The aggregator service can become a bottleneck or a single point of failure if not designed with high availability and scalability in mind. * Complexity: Implementing an aggregator can introduce complexity, especially in terms of data aggregation logic and error handling when dealing with multiple services. -## Related Patterns +## Related Java Design Patterns * [API Gateway](https://java-design-patterns.com/patterns/microservices-api-gateway/): The Microservices Aggregator pattern is often used in conjunction with an API Gateway, which provides a single entry point for clients to access multiple microservices. * [Composite](https://java-design-patterns.com/patterns/composite/): The Microservices Aggregator pattern can be seen as a form of the Composite pattern, where the composite is the aggregated response from multiple microservices. * [Facade](https://java-design-patterns.com/patterns/facade/): The Microservices Aggregator pattern can be seen as a form of the Facade pattern, where the facade is the aggregator service that provides a simplified interface to the client. -## Credits +## References and Credits * [Building Microservices: Designing Fine-Grained Systems](https://amzn.to/43aGpSR) * [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/3y6yv1z) diff --git a/microservices-api-gateway/README.md b/microservices-api-gateway/README.md index 71a00ea9d..72b9b521a 100644 --- a/microservices-api-gateway/README.md +++ b/microservices-api-gateway/README.md @@ -1,32 +1,34 @@ --- -title: Microservices API Gateway +title: "Microservices API Gateway Pattern in Java: Simplifying Service Access with a Unified Endpoint" +shortTitle: Microservice API Gateway +description: "Learn how the API Gateway pattern simplifies client-side development, enhances security, and optimizes communication in microservices architecture. Explore examples, benefits, and best practices." category: Integration language: en tag: - - API design - - Cloud distributed - - Decoupling - - Enterprise patterns - - Integration - - Microservices - - Scalability - - Security + - API design + - Cloud distributed + - Decoupling + - Enterprise patterns + - Integration + - Microservices + - Scalability + - Security --- -## Intent +## Intent of Microservices API Gateway Design Pattern -The API Gateway design pattern aims to provide a unified interface to a set of microservices. It acts as a single entry point for clients, routing requests to the appropriate microservices and aggregating results, thereby simplifying the client-side code. +The API Gateway design pattern aims to provide a unified interface to a set of microservices within a microservices architecture. It acts as a single entry point for clients, routing requests to the appropriate microservices and aggregating results, thereby simplifying the client-side code. ## Also known as * API Facade * Backend for Frontends (BFF) -## Explanation +## Detailed Explanation of Microservices API Gateway Pattern with Real-World Examples Real-world example -> In a large e-commerce platform, an API Gateway is used as the single entry point for all client requests. When a user visits the site or uses the mobile app, their requests for product information, user authentication, order processing, and payment are all routed through the API Gateway. The gateway handles tasks such as user authentication, rate limiting to prevent abuse, and logging for monitoring purposes. This setup simplifies the client interface and ensures that all backend microservices, like the product catalog service, user service, order service, and payment service, can evolve independently without affecting the client directly. This also enhances security by providing a centralized point to enforce policies and monitor traffic. +> In a large e-commerce platform, an API Gateway is used as the single entry point for all client requests, simplifying client-side development. When a user visits the site or uses the mobile app, their requests for product information, user authentication, order processing, and payment are all routed through the API Gateway. The API Gateway handles tasks such as user authentication, rate limiting to prevent abuse, and logging for monitoring purposes, enhancing overall security optimization. This setup simplifies the client interface and ensures that all backend microservices can evolve independently without affecting the client directly, thereby enhancing microservices communication. This also enhances security by providing a centralized point to enforce policies and monitor traffic. In plain words @@ -36,7 +38,7 @@ Wikipedia says > API Gateway is a server that acts as an API front-end, receives API requests, enforces throttling and security policies, passes requests to the back-end service and then passes the response back to the requester. A gateway often includes a transformation engine to orchestrate and modify the requests and responses on the fly. A gateway can also provide functionality such as collecting analytics data and providing caching. The gateway can provide functionality to support authentication, authorization, security, audit and regulatory compliance. -**Programmatic Example** +## Programmatic Example of Microservice API Gateway in Java This implementation shows what the API Gateway pattern could look like for an e-commerce site. The`ApiGateway` makes calls to the Image and Price microservices using the `ImageClientImpl` and `PriceClientImpl` respectively. Customers viewing the site on a desktop device can see both price information and an image of a product, so the `ApiGateway` calls both of the microservices and aggregates the data in the `DesktopProduct` model. However, mobile users only see price information; they do not see a product image. For mobile users, the `ApiGateway` only retrieves price information, which it uses to populate the `MobileProduct`. @@ -125,20 +127,20 @@ public class ApiGateway { } ``` -## Applicability +## When to Use the Microservices API Gateway Pattern in Java * When building a microservices architecture, and there's a need to abstract the complexity of microservices from the client. * When multiple microservices need to be consumed in a single request. * For authentication, authorization, and security enforcement at a single point. * To optimize communication between clients and services, especially in a cloud environment. -## Tutorials +## Microservices API Gateway Pattern Java Tutorials * [Exploring the New Spring Cloud Gateway (Baeldung)](https://www.baeldung.com/spring-cloud-gateway) * [Spring Cloud - Gateway(tutorialspoint)](https://www.tutorialspoint.com/spring_cloud/spring_cloud_gateway.htm) * [Getting Started With Spring Cloud Gateway (DZone)](https://dzone.com/articles/getting-started-with-spring-cloud-gateway) -## Consequences +## Benefits and Trade-offs of Microservices API Gateway Pattern Benefits: @@ -153,19 +155,19 @@ Trade-offs: * Can become a bottleneck if not properly scaled. * Adds complexity in terms of deployment and management. -## Known uses +## Real-World Applications of Microservices API Gateway Pattern in Java * E-commerce platforms where multiple services (product info, pricing, inventory) are aggregated for a single view. * Mobile applications that consume various backend services but require a simplified interface for ease of use. * Cloud-native applications that leverage multiple microservices architectures. -## Related patterns +## Related Java Design Patterns * [Aggregator Microservice](https://java-design-patterns.com/patterns/microservices-aggregator/) - The API Gateway pattern is often used in conjunction with the Aggregator Microservice pattern to provide a unified interface to a set of microservices. * [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/) - API Gateways can use the Circuit Breaker pattern to prevent cascading failures when calling multiple microservices. * [Proxy](https://java-design-patterns.com/patterns/proxy/) - The API Gateway pattern is a specialized form of the Proxy pattern, where the gateway acts as a single entry point for clients, routing requests to the appropriate microservices and aggregating results. -## Credits +## References and Credits * [Building Microservices](https://amzn.to/3UACtrU) * [Cloud Native Patterns: Designing change-tolerant software](https://amzn.to/3uV12WN) diff --git a/microservices-log-aggregation/README.md b/microservices-log-aggregation/README.md index 10aeb7e34..c23b1fe43 100644 --- a/microservices-log-aggregation/README.md +++ b/microservices-log-aggregation/README.md @@ -1,16 +1,18 @@ --- -title: Microservices Log Aggregation +title: "Microservices Log Aggregation Pattern in Java: Centralizing Logs for Enhanced Monitoring" +shortTitle: Microservices Log Aggregation +description: "Learn about the Microservices Log Aggregation pattern, a method for centralizing log collection and analysis to enhance monitoring, debugging, and operational intelligence in distributed systems." category: Integration language: en tag: - - Data processing - - Decoupling - - Enterprise patterns - - Fault tolerance - - Messaging - - Microservices - - Performance - - Scalability + - Data processing + - Decoupling + - Enterprise patterns + - Fault tolerance + - Messaging + - Microservices + - Performance + - Scalability --- ## Also known as @@ -18,15 +20,15 @@ tag: * Centralized Logging * Log Management -## Intent +## Intent of Microservices Log Aggregation Design Pattern -Log Aggregation is a pattern that centralizes the collection, storage, and analysis of logs from multiple sources to facilitate monitoring, debugging, and operational intelligence. +Log Aggregation is a crucial microservices design pattern that centralizes the collection, storage, and analysis of logs from multiple sources, facilitating efficient monitoring, debugging, and operational intelligence. -## Explanation +## Detailed Explanation of Microservices Log Aggregation Pattern with Real-World Examples Real-world example -> Consider an e-commerce platform that operates using a microservices architecture. Each service, such as user authentication, product catalog, order processing, and payment, generates its own logs. To effectively monitor and analyze the entire platform's activity, a log aggregation system is implemented. This system collects logs from each microservice and centralizes them into a single location using tools like the ELK Stack (Elasticsearch, Logstash, Kibana). This allows the platform administrators to have a unified view of all logs, enabling real-time monitoring, quick troubleshooting, and comprehensive analysis of user behavior and system performance. +> Imagine an e-commerce platform using a microservices architecture, where each service generates logs. A log aggregation system, utilizing tools like the ELK Stack (Elasticsearch, Logstash, Kibana), centralizes these logs. This setup allows administrators to effectively monitor and analyze the entire platform's activity in real-time. By collecting logs from each microservice and centralizing them, the system provides a unified view, enabling quick troubleshooting and comprehensive analysis of user behavior and system performance. In plain words @@ -36,7 +38,7 @@ Wikipedia says > You have applied the Microservice architecture pattern. The application consists of multiple services and service instances that are running on multiple machines. Requests often span multiple service instances. Each service instance generates writes information about what it is doing to a log file in a standardized format. The log file contains errors, warnings, information and debug messages. -**Programmatic example** +## Programmatic Example of Microservices Log Aggregation Pattern in Java Log Aggregation is a pattern that centralizes the collection, storage, and analysis of logs from multiple sources to facilitate monitoring, debugging, and operational intelligence. It is particularly useful in distributed systems where logs from various components need to be centralized for better management and analysis. @@ -123,22 +125,22 @@ public class App { In this example, the `LogProducer` services generate logs of different levels. The `LogAggregator` collects these logs and stores them in the `CentralLogStore` if they meet the minimum log level requirement. Finally, the logs are displayed by the `CentralLogStore`. -## Applicability +## When to Use the Microservices Log Aggregation Pattern in Java -* Useful in distributed systems where logs from various components need to be centralized for better management and analysis. +* Microservices log aggregation is essential in distributed systems for better management and analysis of log data. * Applicable in environments where compliance and auditing require consolidated log data. * Beneficial in systems that require high availability and resilience, ensuring that log data is preserved and accessible despite individual component failures. -## Known Uses +## Real-World Applications of Microservices Log Aggregation Pattern in Java -* Java applications using frameworks like Log4j2 or SLF4J paired with centralized log management tools like Elasticsearch, Logstash, and Kibana (ELK stack) or Splunk. +* ava applications using frameworks like Log4j2 or SLF4J with centralized log management tools such as the ELK stack or Splunk benefit from microservices log aggregation. * Microservices architectures where each service outputs logs that are aggregated into a single system to provide a unified view of the system’s health and behavior. -## Consequences +## Benefits and Trade-offs of Microservices Log Aggregation Pattern Benefits: -* Improves debuggability and traceability of issues across multiple services or components. +* Centralizing logs in a microservices environment improves debuggability and traceability across multiple services. * Enhances monitoring capabilities by providing a centralized platform for log analysis. * Facilitates compliance with regulatory requirements for log retention and auditability. @@ -147,13 +149,13 @@ Trade-offs: * Introduces a potential single point of failure if the log aggregation system is not adequately resilient. * Can lead to high data volumes requiring significant storage and processing resources. -## Related Patterns +## Related Java Design Patterns * Messaging Patterns: Log Aggregation often utilizes messaging systems to transport log data, facilitating decoupling and asynchronous data processing. * Microservices: Often employed in microservice architectures to handle logs from various services efficiently. * Publish/Subscribe: Utilizes a pub/sub model for log data collection where components publish logs and the aggregation system subscribes to them. -## Credits +## References and Credits * [Cloud Native Java: Designing Resilient Systems with Spring Boot, Spring Cloud, and Cloud Foundry](https://amzn.to/44vDTat) * [Logging in Action: With Fluentd, Kubernetes and more](https://amzn.to/3JQLzdT) diff --git a/model-view-controller/README.md b/model-view-controller/README.md index dd6cd255f..42ef81fc1 100644 --- a/model-view-controller/README.md +++ b/model-view-controller/README.md @@ -1,28 +1,30 @@ --- -title: Model-View-Controller +title: "Model-View-Controller Pattern in Java: Streamlining Java Web Development" +shortTitle: Model-View-Controller (MVC) +description: "Learn about the Model-View-Controller (MVC) design pattern in Java, including its benefits, real-world examples, use cases, and how to implement it effectively in your applications." category: Architectural language: en tag: - - Architecture - - Client-server - - Decoupling - - Layered architecture - - Presentation + - Architecture + - Client-server + - Decoupling + - Layered architecture + - Presentation --- ## Also known as * MVC -## Intent +## Intent of Model-View-Controller Design Pattern -To separate an application into three interconnected components (Model, View, Controller), enabling modular development of each part independently, which enhances maintainability and scalability. +To separate an application into three interconnected components (Model, View, Controller), enabling modular development of each part independently, enhancing maintainability and scalability. Model-View-Controller (MVC) design pattern is widely used in Java applications for web development and user interface separation. -## Explanation +## Detailed Explanation of Model-View-Controller Pattern with Real-World Examples Real-world example -> Consider ICU room in hospital which displays the patients health information on device displays which are taking input from sensors connected to patient. Here, display's job is to display the data that it receives from the controller which in turn gets update from sensor model. +> Consider ICU room in a hospital displaying patient health information on devices taking input from sensors. The display shows data received from the controller, which updates from the sensor model. This exemplifies the MVC design pattern in a real-world Java application. In plain words @@ -32,7 +34,7 @@ Wikipedia says > Model–view–controller (MVC) is commonly used for developing user interfaces that divide the related program logic into three interconnected elements. This is done to separate internal representations of information from the ways information is presented to and accepted from the user. -**Programmatic Example** +## Programmatic Example of Model-View-Controller Pattern in Java Consider following `GiantModel` model class that provides the health, fatigue & nourishment information. @@ -112,22 +114,24 @@ public class GiantController { } ``` -## Applicability +This example demonstrates how the MVC pattern separates concerns in a Java application, making it easier to manage and update components independently. + +## When to Use the Model-View-Controller Pattern in Java * Used in web applications to separate data model, user interface, and user input processing. -* Suitable for applications where a clear separation of concerns is required, ensuring that the business logic, user interface, and user input are loosely coupled and independently managed. +* Suitable for applications requiring a clear separation of concerns, ensuring that the business logic, user interface, and user input are loosely coupled and independently managed, following the MVC pattern. -## Tutorials +## Model-View-Controller Pattern Java Tutorials * [Spring Boot Model (ZetCode)](https://zetcode.com/springboot/model/) * [Spring MVC Tutorial (Baeldung)](https://www.baeldung.com/spring-mvc-tutorial) -## Known Uses +## Real-World Applications of Model-View-Controller Pattern in Java * Frameworks like Spring MVC in Java for web applications. * Desktop applications in Java, such as those using Swing or JavaFX. -## Consequences +## Benefits and Trade-offs of Model-View-Controller Pattern Benefits: @@ -141,13 +145,13 @@ Trade-offs: * Increased complexity in initially setting up the architecture. * Can lead to excessive boilerplate if not implemented correctly or for very small projects. -## Related Patterns +## Related Java Design Patterns * [Observer](https://java-design-patterns.com/patterns/observer/): Often used in MVC where the view observes the model for changes; this is a fundamental relationship for updating the UI when the model state changes. -* [Strategy](https://java-design-patterns.com/patterns/strategy/): Controllers may use different strategies for handling user input, related through the ability to switch strategies for user input processing. +* [Strategy](https://java-design-patterns.com/patterns/strategy/): Controllers may use different strategies for handling user input, related through the ability to switch strategies for user input processing in Java MVC applications. * [Composite](https://java-design-patterns.com/patterns/composite/): Views can be structured using the Composite Pattern to manage hierarchies of user interface components. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) diff --git a/model-view-intent/README.md b/model-view-intent/README.md index 20bca3413..659bf1b95 100644 --- a/model-view-intent/README.md +++ b/model-view-intent/README.md @@ -1,28 +1,30 @@ --- -title: Model-View-Intent +title: "Model-View-Intent Pattern in Java: Building Robust and Scalable Java UIs with MVI" +shortTitle: Model-View-Intent (MVI) +description: "Discover the Model-View-Intent (MVI) pattern for Java applications. Learn how MVI enhances UI predictability, maintainability, and state management through unidirectional data flow. Explore real-world examples and implementation details." category: Architectural language: en tags: - - Abstraction - - Decoupling - - Presentation - - Reactive - - State tracking + - Abstraction + - Decoupling + - Presentation + - Reactive + - State tracking --- ## Also known as * MVI -## Intent +## Intent of Model-View-Intent Design Pattern -To create a unidirectional and cyclical data flow between the Model, View, and Intent components, enhancing predictability and maintainability in user interface logic. +The Model-View-Intent (MVI) pattern for Java applications creates a unidirectional and cyclical data flow between the Model, View, and Intent components, enhancing UI predictability and state management. -## Explanation +## Detailed Explanation of Model-View-Intent Pattern with Real-World Examples Real-world example -> Consider a real-world analogy of the Model-View-Intent (MVI) pattern using the scenario of ordering at a fast-food restaurant. +> Consider a real-world analogy of the Model-View-Intent (MVI) pattern in Java using the scenario of ordering at a fast-food restaurant to understand its application in enhancing UI state management. > > In this analogy: > - **Model:** It's like the kitchen of the restaurant, where the current state of your order is managed. As you choose items, the kitchen updates the order status and ingredients used. @@ -35,9 +37,9 @@ In plain words > The Model-View-Intent (MVI) pattern is a reactive architectural approach where user actions (Intent) modify the application state (Model), and the updated state is then reflected back in the user interface (View) in a unidirectional and cyclical data flow. -**Programmatic Example** +## Programmatic Example of Model-View-Intent Pattern in Java -The Model-View-Intent (MVI) pattern is a modern approach to structuring your application's logic. It's a variation of the Model-View-Presenter (MVP) and Model-View-ViewModel (MVVM) patterns, but with a more streamlined flow of data and events. +The Model-View-Intent (MVI) pattern for Java is a modern approach to structuring your application's logic, ensuring a smooth, unidirectional flow of data and events. It's a variation of the Model-View-Presenter (MVP) and Model-View-ViewModel (MVVM) patterns, but with a more streamlined flow of data and events. In MVI, the View sends user events to the Intent. The Intent translates these events into a state change in the Model. The Model then pushes this new state to the View, which updates itself accordingly. This creates a unidirectional data flow, which can make your code easier to understand and debug. @@ -182,22 +184,22 @@ public class SetVariableEvent implements UserEvent { This example demonstrates the key aspects of the MVI pattern: unidirectional data flow, clear separation of concerns, and the use of events to drive changes in the Model's state. -## Applicability +## When to Use the Model-View-Intent Pattern in Java -* Useful in applications with complex user interfaces that require a clear separation of concerns and predictable state management. +* The MVI pattern is useful in Java applications with complex user interfaces that require a clear separation of concerns, predictable state management, and enhanced maintainability. * Often applied in reactive programming environments to ensure a smooth data flow and state consistency. -## Tutorials +## Model-View-Intent Pattern Java Tutorials * [Model View Intent: a new Android Architecture Pattern (Apium Academy)](https://apiumacademy.com/blog/model-view-intent-pattern/) * [MVI Architecture for Android Tutorial: Getting Started (Kodeco)](https://www.kodeco.com/817602-mvi-architecture-for-android-tutorial-getting-started) -## Known uses +## Real-World Applications of Model-View-Intent Pattern in Java * Widely adopted in reactive and event-driven Java applications, particularly those using frameworks like RxJava or Project Reactor. * Used in Android development, especially with libraries that support reactive programming such as RxJava and LiveData. -## Consequences +## Benefits and Trade-offs of Model-View-Intent Pattern Benefits: @@ -211,13 +213,13 @@ Trade-offs: * Requires familiarity with reactive programming paradigms. * Can lead to boilerplate code if not managed properly. -## Related patterns +## Related Java Design Patterns [Model-View-ViewModel (MVVM)](https://java-design-patterns.com/patterns/model-view-viewmodel/): Shares a similar goal of separating the view from the model but differs as MVI introduces a cyclical data flow. [Model-View-Controller (MVC)](https://java-design-patterns.com/patterns/model-view-controller/): MVI can be seen as an evolution of MVC, focusing more on reactive programming and unidirectional data flow. [Observer](https://java-design-patterns.com/patterns/observer/): Essential in MVI to observe changes in the Model and update the View accordingly. -## Credits +## References and Credits * [Functional and Reactive Domain Modeling](https://amzn.to/4adghJ8) * [Reactive Programming with RxJava: Creating Asynchronous, Event-Based Applications](https://amzn.to/4dxwawC) diff --git a/model-view-presenter/README.md b/model-view-presenter/README.md index 04e8c188b..f3bbbb01f 100644 --- a/model-view-presenter/README.md +++ b/model-view-presenter/README.md @@ -1,25 +1,27 @@ --- -title: Model-View-Presenter +title: "Model-View-Presenter Pattern in Java: Enhancing UI Logic Separation for Cleaner Code" +shortTitle: Model-View-Presenter (MVP) +description: "Discover the Model-View-Presenter (MVP) pattern in Java. Learn how it separates user interface, business logic, and data interaction to enhance testability and maintainability." category: Architectural language: en tag: - - Architecture - - Client-server - - Decoupling - - Enterprise patterns - - Interface - - Presentation + - Architecture + - Client-server + - Decoupling + - Enterprise patterns + - Interface + - Presentation --- ## Also known as * MVP -## Intent +## Intent of Model-View-Presenter Design Pattern MVP aims to separate the user interface (UI) logic from the business logic and model in a software application, enabling easier testing and maintenance. -## Explanation +## Detailed Explanation of Model-View-Presenter Pattern with Real-World Examples Real-world example @@ -35,13 +37,13 @@ Real-world example In plain words -> The Model-View-Presenter (MVP) pattern separates the user interface, business logic, and data interaction in an application, with the presenter mediating between the view and the model to facilitate clear communication and updates. +> The Model-View-Presenter (MVP) pattern separates the user interface, business logic, and data interaction in an application, with the presenter mediating between the view and the model to facilitate clear communication and updates. Java developers use MVP to improve application structure. Wikipedia says > Model–view–presenter (MVP) is a derivation of the model–view–controller (MVC) architectural pattern, and is used mostly for building user interfaces. In MVP, the presenter assumes the functionality of the "middle-man". In MVP, all presentation logic is pushed to the presenter. -**Programmatic example** +## Programmatic Example of Model-View-Presenter Pattern in Java The Model-View-Presenter (MVP) design pattern is a derivative of the well-known Model-View-Controller (MVC) pattern. It aims to separate the application's logic (Model), GUIs (View), and the way that the user's actions update the application's logic (Presenter). This separation of concerns makes the application easier to manage, extend, and test. @@ -133,16 +135,16 @@ public class App { In this setup, the `App` class creates instances of the Model, View, and Presenter. It then connects these instances, forming the MVP triad. The Presenter is given a reference to the View, and the Model is set on the Presenter. Finally, the Presenter is started, which in turn opens the View. -## Applicability +## When to Use the Model-View-Presenter Pattern in Java Use MVP in applications where a clear [separation of concerns](https://java-design-patterns.com/principles/#separation-of-concerns) is needed between the presentation layer and the underlying business logic. It's particularly useful in client-server applications and enterprise-level applications. -## Known Uses +## Real-World Applications of Model-View-Presenter Pattern in Java * Desktop applications like those built using Java Swing or JavaFX. * Web applications with complex user interfaces and business logic. -## Consequences +## Benefits and Trade-offs of Model-View-Presenter Pattern Benefits: @@ -155,12 +157,12 @@ Trade-offs: * Increases complexity with more classes and interfaces. * Requires careful design to avoid over-coupling between the presenter and the view. -## Related Patterns +## Related Java Design Patterns * [Model-View-Controller (MVC)](https://java-design-patterns.com/patterns/model-view-controller/): MVP is often considered a variant of MVC where the presenter takes over the controller's role in managing user input and updating the model. * [Model-View-ViewModel (MVVM)](https://java-design-patterns.com/patterns/model-view-viewmodel/): Similar to MVP but adapted for frameworks like WPF or frameworks that support data binding, making the view update automatically when the model changes. -## Credits +## References and Credits * [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) * [Pro JavaFX 8: A Definitive Guide to Building Desktop, Mobile, and Embedded Java Clients](https://amzn.to/4a8qcQ1) diff --git a/model-view-viewmodel/README.md b/model-view-viewmodel/README.md index 202df7414..335b4222a 100644 --- a/model-view-viewmodel/README.md +++ b/model-view-viewmodel/README.md @@ -1,24 +1,26 @@ --- -title: Model-View-ViewModel +title: "Model-View-ViewModel Pattern in Java: Separating UI and Logic for Cleaner Code" +shortTitle: Model-View-ViewModel +description: "Learn about the Model-View-ViewModel (MVVM) design pattern in Java. Discover its benefits, real-world applications, and how it improves UI and business logic separation for scalable and maintainable code." category: Architectural language: en tag: - - Architecture - - Data binding - - Decoupling - - Presentation - - Scalability + - Architecture + - Data binding + - Decoupling + - Presentation + - Scalability --- ## Also known as * MVVM -## Intent +## Intent of Model-View-ViewModel Design Pattern -The intent of MVVM is to provide a clear [separation of concerns](https://java-design-patterns.com/principles/#separation-of-concerns) between the UI logic, the presentation logic, and the business logic by dividing the application into three interconnected components: Model, View, and ViewModel. +The intent of the Model-View-ViewModel (MVVM) pattern in Java is to provide a clear [separation of concerns](https://java-design-patterns.com/principles/#separation-of-concerns) between the UI logic, the presentation logic, and the business logic by dividing the application into three interconnected components: Model, View, and ViewModel. -## Explanation +## Detailed Explanation of Model-View-ViewModel Pattern with Real-World Examples Real-world example @@ -34,14 +36,13 @@ Real-world example In plain words -> The Model-View-ViewModel (MVVM) design pattern separates an application into three distinct components: the Model, which holds the data and business logic; the View, which displays the user interface; and the ViewModel, which acts as an intermediary to bind data from the Model to the View, facilitating a clear separation of concerns and easier maintenance and testing of user interfaces. +> The MVVM design pattern separates an application into three distinct components: the Model, which holds the data and business logic; the View, which displays the user interface; and the ViewModel, which acts as an intermediary to bind data from the Model to the View. Wikipedia says > Model–view–viewmodel (MVVM) is a software architectural pattern that facilitates the separation of the development of the graphical user interface (the view) – be it via a markup language or GUI code – from the development of the business logic or back-end logic (the model) so that the view is not dependent on any specific model platform. -**Programmatic Example** - +## Programmatic Example of Model-View-ViewModel Pattern in Java ViewModel will hold the business logic and expose the data from model to View. @@ -122,24 +123,24 @@ To deploy the example, go to model-view-viewmodel folder and run: * `mvn jetty:run -Djetty.http.port=9911` * Open browser to address: http://localhost:9911/model-view-viewmodel/ -## Applicability +## When to Use the Model-View-ViewModel Pattern in Java -* MVVM is applicable in applications requiring a clear separation between the user interface and the underlying business logic, especially in large-scale, data-driven applications where UI and business logic change independently. +MVVM is applicable in applications requiring a clear separation between the user interface and the underlying business logic, especially in large-scale, data-driven applications where UI and business logic change independently. This makes the Model-View-ViewModel pattern ideal for Java applications. -## Tutorials +## Model-View-ViewModel Pattern Java Tutorials * [Data Binding in Android (developer.android.com)](https://developer.android.com/codelabs/android-databinding#0) * [Introduction to Model View View Model (MVVM) (GeeksforGeeks)](https://www.geeksforgeeks.org/introduction-to-model-view-view-model-mvvm/) * [Patterns - WPF Apps With The Model-View-ViewModel Design Pattern (Microsoft)](https://docs.microsoft.com/en-us/archive/msdn-magazine/2009/february/patterns-wpf-apps-with-the-model-view-viewmodel-design-pattern) -## Known uses +## Real-World Applications of Model-View-ViewModel Pattern in Java * Widely used in JavaFX applications for desktop interfaces. * Utilized in Android development with libraries like DataBinding and LiveData for reactive UI updates. * ZK Framework [zkoss.org](https://www.zkoss.org/) * KnockoutJS [knockoutjs.com](https://knockoutjs.com/) -## Consequences +## Benefits and Trade-offs of Model-View-ViewModel Pattern Benefits: @@ -152,12 +153,12 @@ Trade-offs: * Increased complexity in small applications where simpler patterns might suffice. * Learning curve associated with understanding and applying the pattern correctly. -## Related Patterns +## Related Java Design Patterns * [MVC (Model-View-Controller)](https://java-design-patterns.com/patterns/model-view-controller/): MVVM can be seen as a derivative of MVC with a stronger emphasis on binding and decoupling, where the ViewModel acts as an intermediary unlike the controller in MVC. * [MVP (Model-View-Presenter)](https://java-design-patterns.com/patterns/model-view-presenter/): Similar to MVVM but with a focus on the presenter handling the UI logic, making MVVM's ViewModel more passive in terms of direct UI manipulation. -## Credits +## References and Credits * [Android Programming: The Big Nerd Ranch Guide](https://amzn.to/3wBGG5o) * [Pro JavaFX 8: A Definitive Guide to Building Desktop, Mobile, and Embedded Java Clients](https://amzn.to/4a8qcQ1) diff --git a/monad/README.md b/monad/README.md index 40eaee428..e63d830a7 100644 --- a/monad/README.md +++ b/monad/README.md @@ -1,19 +1,21 @@ --- -title: Monad +title: "Monad Pattern in Java: Mastering Functional Programming Paradigms" +shortTitle: Monad +description: "Learn how to implement the Monad design pattern in Java for functional programming. Discover its benefits, real-world examples, and best practices to enhance code readability and error handling." category: Functional language: en tag: - - Abstraction - - Accumulation - - Decoupling - - Encapsulation - - Functional decomposition - - Generic - - Idiom - - Instantiation - - Interface - - Layered architecture - - Object composition + - Abstraction + - Accumulation + - Decoupling + - Encapsulation + - Functional decomposition + - Generic + - Idiom + - Instantiation + - Interface + - Layered architecture + - Object composition --- ## Also known as @@ -21,15 +23,15 @@ tag: * Computation Wrapper * Monadic Interface -## Intent +## Intent of Monad Design Pattern -To provide a mechanism for encapsulating computations or side effects, enabling the chaining of operations while managing context and data flow in a side-effect-free manner. +The Monad design pattern in Java provides a mechanism for encapsulating computations or side effects, enabling the chaining of operations while managing context and data flow in a side-effect-free manner. -## Explanation +## Detailed Explanation of Monad Pattern with Real-World Examples Real-world example -> Consider a real-world analogous example of a monad with a restaurant meal ordering process. In this scenario, each step of selecting a dish, adding sides, and choosing a drink can be thought of as a monadic operation. Each operation encapsulates the current state of the order (e.g., main dish chosen) and allows for the next choice (e.g., selecting a side) without exposing the complexity of the entire order's details to the customer. +> Consider a real-world example of a monad in Java with a restaurant meal ordering process. This encapsulation and chaining allow for a clean, error-managed progression, similar to how monads handle data and operations in functional programming. In this scenario, each step of selecting a dish, adding sides, and choosing a drink can be thought of as a monadic operation. Each operation encapsulates the current state of the order (e.g., main dish chosen) and allows for the next choice (e.g., selecting a side) without exposing the complexity of the entire order's details to the customer. > > Just like in a functional monad, if any step fails (like an unavailable dish), the entire process can be halted or redirected without throwing exceptions, maintaining a smooth flow. This encapsulation and chaining allow for a clean, error-managed progression from choosing the main dish to completing the full meal order, akin to how monads handle data and operations in functional programming. This approach ensures a consistent experience, where every choice builds on the previous one in a controlled manner. @@ -41,11 +43,9 @@ Wikipedia says > In functional programming, a monad is a structure that combines program fragments (functions) and wraps their return values in a type with additional computation. In addition to defining a wrapping monadic type, monads define two operators: one to wrap a value in the monad type, and another to compose together functions that output values of the monad type (these are known as monadic functions). General-purpose languages use monads to reduce boilerplate code needed for common operations (such as dealing with undefined values or fallible functions, or encapsulating bookkeeping code). Functional languages use monads to turn complicated sequences of functions into succinct pipelines that abstract away control flow, and side effects. -**Programmatic Example** +## Programmatic Example of Monad Pattern in Java -Here’s the Monad implementation in Java. - -The `Validator` takes an object, validates it against specified predicates, and collects any validation errors. The `validate` method allows you to add validation steps, and the `get` method either returns the validated object or throws an `IllegalStateException` with a list of validation exceptions if any of the validation steps fail. +Here’s the Monad implementation in Java. The `Validator` class encapsulates an object and performs validation steps in a monadic fashion, showcasing the benefits of using the Monad pattern for error handling and state management. ```java public class Validator { @@ -119,24 +119,26 @@ Console output: 15:06:17.679 [main] INFO com.iluwatar.monad.App -- User[name=user, age=24, sex=FEMALE, email=foobar.com] ``` -## Applicability +## When to Use the Monad Pattern in Java -* Consistent and unified error handling is required without relying on exceptions. +The Monad design pattern is applicable when + +* Consistent and unified error handling is required without relying on exceptions, particularly in functional programming paradigms. * Asynchronous computations need clear and maintainable chaining. * State needs to be managed and encapsulated within functional flows. * Dependencies and lazy evaluations are to be handled cleanly and efficiently. -## Tutorials +## Monad Pattern Java Tutorials * [Design Pattern Reloaded (Remi Forax)](https://youtu.be/-k2X7guaArU) -## Known Uses +## Real-World Applications of Monad Pattern in Java * Optional in Java's standard library for handling potential absence of values. * Stream for constructing functional pipelines to operate on collections. -* Frameworks like Vavr, providing functional programming enhancements for Java. +* Frameworks like Vavr enhance functional programming in Java by providing monadic constructs for better code maintainability. -## Consequences +## Benefits and Trade-offs of Monad Pattern Benefits: @@ -151,13 +153,15 @@ Trade-offs: * May introduce performance overhead due to additional abstraction layers. * Debugging can be difficult due to less transparent operational flow. -## Related Patterns +## Related Java Design Patterns + +Related design patterns to monads in Java include * [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Similar in that it helps instantiate monads, encapsulating object creation logic. * [Command](https://java-design-patterns.com/patterns/command/): Also encapsulates operations, but monads add context management to the mix. * [Decorator](https://java-design-patterns.com/patterns/decorator/): Dynamically enhances functionalities, whereas monads use static typing for consistent composability. -## Credits +## References and Credits * [Functional Programming in Java](https://amzn.to/3JUIc5Q) * [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://amzn.to/3QCmGXs) diff --git a/monitor/README.md b/monitor/README.md index 3041e611b..46d5b6867 100644 --- a/monitor/README.md +++ b/monitor/README.md @@ -1,24 +1,26 @@ --- -title: Monitor +title: "Monitor Pattern in Java: Implementing Robust Locking Mechanisms with Monitors" +shortTitle: Monitor +description: "Learn how the Monitor design pattern in Java ensures thread safety and synchronization. Explore examples, applicability, and benefits of using monitors in concurrent programming." category: Concurrency language: en tag: - - Encapsulation - - Fault tolerance - - Isolation - - Synchronization - - Thread management + - Encapsulation + - Fault tolerance + - Isolation + - Synchronization + - Thread management --- ## Also known as * Synchronized Block -## Intent +## Intent of Monitor Design Pattern -The Monitor design pattern is used to synchronize concurrent operations by encapsulating shared resources in such a way that only one thread can access them at a time, ensuring thread safety. +The Monitor design pattern in Java is essential for synchronizing concurrent operations, ensuring thread safety and preventing race conditions. -## Explanation +## Detailed Explanation of Monitor Pattern with Real-World Examples Real-world example @@ -34,11 +36,11 @@ Wikipedia says > In concurrent programming (also known as parallel programming), a monitor is a synchronization construct that allows threads to have both mutual exclusion and the ability to wait (block) for a certain condition to become false. Monitors also have a mechanism for signaling other threads that their condition has been met. -**Programmatic Examples** +## Programmatic Example of Monitor Pattern in Java The Monitor design pattern is a synchronization technique used in concurrent programming to ensure that only one thread can execute a particular section of code at a time. It is a method of wrapping and hiding the synchronization primitives (like semaphores or locks) within the methods of an object. This pattern is useful in situations where race conditions could occur. -In the provided code, the `Bank` class is an example of the Monitor pattern. The `Bank` class has several methods that are marked as `synchronized`. This means that only one thread can execute these methods at a time, ensuring that the bank's state remains consistent even when accessed from multiple threads. +The Java Monitor design pattern can be seen in the `Bank` class example. By using synchronized methods, the `Bank` class ensures that only one thread can perform transactions at any given time, illustrating effective use of the Monitor pattern in real-world applications. Here is a simplified version of the `Bank` class with additional comments: @@ -115,7 +117,7 @@ public class Main { In this example, the `Bank` class is the monitor, and the `transfer` method is the critical section that needs to be executed in a mutually exclusive manner. The `synchronized` keyword in Java is used to implement the Monitor pattern, ensuring that only one thread can execute the `transfer` method at a time. -## Applicability +## When to Use the Monitor Pattern in Java The Monitor design pattern should be used in situations where you have shared resources that need to be accessed and manipulated by multiple threads or processes concurrently. This pattern is particularly useful in scenarios where synchronization is necessary to prevent race conditions, data corruption, and inconsistent states. Here are some situations where you should consider using the Monitor pattern: @@ -139,12 +141,11 @@ However, it's important to note that the Monitor pattern might not be the best f Before applying the Monitor pattern, it's recommended to thoroughly analyze your application's concurrency requirements and choose the synchronization approach that best suits your needs, taking into consideration factors like performance, complexity, and available language features. -## Known Uses +## Real-World Applications of Monitor Pattern in Java -* Java's synchronized methods and blocks. -* Implementations of concurrent data structures like Vector and Hashtable in the Java Collections Framework. +Common implementations of the Monitor design pattern in Java include synchronized methods and blocks, as well as concurrent data structures like `Vector` and `Hashtable`. -## Consequences +## Benefits and Trade-offs of Monitor Pattern Benefits: @@ -156,12 +157,12 @@ Trade-offs: * Can lead to decreased performance due to locking overhead. * Potential for deadlocks if not carefully designed. -## Related Patterns +## Related Java Design Patterns Semaphore: Used to control access to a common resource by multiple threads; Monitor uses a binary semaphore concept at its core. Mutex: Another mechanism for ensuring mutual exclusion; Monitor is a higher-level construct often implemented using mutexes. -## Credits +## References and Credits * [Concurrency: State Models & Java Programs](https://amzn.to/4dxxjUX) * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) diff --git a/monostate/README.md b/monostate/README.md index 2e1d28f07..33a603502 100644 --- a/monostate/README.md +++ b/monostate/README.md @@ -1,28 +1,30 @@ --- -title: Monostate +title: "Monostate Pattern in Java: Achieving Singleton Behavior with Class-Level State" +shortTitle: Monostate +description: "Learn how the Monostate design pattern works in Java. Discover its benefits, implementation details, and use cases. Perfect for ensuring shared state across multiple class instances." category: Creational language: en tag: - - Encapsulation - - Instantiation - - Object composition - - Persistence - - Polymorphism + - Encapsulation + - Instantiation + - Object composition + - Persistence + - Polymorphism --- ## Also known as * Borg -## Intent +## Intent of Monostate Design Pattern -Monostate is an alternative approach to achieving a singleton-like behavior in object-oriented design. It enforces a unique behavior where all instances of a class share the same state. Unlike the Singleton pattern, which restricts a class to a single instance, Monostate allows for multiple instances but ensures they all have a shared state. +The Monostate pattern is an alternative approach to achieving a singleton-like behavior in object-oriented design, ensuring a shared state in Java applications. It enforces a unique behavior where all instances of a class share the same state. Unlike the Singleton pattern, which restricts a class to a single instance, Monostate allows for multiple instances but ensures they all have a shared state. -## Explanation +## Detailed Explanation of Monostate Pattern with Real-World Examples Real-word example -> Imagine a library with multiple desks where patrons can access the library's catalog. While each desk appears to be independent, any changes made to the catalog (like adding or removing a book) are immediately reflected at all desks. This setup ensures that no matter which desk a patron uses, they see the exact same, up-to-date catalog. This is analogous to the Monostate pattern, where multiple instances of a class share the same state, ensuring consistent data across all instances. +> Imagine a library with multiple desks where patrons can access the library's catalog. While each desk appears to be independent, any changes made to the catalog (like adding or removing a book) are immediately reflected at all desks. This setup ensures that no matter which desk a patron uses, they see the exact same, up-to-date catalog, similar to how the Monostate pattern maintains a shared state across all instances in Java. This is analogous to the Monostate pattern, where multiple instances of a class share the same state, ensuring consistent data across all instances. In plain words @@ -32,9 +34,9 @@ wiki.c2.com says > A monostate is a "conceptual singleton" - all data members of a monostate are static, so all instances of the monostate use the same (static) data. Applications using a monostate can create any number of instances that they desire, as each instance uses the same data. -**Programmatic Examples** +## Programmatic Example of Monostate Pattern in Java -The Monostate pattern is a way to ensure that all instances of a class share the same state. This is achieved by using static fields in the class. Any changes to these fields will be reflected across all instances of the class. This pattern is useful when you want to avoid global variables but still need a shared state across multiple instances. +The Monostate pattern in Java ensures that all instances of a class share the same state, making it a great Singleton alternative for maintaining consistent data. This is achieved by using static fields in the class. Any changes to these fields will be reflected across all instances of the class. This pattern is useful when you want to avoid global variables but still need a shared state across multiple instances. Let's take a look at the `LoadBalancer` class from the `monostate` module: @@ -77,11 +79,11 @@ public class App { In this example, we create two instances of `LoadBalancer`: `loadBalancer1` and `loadBalancer2`. They share the same state. When we make a request via `loadBalancer1`, the request is served by the first server. When we make a request via `loadBalancer2`, the request is served by the second server, not the first one, because the `nextServerIndex` has been updated by `loadBalancer1`. This demonstrates the Monostate pattern in action. -## Applicability +## When to Use the Monostate Pattern in Java -Use the Monostate pattern when +Use the Monostate pattern in Java design patterns when -1. **Shared State Across Instances:** All instances of a class must share the same state. Changes in one instance should be reflected across all instances. +1. **Shared State Across Instances:** All instances of a class must share the same state. Changes in one instance should be reflected across all instances. Monostate offers more flexibility compared to the traditional Singleton pattern. 2. **Transparent Usage:** Unlike Singleton, which can be less transparent in its usage, Monostate allows for a more transparent way of sharing state across instances. Clients interact with instances of the Monostate class as if they were regular instances, unaware of the shared state. @@ -93,12 +95,12 @@ Use the Monostate pattern when 6. **Consistent Configuration or State Management:** In scenarios where you need consistent configuration management or state management across different parts of an application, Monostate provides a pattern to ensure all parts of the system are in sync. -## Known uses +## Real-World Applications of Monostate Pattern in Java * Configuration settings that need to be shared and accessible by various parts of an application. * Resource pools where the state needs to be consistent across different consumers. -## Consequences +## Benefits and Trade-offs of Monostate Pattern Benefits: @@ -110,12 +112,12 @@ Trade-offs: * Can lead to hidden dependencies due to shared state, making the system harder to understand and debug. * Reduces the flexibility to have instances with independent states. -## Related Patterns +## Related Java Design Patterns -* [Singleton](https://java-design-patterns.com/patterns/singleton/): Both Singleton and Monostate ensure a single shared state, but Singleton does so by restricting instance creation. +* [Singleton](https://java-design-patterns.com/patterns/singleton/): Both Singleton and Monostate patterns ensure a single shared state, but the Monostate pattern in Java allows for multiple instances with the same state, making it a unique object-oriented design approach. * [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Flyweight shares state to reduce memory usage, similar to how Monostate shares state among instances. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/multiton/README.md b/multiton/README.md index f3818bd0d..34e37866a 100644 --- a/multiton/README.md +++ b/multiton/README.md @@ -1,22 +1,24 @@ --- -title: Multiton +title: "Multiton Pattern in Java: Mastering Advanced Singleton Variants" +shortTitle: Multiton +description: "Learn how the Multiton pattern in Java ensures unique named instances and provides a global access point. Discover implementation tips and code examples." category: Creational language: en tag: - - Decoupling - - Instantiation - - Object composition + - Decoupling + - Instantiation + - Object composition --- ## Also known as * Registry of Singletons -## Intent +## Intent of Multiton Design Pattern -The Multiton pattern is a variation of the Singleton design pattern that manages a map of named instances as key-value pairs. +The Multiton pattern in Java ensures a class has only unique named instances, providing a global point of access to them. Each named instance is accessed through a unique key, making it an essential part of Java design patterns. -## Explanation +## Detailed Explanation of Multiton Pattern with Real-World Examples Real-world example @@ -24,13 +26,15 @@ Real-world example In plain words -> Multiton pattern ensures there are a predefined amount of instances available globally. +> The Multiton pattern is an extension of the Singleton pattern, offering a way to have a map of unique named instances instead of a single instance. This makes it a valuable Java design pattern for managing named instances efficiently. Wikipedia says > In software engineering, the multiton pattern is a design pattern which generalizes the singleton pattern. Whereas the singleton allows only one instance of a class to be created, the multiton pattern allows for the controlled creation of multiple instances, which it manages through the use of a map. -**Programmatic Example** +## Programmatic Example of Multiton Pattern in Java + +In this tutorial, we’ll explore how to implement the Multiton pattern in Java, covering its structure, benefits, and providing code examples. By following these implementation tips, you’ll be able to effectively utilize this Java design pattern. The Nazgûl, also called ringwraiths or the Nine Riders, are Sauron's most terrible servants. By definition, there's always nine of them. @@ -127,20 +131,20 @@ Program output: 15:16:10.601 [main] INFO com.iluwatar.multiton.App -- UVATHA=UVATHA ``` -## Applicability +## When to Use the Multiton Pattern in Java -Use the Multiton pattern when +Use cases for the Multiton pattern in Java * A class must have named instances, but only one instance for each unique key. * Global access to these instances is necessary without requiring global variables. * You want to manage shared resources categorized by key. -## Known Uses +## Real-World Applications of Multiton Pattern in Java * Managing database connections in different contexts. * Configuration settings for different environments in an application. -## Consequences +## Benefits and Trade-offs of Multiton Pattern Benefits: @@ -152,11 +156,11 @@ Trade-offs: * Increased memory usage if not managed properly due to multiple instances. * Potential issues with concurrency if not implemented with thread safety in mind. -## Related Patterns +## Related Java Design Patterns * [Singleton](https://java-design-patterns.com/patterns/singleton/): Multiton can be seen as an extension of the Singleton pattern where Singleton allows only one instance of a class, Multiton allows one instance per key. * [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Multiton uses a method to create or retrieve instances, similar to how a Factory Method controls object creation. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) diff --git a/mute-idiom/README.md b/mute-idiom/README.md index 0f58f9991..3999d7ab9 100644 --- a/mute-idiom/README.md +++ b/mute-idiom/README.md @@ -1,14 +1,16 @@ --- -title: Mute Idiom +title: "Mute Idiom Pattern in Java: Implementing Unobtrusive Exception Suppression" +shortTitle: Mute Idiom +description: "Discover the Mute Idiom design pattern in Java, which simplifies error handling by muting non-critical exceptions. Learn how to apply it effectively in multithreaded environments." category: Behavioral language: en tag: - - Context - - Decoupling - - Idiom - - Error handling - - Synchronization - - Thread management + - Context + - Decoupling + - Idiom + - Error handling + - Synchronization + - Thread management --- ## Also known as @@ -16,15 +18,15 @@ tag: * Exception Suppression * Quiet Exception -## Intent +## Intent of Mute Idiom Design Pattern -The Mute Idiom is designed to simplify error handling by muting exceptions that are deemed non-critical or expected in specific contexts, especially within multithreaded or complex control flow environments. +The Mute Idiom in Java is a design pattern that simplifies error handling by suppressing non-critical exceptions. This approach is especially useful in multithreaded applications and complex control flow scenarios. -## Explanation +## Detailed Explanation of Mute Idiom Pattern with Real-World Examples Real-world example -> An analogous real-world example of the Mute Idiom design pattern is found in car door locking mechanisms. +> A real-world analogy of the Mute Idiom is found in car door locking mechanisms, where non-critical exceptions (like an already locked door) are ignored, simplifying the system's logic. Similarly, in Java, the Mute Idiom focuses on essential operations, avoiding unnecessary exception handling. > > Imagine a car equipped with an automatic locking system that attempts to lock all doors when the car reaches a certain speed. In this system, if one of the doors is already locked, the system doesn't need to alert the driver or perform any special handling; it simply skips locking that door and continues with the others. The locking system "mutes" the handling of already locked doors, focusing only on those that need to be locked. This approach simplifies the logic and avoids unnecessary checks, similar to how the Mute Idiom in software development suppresses handling trivial exceptions. @@ -32,7 +34,9 @@ In plain words > The Mute Idiom design pattern suppresses the handling of trivial or non-critical exceptions to simplify code. -**Programmatic Example** +## Programmatic Example of Mute Idiom Pattern in Java + +In the following Java code example, we demonstrate the Mute Idiom by muting non-critical exceptions during the resource management process. This approach ensures error handling does not interrupt the main logic. The Mute Idiom is a design pattern that is used to simplify error handling by muting exceptions that are deemed non-critical or expected in specific contexts. This pattern is particularly useful in multithreaded or complex control flow environments. @@ -81,24 +85,28 @@ public class App { In this way, the Mute Idiom allows us to simplify error handling by reducing boilerplate code for expected exceptions, enhancing code readability and maintainability, and allowing uninterrupted execution for non-critical exceptions. -## Applicability +## When to Use the Mute Idiom Pattern in Java -* Useful in scenarios where certain exceptions are predictable and do not affect the overall logic or outcome. -* Commonly used in logging, cleanup operations, or when working with APIs that signal non-critical issues via exceptions. +The Mute Idiom is applicable in -## Tutorials +* Scenarios where certain exceptions are predictable and do not affect the overall logic or outcome. +* Commonly used in logging, cleanup operations, or interacting with third-party APIs in Java. + +## Mute Idiom Pattern Java Tutorials * [The Mute Design Pattern (JOOQ)](http://blog.jooq.org/2016/02/18/the-mute-design-pattern/) -## Known Uses +## Real-World Applications of Mute Idiom Pattern in Java * Muting exceptions in background tasks or threads where interruption is expected. * Handling known issues in third-party libraries where exceptions can be safely ignored. -## Consequences +## Benefits and Trade-offs of Mute Idiom Pattern Benefits: +Using the Mute Idiom + * Simplifies error handling by reducing boilerplate code for expected exceptions. * Enhances code readability and maintainability. * Allows uninterrupted execution for non-critical exceptions. @@ -108,12 +116,12 @@ Trade-offs: * Can lead to missed critical issues if overused or misapplied. * Makes debugging harder if exceptions are muted indiscriminately. -## Related Patterns +## Related Java Design Patterns * [Null Object](https://java-design-patterns.com/patterns/null-object/): Both aim to simplify error handling; Null Object avoids null checks while Mute Idiom avoids exception handling complexities. * [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used to wrap functionality with additional error handling or muting behaviors. -## Credits +## References and Credits * [Effective Java](https://amzn.to/4cGk2Jz) * [Java Concurrency in Practice](https://amzn.to/4aRMruW) diff --git a/naked-objects/README.md b/naked-objects/README.md index e9a9fe81a..b96db41cd 100644 --- a/naked-objects/README.md +++ b/naked-objects/README.md @@ -1,31 +1,33 @@ --- -title: Naked Objects +title: "Naked Objects Pattern in Java: Leveraging Domain Objects for Dynamic UI Generation" +shortTitle: Naked Objects +description: “Explore the Naked Objects design pattern in Java. Learn how to dynamically create user interfaces from domain objects with examples and best practices.” category: Architectural language: en tag: - - Architecture - - Business - - Decoupling - - Domain - - Enterprise patterns - - Instantiation - - Object composition - - Persistence + - Architecture + - Business + - Decoupling + - Domain + - Enterprise patterns + - Instantiation + - Object composition + - Persistence --- ## Also known as * Transparent Objects -## Intent +## Intent of Naked Objects Design Pattern -To enable the rapid development of maintainable systems by representing all business objects directly and automatically creating the user interface from these definitions. +To enable the rapid development of maintainable systems by representing all business objects directly and automatically creating the user interface from these definitions. Naked Objects design pattern is essential for developers aiming to align user interfaces with domain models seamlessly. -## Explanation +## Detailed Explanation of Naked Objects Pattern with Real-World Examples Real-world example -> Consider a real-world example where a company develops a customer relationship management (CRM) system using the Naked Objects design pattern. In this CRM system, each business object, such as "Customer," "Order," and "Product," is represented directly as an object in the system. The user interface is automatically generated based on these domain objects, allowing sales representatives to view and edit customer information, track orders, and manage inventory without needing a separately designed UI. +> In a Naked Objects design pattern, a company might develop a customer relationship management (CRM) system where each business object, such as "Customer," "Order," and "Product," is represented directly. This allows for a dynamic and adaptable UI reflecting the underlying domain model with minimal developer intervention. The user interface is automatically generated based on these domain objects, allowing sales representatives to view and edit customer information, track orders, and manage inventory without needing a separately designed UI. > > This approach ensures that any changes in the business logic or domain model are immediately reflected in the user interface, significantly reducing the development and maintenance time. For instance, if a new field, "Loyalty Points," is added to the "Customer" object to track rewards, this field automatically appears in the CRM's user interface without additional UI development. This keeps the system flexible and closely aligned with the evolving business needs. @@ -42,9 +44,9 @@ Wikipedia says > > The naked object pattern's innovative feature arises by combining the 1st and 2nd principles into a 3rd principle: 3. The user interface shall be entirely automatically created from the definitions of the domain objects. This may be done using reflection or source code generation. -**Programmatic example** +## Programmatic Example of Naked Objects Pattern in Java -In the context of the Naked Objects pattern, let's consider a simplified example with domain objects representing books and authors. The example demonstrates how the Naked Objects pattern can be applied to create a user interface for managing a library catalog. +Consider a simplified example with domain objects representing books and authors. In a Java-based application using the Naked Objects pattern, we define domain objects such as `Book` and `Author`. This example illustrates how Naked Objects can streamline user interface generation and domain object manipulation. Suppose we have the following domain objects in a Java-based application: @@ -97,17 +99,17 @@ var booksByAuthor = author.getBooks(); This example demonstrates how the Naked Objects pattern can be implemented in a Java-based application with domain objects for books and authors. Users can directly manipulate these domain objects through the generated user interface. -## Applicability +## When to Use the Naked Objects Pattern in Java * When aiming to create a system where the domain objects can be easily understood and manipulated without an explicit user interface design. * For applications requiring a dynamic, adaptable UI that reflects the underlying domain model with minimal developer intervention. -## Known uses +## Real-World Applications of Naked Objects Pattern in Java * Enterprise applications where business rules and domain logic are primary. * Systems that benefit from a dynamic and adaptive user interface. -## Consequences +## Benefits and Trade-offs of Naked Objects Pattern Benefits: @@ -122,12 +124,12 @@ Trade-offs: * Potential over-exposure of the domain model * Reliance on framework capabilities -## Related Patterns +## Related Java Design Patterns Active Record: Similar in exposing domain models directly, but Active Record typically involves persistence aspects as well. Domain-Driven Design: Shares the focus on domain modeling but without the automatic UI generation of Naked Objects. -## Credits +## References and Credits * [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3wlDrze) * [Naked Objects](https://amzn.to/3yhrfQr) diff --git a/notification/README.md b/notification/README.md index adb3b1784..e94421ff5 100644 --- a/notification/README.md +++ b/notification/README.md @@ -1,24 +1,26 @@ --- -title: Notification +title: "Notification Pattern in Java: Enhancing System Communication with Event Alerts" +shortTitle: Notification +description: "Learn how to implement the Notification design pattern in Java with detailed explanations, code examples, and use cases. Improve your design patterns knowledge and code quality." category: Behavioral language: en tags: - - Asynchronous - - Decoupling - - Event-driven - - Messaging - - Publish/subscribe + - Asynchronous + - Decoupling + - Event-driven + - Messaging + - Publish/subscribe --- ## Also known as * Event Listener -## Intent +## Intent of Notification Design Pattern -The Notification design pattern aims to facilitate communication between different parts of a system by allowing objects to subscribe to specific events and receive updates asynchronously when those events occur. +The Notification design pattern in Java aims to facilitate asynchronous communication between different parts of a system by allowing objects to subscribe to specific events and receive updates asynchronously when those events occur. -## Explanation +## Detailed Explanation of Notification Pattern with Real-World Examples Real-world example @@ -30,9 +32,9 @@ In plain words > The Notification design pattern enables an object to automatically notify a list of interested observers about changes or events without knowing the specifics of the subscribers. -**Programatic example** +## Programmatic Example of Notification Pattern in Java -The Notification pattern is used to capture information passed between layers, validate the information, and return any errors to the presentation layer if needed. It reduces coupling between the producer and consumer of events, enhances flexibility and reusability of components, and allows for dynamic subscription and unsubscription to events. +The Java Notification pattern is used to capture information passed between layers, validate the information, and return any errors to the presentation layer if needed. It reduces coupling between the producer and consumer of events, enhances flexibility and reusability of components, and allows for dynamic event subscription and unsubscription. In this example, we'll use a form submission scenario to demonstrate the Notification pattern. The form is used to register a worker with their name, occupation, and date of birth. The form data is passed to the domain layer for validation, and any errors are returned to the presentation layer. @@ -91,19 +93,19 @@ Example output: 18:10:00.080 [main] INFO com.iluwatar.RegisterWorkerForm - Not registered, see errors ``` -## Applicability +## When to Use the Notification Pattern in Java * When a change to one object requires changing others, and you don’t know how many objects need to be changed. * When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently. * When a system component must be notified of events without making assumptions about the system’s other components. -## Known uses +## Real-World Applications of Notification Pattern in Java * GUI frameworks where user actions trigger responses in the application. * Notification systems in large-scale distributed systems. * Event management in microservices architecture. -## Consequences +## Benefits and Trade-offs of Notification Pattern Benefits: @@ -116,13 +118,13 @@ Trade-offs: * Can lead to a complex system if not managed well, due to the dynamic nature of subscriptions. * Debugging can be challenging due to the asynchronous and decoupled nature of events. -## Related patterns +## Related Java Design Patterns * [Command](https://java-design-patterns.com/patterns/command/): Can be used to encapsulate a request as an object, often used in conjunction with notifications to decouple the sender and receiver. * [Mediator](https://java-design-patterns.com/patterns/mediator/): Facilitates centralized communication between objects, whereas the Notification pattern is more decentralized. * [Observer](https://java-design-patterns.com/patterns/observer/): A foundational pattern for the Notification pattern, focusing on one-to-many dependency relationships. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/3WcFVui) diff --git a/null-object/README.md b/null-object/README.md index 7dd31477f..75da7452a 100644 --- a/null-object/README.md +++ b/null-object/README.md @@ -1,11 +1,13 @@ --- -title: Null Object +title: "Null Object Pattern in Java: Streamlining Error Handling with Graceful Defaults" +shortTitle: Null Object +description: "Learn how the Null Object Pattern simplifies your Java code by handling null references effectively. Discover its implementation, advantages, and practical use cases." category: Behavioral language: en tag: - - Code simplification - - Decoupling - - Polymorphism + - Code simplification + - Decoupling + - Polymorphism --- ## Also known as @@ -13,11 +15,11 @@ tag: * Active Nothing * Stub -## Intent +## Intent of Null Object Design Pattern -To provide a default behavior for an object, avoiding the need for null checks and enhancing code readability. +The Null Object Pattern is an essential Java design pattern that provides a seamless way to handle absent objects without performing null checks, streamlining your Java applications. -## Explanation +## Detailed Explanation of Null Object Pattern with Real-World Examples Real-world example @@ -33,7 +35,9 @@ Wikipedia says > In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral ("null") behavior. The null object design pattern describes the uses of such objects and their behavior (or lack thereof). -**Programmatic Example** +## Programmatic Example of Null Object in Java + +By implementing the Null Object Pattern, Java developers can ensure that their applications handle 'empty' objects more gracefully, enhancing code stability and readability. We are building a binary tree from nodes. There are ordinary nodes and "empty" nodes. Traversing the tree normally should not cause errors, so we use null object pattern where necessary. @@ -158,19 +162,19 @@ Program output: 122 ``` -## Applicability +## When to Use the Null Object Pattern in Java * When you need to provide a default behavior in place of a null object. * To simplify the client code by eliminating null checks. * When a default action is preferable to handling a null reference. -## Known Uses +## Real-World Applications of Null Object Pattern in Java -* Logging systems where a NullLogger can be used to avoid null checks. +* Commonly used in logging systems, the Null object helps prevent NullPointerExceptions, making it a critical pattern for reliable Java software development. * Collections that use a NullIterator to handle empty collections gracefully. * GUI systems where a NullComponent can be used to represent a component that does nothing. -## Consequences +## Benefits and Trade-offs of Null Object Pattern Benefits: @@ -183,13 +187,13 @@ Trade-offs: * May introduce additional classes, potentially increasing the overall complexity of the system. * The default behavior might mask potential issues that would otherwise be caught by explicit null handling. -## Related Patterns +## Related Java Design Patterns * [Strategy](https://java-design-patterns.com/patterns/strategy/): Null Object can be seen as a special case of the Strategy Pattern where the strategy is to do nothing. * [State](https://java-design-patterns.com/patterns/state/): Similar in that both patterns can handle different states or behaviors; Null Object is like a state that does nothing. * [Factory](https://java-design-patterns.com/patterns/factory/): Often used to provide Null Objects in place of actual objects. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/object-mother/README.md b/object-mother/README.md index 91631c462..c80ad2eaa 100644 --- a/object-mother/README.md +++ b/object-mother/README.md @@ -1,12 +1,14 @@ --- -title: Object Mother +title: "Object Mother Pattern in Java: Simplifying Object Creation for Testing" +shortTitle: Object Mother +description: "Explore the Object Mother pattern in Java for simplifying test object creation. Learn how to efficiently generate test data, reduce boilerplate, and enhance test maintainability with our in-depth guide and examples." category: Testing language: en tag: - - Code simplification - - Instantiation - - Isolation - - Testing + - Code simplification + - Instantiation + - Isolation + - Testing --- ## Also known as @@ -14,11 +16,11 @@ tag: * Object Builder * Test Data Builder -## Intent +## Intent of Object Mother Design Pattern -The Object Mother pattern simplifies the creation of objects for testing purposes, ensuring that test cases are clear and maintainable by centralizing the logic needed to instantiate objects in a consistent state. +The Object Mother pattern simplifies the creation of objects for testing purposes in Java, ensuring that test cases are clear and maintainable by centralizing the logic needed to instantiate objects in a consistent state. -## Explanation +## Detailed Explanation of Object Mother Pattern with Real-World Examples Real-world example @@ -35,7 +37,7 @@ wiki.c2.com says > 2. providing methods to update the objects during the tests, and > 3. if necessary, deleting the object from the database at the completion of the test. -**Programmatic example** +## Programmatic Example of Object Mother Pattern in Java The Object Mother is a design pattern that aims to provide an easy way to create objects for testing purposes. It encapsulates the logic for building instances of complex objects in one place, making it easier to maintain and reuse across multiple tests. @@ -121,7 +123,7 @@ class RoyaltyObjectMotherTest { In this way, the Object Mother pattern simplifies the creation of objects for testing, making the tests easier to read and maintain. -## Applicability +## When to Use the Object Mother Pattern in Java Use the Object Mother pattern when @@ -129,19 +131,19 @@ Use the Object Mother pattern when * You need to reuse a standard set of objects across multiple tests. * Test setup is becoming cumbersome and repetitive. -## Tutorials +## Object Mother Pattern Java Tutorials * [What is an ObjectMother? (Stack Overflow)](http://stackoverflow.com/questions/923319/what-is-an-objectmother) * [Object Mother (c2wiki)](http://c2.com/cgi/wiki?ObjectMother) * [Test Data Builders: an alternative to the Object Mother pattern (Nat Pryce)](http://www.natpryce.com/articles/000714.html) -## Known Uses +## Real-World Applications of Object Mother Pattern in Java * In unit testing frameworks to create test fixtures. * In enterprise applications to generate standard domain objects required across multiple test cases. * In open-source projects like Apache Commons and Spring Framework for test object creation. -## Consequences +## Benefits and Trade-offs of Object Mother Pattern Benefits: @@ -154,12 +156,12 @@ Trade-offs: * Maintenance: Requires maintaining the Object Mother class itself, which can grow complex over time. * Overhead: May introduce additional layers of abstraction that could complicate understanding for new developers. -## Related Patterns +## Related Java Design Patterns * [Builder](https://java-design-patterns.com/patterns/builder/): Both patterns deal with object creation. The Object Mother is often simpler and used specifically in a testing context, whereas the Builder Pattern is more general-purpose. * [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Similar in the sense of centralizing object creation logic. The Object Mother is specifically aimed at tests, while Factory Method is used more broadly in application code. -## Credits +## References and Credits * [Growing Object-Oriented Software, Guided by Tests](https://amzn.to/4dGfIuk) * [xUnit Test Patterns: Refactoring Test Code](https://amzn.to/4dHGDpm) diff --git a/object-pool/README.md b/object-pool/README.md index 623e7999c..56888b017 100644 --- a/object-pool/README.md +++ b/object-pool/README.md @@ -1,25 +1,27 @@ --- -title: Object Pool +title: "Object Pool Pattern in Java: Enhancing Performance with Reusable Object Management" +shortTitle: Object Pool +description: "Learn how the Object Pool design pattern improves performance by reusing expensive objects efficiently. Explore examples, benefits, and best practices in Java." category: Creational language: en tag: - - Game programming - - Instantiation - - Memory management - - Performance - - Resource management - - Scalability + - Game programming + - Instantiation + - Memory management + - Performance + - Resource management + - Scalability --- ## Also known as * Resource Pool -## Intent +## Intent of Object Pool Design Pattern -The Object Pool design pattern manages a pool of reusable objects, optimizing resource use by recycling objects rather than creating and destroying them repeatedly. +The Object Pool design pattern in Java manages a pool of reusable objects, optimizing memory management and application performance by recycling objects rather than creating and destroying them repeatedly. -## Explanation +## Detailed Explanation of Object Pool Pattern with Real-World Examples Real-world example @@ -33,7 +35,7 @@ Wikipedia says > The object pool pattern is a software creational design pattern that uses a set of initialized objects kept ready to use – a "pool" – rather than allocating and destroying them on demand. -**Programmatic Example** +## Programmatic Example of Object Pool Pattern in Java In our war game we need to use oliphaunts, massive and mythic beasts, but the problem is that they are extremely expensive to create. The solution is to create a pool of them, track which ones are in-use, and instead of disposing them re-use the instances. @@ -149,7 +151,7 @@ Program output: 21:21:58.147 [main] INFO com.iluwatar.object.pool.App -- Pool available=0 inUse=3 ``` -## Applicability +## When to Use the Object Pool Pattern in Java Use the Object Pool pattern when @@ -158,14 +160,14 @@ Use the Object Pool pattern when * A fixed number of objects need to be controlled, like in connection pooling. * Object reuse can significantly improve system performance and resource management. -## Known Uses +## Real-World Applications of Object Mother Pattern in Java * Database connection pooling in Java applications. * Thread pooling in Java concurrent programming. * Pooling of socket connections in network applications. * Object pools in game development for frequently created and destroyed game objects. -## Consequences +## Benefits and Trade-offs of Object Pool Pattern Benefits: @@ -179,13 +181,13 @@ Trade-offs: * Thread Safety: Requires careful handling of concurrent access to the pool, introducing potential synchronization issues. * Initialization Cost: Initial creation of the pool can be resource-intensive. -## Related Patterns +## Related Java Design Patterns * [Singleton](https://java-design-patterns.com/patterns/singleton/): Ensures a single instance of the pool is used, providing a global point of access. * [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Shares fine-grained objects to reduce memory usage, complementing object pooling by managing object state efficiently. * [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Often used to create objects within the pool, abstracting the instantiation process. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/observer/README.md b/observer/README.md index e2327d300..1bf11fbe3 100644 --- a/observer/README.md +++ b/observer/README.md @@ -1,23 +1,25 @@ --- -title: Observer +title: "Observer Pattern in Java: Mastering Reactive Interfaces in Java Applications" +shortTitle: Observer +description: "Learn the Observer design pattern in Java. Discover its intent, applicability, and real-world examples. Understand how it promotes loose coupling and dynamic observer management. Ideal for software developers and architects." category: Behavioral language: en tag: - - Decoupling - - Event-driven - - Gang Of Four - - Publish/subscribe + - Decoupling + - Event-driven + - Gang Of Four + - Publish/subscribe --- ## Also known as * Dependents -## Intent +## Intent of Observer Design Pattern -Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. +The Observer pattern in Java defines a one-to-many relationship between objects, ensuring that when one object updates its state, all dependent observers are notified and updated automatically, enhancing system responsiveness and modularity. -## Explanation +## Detailed Explanation of Observer Pattern with Real-World Examples Real-world example @@ -25,13 +27,13 @@ Real-world example In plain words -> Register as an observer to receive state changes in the object. +> Implement the Observer interface to actively monitor and respond to state changes in Java applications, improving event-driven programming efficiency. Wikipedia says > The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. -**Programmatic Example** +## Programmatic Example of Observer Pattern in Java In a land far away live the races of hobbits and orcs. Both of them are mostly outdoors, so they closely follow the weather changes. One could say that they are constantly observing the weather. @@ -161,7 +163,7 @@ Program output: 21:28:08.313 [main] INFO com.iluwatar.observer.generic.GenHobbits -- The hobbits are facing Sunny weather now ``` -## Applicability +## When to Use the Observer Pattern in Java Use the Observer pattern in any of the following situations: @@ -169,7 +171,7 @@ Use the Observer pattern in any of the following situations: * When a change to one object requires changing others, and you don't know how many objects need to be changed. * When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't want these objects tightly coupled. -## Known uses +## Real-World Applications of Observer Pattern in Java * [java.util.Observer](http://docs.oracle.com/javase/8/docs/api/java/util/Observer.html) * [java.util.EventListener](http://docs.oracle.com/javase/8/docs/api/java/util/EventListener.html) @@ -178,11 +180,11 @@ Use the Observer pattern in any of the following situations: * Model-View-Controller (MVC) frameworks. * Event handling systems. -## Consequences +## Benefits and Trade-offs of Observer Pattern Benefits: -* Promotes loose coupling between the subject and its observers. +* This Java design pattern promotes loose coupling, allowing the subject and its observers to interact without tight dependencies, facilitating easier maintenance and scalability. * Allows dynamic subscription and unsubscription of observers. Trade-offs: @@ -191,12 +193,12 @@ Trade-offs: * The order of notification is not specified, leading to potential unexpected behavior. * Potential for performance issues with a large number of observers. -## Related Patterns +## Related Java Design Patterns * [Mediator](https://java-design-patterns.com/patterns/mediator/): Encapsulates how a set of objects interact, which can be used to reduce the direct dependencies among objects. * [Singleton](https://java-design-patterns.com/patterns/singleton/): Often used with the Observer pattern to ensure a single instance of the subject. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Java Generics and Collections](https://amzn.to/3VhOBxp) diff --git a/optimistic-offline-lock/README.md b/optimistic-offline-lock/README.md index b2e1942e8..98bf4140b 100644 --- a/optimistic-offline-lock/README.md +++ b/optimistic-offline-lock/README.md @@ -1,25 +1,27 @@ --- -title: Optimistic Offline Lock +title: "Optimistic Offline Lock Pattern in Java: Mastering Conflict Resolution in Database Transactions" +shortTitle: Optimistic Offline Lock +description: "Explore the Optimistic Offline Lock design pattern in Java with detailed implementation guidelines and practical examples. Learn how to manage data concurrency effectively in your Java applications." category: Data access language: en tag: - - Concurrency - - Data access - - Fault tolerance - - Isolation - - Persistence - - Transactions + - Concurrency + - Data access + - Fault tolerance + - Isolation + - Persistence + - Transactions --- ## Also known as * Optimistic Concurrency Control -## Intent +## Intent of Optimistic Offline Lock Design Pattern -To manage concurrent data modifications without using long-duration database locks, thus improving system performance and scalability. +The Optimistic Offline Lock pattern in Java is specifically designed to manage concurrent data modifications without the need for long-duration database locks, thus enhancing system performance and scalability. -## Explanation +## Detailed Explanation of Optimistic Offline Lock Pattern with Real-World Examples Real-world example @@ -33,7 +35,9 @@ Wikipedia says > Optimistic concurrency control (OCC), also known as optimistic locking, is a concurrency control method applied to transactional systems such as relational database management systems and software transactional memory. -**Programmatic Example** +## Programmatic Example of Optimistic Offline Lock Pattern in Java + +In this section, we delve into the practical implementation of the Optimistic Offline Lock in Java. By following these steps, you can ensure that your application handles data conflicts and concurrency with minimal overhead. The Optimistic Offline Lock pattern is a concurrency control method that allows multiple transactions to proceed without locks, resolving conflicts only when they occur. This pattern is useful in scenarios where the likelihood of conflicting transactions is low and long-duration locks could hamper performance and scalability. @@ -88,24 +92,24 @@ public class CardUpdateService implements UpdateService { In this code snippet, the doUpdate method in the CardUpdateService class is a programmatic example of the Optimistic Offline Lock pattern. It allows the Card entity to be updated without locks and resolves conflicts by checking the version of the Card before the update. -## Applicability +## When to Use the Optimistic Offline Lock Pattern in Java * When multiple transactions need to access and modify the same data simultaneously without causing data inconsistencies. * In systems where the likelihood of conflicting transactions is low. * When you want to avoid long-duration locks that could hamper performance and scalability. -## Tutorials +## Optimistic Offline Lock Pattern Java Tutorials * [Offline Concurrency Control (Baeldung)](https://www.baeldung.com/cs/offline-concurrency-control) * [Optimistic Locking in JPA (Baeldung)](https://www.baeldung.com/jpa-optimistic-locking) -## Known uses +## Real-World Applications of Optimistic Offline Lock Pattern in Java * Web-based applications with high-read, low-write access patterns. * Distributed systems where locking resources for long durations is not feasible. * Java enterprise applications using JPA or Hibernate for data persistence. -## Consequences +## Benefits and Trade-offs of Optimistic Offline Lock Pattern Benefits: @@ -119,13 +123,13 @@ Trade-offs: * Can lead to more frequent retries of transactions if conflicts are common. * Not suitable for high-conflict scenarios where frequent data modification collisions occur. -## Related Patterns +## Related Java Design Patterns * Pessimistic Offline Lock: Unlike the Optimistic Offline Lock, this pattern uses locks to prevent conflicts by locking the data during the entire transaction. It is useful in high-conflict scenarios. * [Unit of Work](https://java-design-patterns.com/patterns/unit-of-work/): Helps in managing a set of changes as a single transaction, ensuring data integrity. It can be used in conjunction with Optimistic Offline Lock to handle complex transactions. * [Version Number](https://java-design-patterns.com/patterns/version-number/): A common technique used in Optimistic Offline Lock to detect conflicts by maintaining a version number for each data entity. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Java Persistence with Hibernate](https://amzn.to/44tP1ox) diff --git a/page-controller/README.md b/page-controller/README.md index 60d0e1d3a..28360c9b8 100644 --- a/page-controller/README.md +++ b/page-controller/README.md @@ -1,23 +1,25 @@ --- -title: Page Controller +title: "Page Controller Pattern in Java: Centralizing Web Page Logic for Cleaner Design" +shortTitle: Page Controller +description: "Explore the Page Controller design pattern in Java with detailed examples. Learn how it handles web application requests and improves architectural organization." categories: Architectural language: en tags: - - API design - - Business - - Client-server - - Decoupling - - Enterprise patterns - - Layered architecture - - Presentation - - Web development + - API design + - Business + - Client-server + - Decoupling + - Enterprise patterns + - Layered architecture + - Presentation + - Web development --- -## Intent +## Intent of Page Controller Design Pattern The Page Controller pattern is intended to handle requests for a specific page or action within a web application, processing input, and determining the appropriate view for rendering the response. -## Explanation +## Detailed Explanation of Page Controller Pattern with Real-World Examples Real-world example @@ -27,11 +29,11 @@ Real-world example In plain words -> The Page Controller pattern handles requests for specific pages or actions within a web application, processing input, executing business logic, and determining the appropriate view for rendering the response. +> The Page Controller pattern handles requests for specific pages or actions within a Java web application, processing input, executing business logic, and determining the appropriate view for rendering the response, enhancing response handling and system architecture. -**Programmatic Example** +## Programmatic Example of Page Controller Pattern in Java -The Page Controller design pattern is a pattern used in web development where each page of a website is associated with a class or function known as a controller. The controller handles the HTTP requests for that page and determines which model and view to use. This pattern is commonly used in MVC (Model-View-Controller) architectures. +The Page Controller design pattern is a pattern used in web development where each page of a website is associated with a class or function known as a controller. The controller handles the HTTP requests for that page and determines which model and view to use. Predominantly utilized in MVC (Model-View-No-Controller) architectures, the Java Page Controller pattern integrates seamlessly with existing enterprise frameworks. In the provided code, we have an example of the Page Controller pattern implemented using Spring Boot in Java. Let's break it down: @@ -119,19 +121,19 @@ public class UserView { In this example, the controllers (`SignupController` and `UserController`) are the Page Controllers. They handle the HTTP requests for their respective pages and determine which model and view to use. The models (`SignupModel` and `UserModel`) hold the data for the page, and the views (`SignupView` and `UserView`) determine how that data is presented. This separation of concerns makes the code easier to manage and maintain. -## Applicability +## When to Use the Page Controller Pattern in Java * When developing a web application where each page or action needs specific processing. * When aiming to separate the request handling logic from the view rendering logic. * In scenarios where a clear separation of concerns between different layers (controller, view) is required. -## Known Uses +## Real-World Applications of Page Controller Pattern in Java * Spring MVC (Java) * Apache Struts * JSF (JavaServer Faces) -## Consequences +## Benefits and Trade-offs of Page Controller Pattern Benefits: @@ -144,13 +146,13 @@ Trade-offs: * Complexity: Can add complexity to the application structure, requiring careful organization and documentation. * Overhead: May introduce performance overhead due to additional layers of abstraction and processing. -## Related Patterns +## Related Java Design Patterns * [Front Controller](https://java-design-patterns.com/patterns/front-controller/): Often used in conjunction with Page Controller to handle common pre-processing logic such as authentication and logging. * View Helper: Works alongside Page Controller to assist in preparing the view, often handling formatting and other presentation logic. * [Model-View-Controller (MVC)](https://java-design-patterns.com/patterns/model-view-controller/): Page Controller is a fundamental part of the MVC architecture, acting as the Controller. -## Credits +## References and Credits * [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap) * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) diff --git a/page-object/README.md b/page-object/README.md index 9e63dd8ee..6f21070a3 100644 --- a/page-object/README.md +++ b/page-object/README.md @@ -1,25 +1,27 @@ --- -title: Page Object +title: "Page Object Pattern in Java: Streamlining UI Testing for Better Maintainability" +shortTitle: Page Object +description: "Explore the Page Object design pattern for Java. Learn how to implement, use, and optimize this pattern for better code maintainability and test automation in Java applications." category: Testing language: en tag: - - Abstraction - - Code simplification - - Decoupling - - Encapsulation - - Testing - - Web development + - Abstraction + - Code simplification + - Decoupling + - Encapsulation + - Testing + - Web development --- ## Also known as * Page Object Model (POM) -## Intent +## Intent of Page Object Design Pattern -The Page Object pattern aims to create a model of the UI elements of a web page to improve the maintainability and readability of test automation code. +The Page Object pattern in Java aims to create a model of the UI elements of a web page to improve the maintainability and readability of test automation code. -## Explanation +## Detailed Explanation of Page Object Pattern with Real-World Examples Real-world example @@ -29,7 +31,7 @@ Real-world example In plain words -> The Page Object design pattern creates an abstraction layer for web pages, encapsulating their elements and interactions to simplify and maintain automated testing scripts. +> The Page Object design pattern creates an abstraction layer for web pages, encapsulating their elements and interactions to simplify and maintain automated UI testing scripts. selenium.dev says @@ -37,7 +39,7 @@ selenium.dev says > > Page Object is a Design Pattern that has become popular in test automation for enhancing test maintenance and reducing code duplication. A page object is an object-oriented class that serves as an interface to a page of your AUT. The tests then use the methods of this page object class whenever they need to interact with the UI of that page. The benefit is that if the UI changes for the page, the tests themselves don’t need to change, only the code within the page object needs to change. Subsequently, all changes to support that new UI are located in one place. -**Programmatic example** +## Programmatic Example of Page Object Pattern in Java The Page Object design pattern is a popular design pattern in test automation. It helps in enhancing test maintenance and reducing code duplication. A page object is an object-oriented class that serves as an interface to a page of your Application Under Test (AUT). The tests then use the methods of this page object class whenever they need to interact with the UI of that page. The benefit is that if the UI changes for the page, the tests themselves don’t need to change, only the code within the page object needs to change. Subsequently, all changes to support that new UI are located in one place. @@ -81,22 +83,22 @@ In this example, the `LoginPage` class represents the login page of a web applic This Page Object can be used in test scripts to interact with the login page without exposing the details of the page structure in the test code, promoting maintainability and reusability. -## Applicability +## When to Use the Page Object Pattern in Java Use the Page Object pattern when -* Automating tests for web applications. +* Automating UI tests for web applications. * You want to separate the UI actions from the test logic. * Enhancing test code readability and reducing duplication. * Simplifying maintenance when the web UI changes. -## Known Uses +## Real-World Applications of Page Object Pattern in Java * Selenium WebDriver tests for web applications. * Automated UI testing frameworks in Java. * Popular test automation frameworks like TestNG and JUnit. -## Consequences +## Benefits and Trade-offs of Page Object Pattern Benefits: @@ -110,13 +112,13 @@ Trade-offs: * Initial Setup: Requires extra effort to design and implement page objects. * Complexity: Overuse may lead to a complex structure with many page objects and methods. -## Related Patterns +## Related Java Design Patterns * [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used alongside Page Objects to add additional responsibilities to objects dynamically. * [Facade](https://java-design-patterns.com/patterns/facade/): Both provide a simplified interface to a complex subsystem. Page Object abstracts the complexities of the UI. * [Proxy](https://java-design-patterns.com/patterns/proxy/): Acts as a surrogate or placeholder, which can also be used for lazy initialization of page objects. -## Credits +## References and Credits * [Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation](https://amzn.to/4bjhTSK) * [Selenium Design Patterns and Best Practices](https://amzn.to/4aofYv8) diff --git a/parameter-object/README.md b/parameter-object/README.md index fe23483f4..bbb1c73d9 100644 --- a/parameter-object/README.md +++ b/parameter-object/README.md @@ -1,24 +1,26 @@ --- -title: Parameter Object +title: "Parameter Object Pattern in Java: Simplifying Method Signatures with Structured Data" +shortTitle: Parameter Object +description: "Explore the Parameter Object pattern at Java Design Patterns. Learn how it simplifies method signatures, enhances maintainability, and promotes encapsulation with real-world examples and detailed code snippets." category: Structural language: en tag: - - Abstraction - - Code simplification - - Decoupling - - Encapsulation - - Object composition + - Abstraction + - Code simplification + - Decoupling + - Encapsulation + - Object composition --- ## Also known as * Argument Object -## Intent +## Intent of Parameter Object Design Pattern -Simplify method signatures by encapsulating parameters into a single object, promoting cleaner code and better maintainability. +The Parameter Object pattern is a key Java design pattern aimed at improving code maintainability by reducing method complexity through encapsulation of parameters into a single object. -## Explanation +## Detailed Explanation of Parameter Object Pattern with Real-World Examples Real-world example @@ -38,9 +40,9 @@ wiki.c2.com says > Replace the LongParameterList with a ParameterObject; an object or structure with data members representing the arguments to be passed in. -**Programmatic example** +## Programmatic Example of Parameter Object Pattern in Java -The Parameter Object design pattern is a way to group multiple parameters into a single object. This simplifies method signatures and enhances code maintainability. +The Parameter Object design pattern is a way to group multiple parameters into a single object. This simplifies method signatures and enhances code maintainability enabling Java developers to streamline complex method calls, focusing on cleaner and more maintainable Java code. First, let's look at the `ParameterObject` class. This class encapsulates the parameters needed for the search operation. It uses [Builder pattern](https://java-design-patterns.com/patterns/builder/) to allow for easy creation of objects, even when there are many parameters. @@ -127,24 +129,23 @@ public class App { This example demonstrates how the Parameter Object pattern can simplify method signatures and make the code more maintainable. It also shows how the pattern can be combined with the Builder pattern to make object creation more flexible and readable. -## Applicability +## When to Use the Parameter Object Pattern in Java * Methods require multiple parameters that logically belong together. * There is a need to reduce the complexity of method signatures. * The parameters may need to evolve over time, adding more properties without breaking existing method signatures. * It’s beneficial to pass data through a method chain. -## Tutorials +## Parameter Object Pattern Java Tutorials * [Does Java have default parameters? (Daniel Olszewski)](http://dolszewski.com/java/java-default-parameters) - -## Known Uses +## Real-World Applications of Parameter Object Pattern in Java * Java Libraries: Many Java frameworks and libraries use this pattern. For example, Java’s java.util.Calendar class has various methods where parameter objects are used to represent date and time components. * Enterprise Applications: In large enterprise systems, parameter objects are used to encapsulate configuration data passed to services or API endpoints. -## Consequences +## Benefits and Trade-offs of Parameter Object Pattern Benefits: @@ -164,7 +165,7 @@ Trade-offs: * [Composite](https://java-design-patterns.com/patterns/composite/): Sometimes used with parameter objects to handle hierarchical parameter data. * [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Can be used to create instances of parameter objects, particularly when different parameter combinations are needed. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/partial-response/README.md b/partial-response/README.md index c1abd7590..a3704a4c3 100644 --- a/partial-response/README.md +++ b/partial-response/README.md @@ -1,15 +1,17 @@ --- -title: Partial Response +title: "Partial Response Pattern in Java: Optimizing Data Delivery for Efficient Web Services" +shortTitle: Partial Response +description: "Explore the Partial Response design pattern for APIs, a strategy to boost performance by allowing clients to process data as soon as it becomes available. Learn how it improves scalability and reduces server load." category: Behavioral language: en tag: - - API design - - Asynchronous - - Client-server - - Decoupling - - Performance - - Scalability - - Web development + - API design + - Asynchronous + - Client-server + - Decoupling + - Performance + - Scalability + - Web development --- ## Also known as @@ -17,11 +19,11 @@ tag: * Incremental Response * Partial Result -## Intent +## Intent of Partial Response Design Pattern To enable an application to return a partial response to a client, improving perceived performance and enabling the client to start processing parts of the data before the entire response is available. -## Explanation +## Detailed Explanation of Partial Response Pattern with Real-World Examples Real-world example @@ -31,7 +33,7 @@ In plain words > The Partial Response design pattern allows a system to send portions of data to the client as they become available, enabling the client to start processing the data before the complete response is received. -**Programmatic Example** +## Programmatic Example of Partial Response Pattern in Java The Partial Response design pattern allows clients to specify which fields of a resource they need. This pattern is useful for reducing the amount of data transferred over the network and allowing clients to start processing data sooner. @@ -136,21 +138,23 @@ To summarize, in this example: By implementing the Partial Response design pattern, clients can request only the necessary data, enhancing performance and reducing bandwidth usage. -## Applicability +## When to Use the Partial Response Pattern in Java Use the Partial Response pattern when -* When the response data is large or takes a long time to process and transfer. +* Utilize the Partial Response pattern when dealing with large data sets or APIs that require improved load time and performance. * When it’s beneficial for the client to begin processing the data as it arrives rather than waiting for the complete response. * In APIs where different clients might need different subsets of data, allowing them to specify what they need. -## Known Uses +## Real-World Applications of Partial Response Pattern in Java + +This pattern is widely adopted in * RESTful APIs allowing clients to specify fields they want using query parameters. * Streaming large datasets where initial parts of the data can be sent immediately (e.g., video streaming). * GraphQL queries where clients can request only specific fields to be returned. -## Consequences +## Benefits and Trade-offs of Partial Response Pattern Benefits: @@ -164,13 +168,13 @@ Trade-offs: * Error Handling: May complicate error handling and recovery if only parts of the data are received correctly. * State Management: Requires careful management of state, especially if the partial responses are to be processed incrementally. -## Related Patterns +## Related Java Design Patterns * Asynchronous Messaging: Often used together with asynchronous messaging patterns to handle partial responses without blocking the client. * [Caching](https://java-design-patterns.com/patterns/caching/): Can be combined with caching patterns to store partial responses and avoid redundant data transfers. * [Proxy](https://java-design-patterns.com/patterns/proxy/): The proxy can intercept requests and manage partial responses, providing a buffer between the client and server. -## Credits +## References and Credits * [Building Microservices](https://amzn.to/3UACtrU) * [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/4dKEwBa) diff --git a/pipeline/README.md b/pipeline/README.md index a7355513f..e05f151e2 100644 --- a/pipeline/README.md +++ b/pipeline/README.md @@ -1,14 +1,16 @@ --- -title: Pipeline +title: "Pipeline Pattern in Java: Streamlining Data Processing with Modular Components" +shortTitle: Pipeline +description: "Master the Pipeline design pattern in Java with our comprehensive guide. Learn how to implement data processing in discrete stages for improved code scalability and flexibility. Ideal for developers looking to advance their software engineering skills." category: Behavioral language: en tag: - - API design - - Data processing - - Decoupling - - Extensibility - - Functional decomposition - - Scalability + - API design + - Data processing + - Decoupling + - Extensibility + - Functional decomposition + - Scalability --- ## Also known as @@ -16,15 +18,15 @@ tag: * Chain of Operations * Processing Pipeline -## Intent +## Intent of Pipeline Design Pattern -The Pipeline design pattern is intended to allow data processing in discrete stages, where each stage is represented by a different component and the output of one stage serves as the input for the next. +The Pipeline design pattern in Java is engineered to facilitate data processing across discrete stages, enhancing modular development and operational efficiency. -## Explanation +## Detailed Explanation of Pipeline Pattern with Real-World Examples Real-world example -> A real-world analogous example of the Pipeline design pattern is an **assembly line in a car manufacturing plant**. +> A practical example of the Java Pipeline design pattern can be seen in assembly lines, such as those in car manufacturing, illustrating its efficiency and scalability. > > In this analogy, the car manufacturing process is divided into several discrete stages, each stage handling a specific part of the car assembly. For example: > @@ -34,7 +36,7 @@ Real-world example > 4. **Interior Assembly:** The interior, including seats and dashboard, is installed. > 5. **Quality Control:** The finished car is inspected for defects. > ->Each stage operates independently and sequentially, where the output of one stage (e.g., a partially assembled car) becomes the input for the next stage. This modular approach allows for easy maintenance, scalability (e.g., adding more workers to a stage), and flexibility (e.g., replacing a stage with a more advanced version). Just like in a software pipeline, changes in one stage do not affect the others, facilitating continuous improvements and efficient production. +> In the Java Pipeline pattern, each stage functions independently and sequentially, ensuring smooth data flow and easy modifications. The output of one stage (e.g., a partially assembled car) becomes the input for the next stage. This modular approach allows for easy maintenance, scalability (e.g., adding more workers to a stage), and flexibility (e.g., replacing a stage with a more advanced version). Just like in a software pipeline, changes in one stage do not affect the others, facilitating continuous improvements and efficient production. In plain words @@ -44,7 +46,7 @@ Wikipedia says > In software engineering, a pipeline consists of a chain of processing elements (processes, threads, coroutines, functions, etc.), arranged so that the output of each element is the input of the next; the name is by analogy to a physical pipeline. -**Programmatic Example** +## Programmatic Example of Pipeline Pattern in Java Let's create a string processing pipeline example. The stages of our pipeline are called `Handler`s. @@ -117,7 +119,7 @@ Console output: 07:34:27.075 [main] INFO com.iluwatar.pipeline.App -- Pipeline output: [!] ``` -## Applicability +## When to Use the Pipeline Pattern in Java Use the Pipeline pattern when you want to @@ -125,20 +127,20 @@ Use the Pipeline pattern when you want to * When each stage of processing is independent and can be easily replaced or reordered. * When you want to improve the scalability and maintainability of data processing code. -## Tutorials +## Pipeline Pattern Java Tutorials * [The Pipeline design pattern (in Java) (Medium)](https://medium.com/@deepakbapat/the-pipeline-design-pattern-in-java-831d9ce2fe21) * [The Pipeline Pattern — for fun and profit (Aaron Weatherall)](https://medium.com/@aaronweatherall/the-pipeline-pattern-for-fun-and-profit-9b5f43a98130) * [Pipelines (Microsoft)](https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ff963548(v=pandp.10)) -## Known Uses +## Real-World Applications of Pipeline Pattern in Java * Data transformation and ETL (Extract, Transform, Load) processes. * Compilers for processing source code through various stages such as lexical analysis, syntax analysis, semantic analysis, and code generation. * Image processing applications where multiple filters are applied sequentially. * Logging frameworks where messages pass through multiple handlers for formatting, filtering, and output. -## Consequences +## Benefits and Trade-offs of Pipeline Pattern Benefits: @@ -153,13 +155,13 @@ Trade-offs: * Performance Overhead: Each stage introduces some performance overhead due to context switching and data transfer between stages. * Debugging Difficulty: Debugging pipelines can be more challenging since the data flows through multiple components. -## Related Patterns +## Related Java Design Patterns * [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Both patterns involve passing data through a series of handlers, but in Chain of Responsibility, handlers can decide not to pass the data further. * [Decorator](https://java-design-patterns.com/patterns/decorator/): Both patterns involve adding behavior dynamically, but Decorator wraps additional behavior around objects, whereas Pipeline processes data in discrete steps. * [Composite](https://java-design-patterns.com/patterns/composite/): Like Pipeline, Composite also involves hierarchical processing, but Composite is more about part-whole hierarchies. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525) diff --git a/poison-pill/README.md b/poison-pill/README.md index 843245ba3..15e33c66b 100644 --- a/poison-pill/README.md +++ b/poison-pill/README.md @@ -1,23 +1,25 @@ --- -title: Poison Pill +title: "Poison Pill Pattern in Java: Gracefully Terminating Multithreaded Processes" +shortTitle: Poison Pill +description: "Explore the Poison As an alternative to "Poison Pill" design pattern in Java, used for gracefully shutting down multi-threaded applications. Understand its intent, applicability, and see a real-world example. Perfect for developers looking to enhance concurrency and messaging systems." category: Concurrency language: en tag: - - Decoupling - - Fault tolerance - - Messaging - - Thread management + - Decoupling + - Fault tolerance + - Messaging + - Thread management --- ## Also known as * Shutdown Signal -## Intent +## Intent of Poison Pill Design Pattern -The Poison Pill design pattern is used to gracefully shut down a service or a producer-consumer system by sending a special message (the "poison pill") which indicates that no more messages will be sent, allowing the consumers to terminate. +The Poison Pill design pattern is used to gracefully shut down a service or a producer-consumer system by sending a special message (the "poison pill") to message queue which indicates that no more messages will be sent, allowing the consumers to terminate. -## Explanation +## Detailed Explanation of Poison Pill Pattern with Real-World Examples Real-world example @@ -27,7 +29,9 @@ In plain words > Poison Pill is a known message structure that ends the message exchange. -**Programmatic Example** +## Programmatic Example of Poison Pill Pattern in Java + +In this Java example, the Poison Pill serves as a shutdown signal within message queues, demonstrating effective thread management and consumer communication. Let's define the message structure first. There's interface `Message` and implementation `SimpleMessage`. @@ -206,25 +210,25 @@ Program output: 07:43:01.520 [Thread-0] INFO com.iluwatar.poison.pill.Consumer -- Consumer CONSUMER_1 receive request to terminate. ``` -## Class diagram +## Detailed Explanation of Poison Pill Pattern with Real-World Examples ![Poison Pill](./etc/poison-pill.png "Poison Pill") -## Applicability +## When to Use the Poison Pill Pattern in Java Use the Poison Pill idiom when: -* When there is a need to gracefully shut down a multithreaded application. +* Systems require robust fault tolerance and seamless consumer shutdown in multithreaded environments. * In producer-consumer scenarios where consumers need to be informed about the end of message processing. * To ensure that consumers can finish processing remaining messages before shutting down. -## Known Uses +## Real-World Applications of Poison Pill Pattern in Java * Java ExecutorService shutdown using a special task to signal shutdown. * Messaging systems where a specific message indicates the end of the queue processing. * [Akka framework](https://doc.akka.io/japi/akka/2.5/akka/actor/typed/internal/PoisonPill.html) -## Consequences +## Benefits and Trade-offs of Poison Pill Pattern Benefits: @@ -237,13 +241,13 @@ Trade-offs: * Requires consumers to check for the poison pill, adding some overhead. * If not managed properly, could lead to consumers not recognizing the poison pill, causing indefinite blocking. -## Related Patterns +## Related Java Design Patterns * [Producer-Consumer](https://java-design-patterns.com/patterns/producer-consumer/): Works in tandem with the Poison Pill pattern to handle the communication and shutdown of consumers. * Message Queue: Often uses poison pills to signal the end of message processing in the queue. * [Observer](https://java-design-patterns.com/patterns/observer/): Can be used to notify subscribers about the shutdown event. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Java Concurrency in Practice](https://amzn.to/4aRMruW) diff --git a/pom.xml b/pom.xml index 2525cb4f6..c955b7da4 100644 --- a/pom.xml +++ b/pom.xml @@ -131,7 +131,7 @@ value-object monad mute-idiom - hexagonal + hexagonal-architecture abstract-document microservices-aggregrator promise @@ -146,7 +146,7 @@ guarded-suspension balking extension-objects - marker + marker-interface command-query-responsibility-segregation event-sourcing data-transfer-object diff --git a/presentation-model/README.md b/presentation-model/README.md index f5f43a660..597c45803 100644 --- a/presentation-model/README.md +++ b/presentation-model/README.md @@ -1,23 +1,25 @@ --- -title: Presentation Model +title: "Presentation Model Pattern in Java: Enhancing UI Design with Robust Data Management" +shortTitle: Presentation Model +description: "Explore the Presentation Model Pattern at Java Design Patterns. Learn how it separates UI from business logic to enhance flexibility, maintainability, and testability. Ideal for Java developers interested in robust design solutions." category: Architectural language: en tag: - - Decoupling - - Encapsulation - - Presentation - - Testing + - Decoupling + - Encapsulation + - Presentation + - Testing --- ## Also known as * Application Model -## Intent +## Intent of Presentation Model Design Pattern -To separate the logic of the user interface (UI) from the business logic by creating a model that represents the data and behavior of the UI independently. +The Presentation Model pattern separates the logic of the user interface (UI) from the business logic by creating a model that represents the data and behavior of the UI independently. -## Explanation +## Detailed Explanation of Presentation Model Pattern with Real-World Examples Real-world example @@ -27,9 +29,9 @@ In plain words > The Presentation Model design pattern separates the UI logic from the business logic by creating an intermediate model that represents the data and behavior of the UI independently, enhancing testability, maintainability, and flexibility. -**Programmatic example** +## Programmatic Example of Presentation Model Pattern in Java -The Presentation Model design pattern is a pattern that separates the responsibility of managing the state and behavior of the GUI in a separate model class. This model class is not tied to the view and can be used to test the GUI behavior independently from the GUI itself. +The Presentation Model design pattern is a pattern that separates the responsibility of managing the state and behavior of the GUI in a separate model class. This model class is not tied to the view and can be used to test the GUI behavior independently of the GUI itself. Let's take a look at the code provided and see how it implements the Presentation Model pattern. @@ -103,20 +105,22 @@ public final class App { In this example, the `PresentationModel` class is the Presentation Model. It separates the GUI's state and behavior from the `View` class, allowing the GUI to be tested independently from the actual GUI components. -## Applicability +## When to Use the Presentation Model Pattern in Java Use the Presentation Model Pattern when * Use when you want to decouple the UI from the underlying business logic to allow for easier testing, maintenance, and the ability to support multiple views or platforms. * Ideal for applications where the UI changes frequently or needs to be different across various platforms while keeping the core logic intact. -## Known Uses +## Real-World Applications of Presentation Model Pattern in Java + +The Presentation Model pattern is used in: * JavaFX applications: Utilizing JavaFX properties and bindings to create a clear separation between the UI and business logic. * Swing applications: Employing a Presentation Model to decouple Swing components from the application logic, enhancing testability and flexibility. * Android apps: Implementing MVVM architecture using ViewModel classes to manage UI-related data and lifecycle-aware components. -## Consequences +## Benefits and Trade-offs of Presentation Model Pattern Benefits: @@ -130,13 +134,13 @@ Trade-offs: * Complexity: Can introduce additional layers and complexity in the application architecture. * Learning Curve: May require a deeper understanding of binding mechanisms and state management. -## Related Patterns +## Related Java Design Patterns * [Model-View-Controller (MVC)](https://java-design-patterns.com/patterns/model-view-controller/): Similar in that it separates concerns, but Presentation Model encapsulates more of the view logic. * [Model-View-Presenter (MVP)](https://java-design-patterns.com/patterns/model-view-presenter/): Another UI pattern focusing on separation of concerns, but with a different interaction model. * [Observer](https://java-design-patterns.com/patterns/observer/): Often used within the Presentation Model to update the UI when the model changes. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/private-class-data/README.md b/private-class-data/README.md index 93c467392..18dd48053 100644 --- a/private-class-data/README.md +++ b/private-class-data/README.md @@ -1,11 +1,13 @@ --- -title: Private Class Data +title: "Private Class Data Pattern in Java: Safeguarding Data Integrity with Encapsulation" +shortTitle: Private Class Data +description: "Explore the Private Class Data pattern in Java, ideal for enhancing data security and integrity in object-oriented programming. Learn how it prevents unintended data manipulation with encapsulation." category: Structural language: en tag: - - Abstraction - - Encapsulation - - Security + - Abstraction + - Encapsulation + - Security --- ## Also known as @@ -13,11 +15,11 @@ tag: * Data Hiding * Encapsulation -## Intent +## Intent of Private Class Data Design Pattern -The Private Class Data design pattern aims to restrict access to the internal state of an object by providing controlled access through methods, thereby increasing security and reducing accidental data corruption. +The Private Class Data design pattern in Java focuses on restricting access to the internal state of an object, enhancing security and reducing risks of data corruption through controlled method access. -## Explanation +## Detailed Explanation of Private Class Data Pattern with Real-World Examples Real-world example @@ -31,7 +33,7 @@ Wikipedia says > Private class data is a design pattern in computer programming used to encapsulate class attributes and their manipulation. -**Programmatic Example** +## Programmatic Example of Private Class Data Pattern in Java Imagine you are cooking a stew for your family dinner. You want to stop your family members from tasting the stew while you're still preparing it. If they do, there might not be enough stew left for dinner. @@ -123,7 +125,7 @@ Program output: 08:00:08.213 [main] INFO com.iluwatar.privateclassdata.ImmutableStew -- Mixing the immutable stew we find: 2 potatoes, 4 carrots, 3 meat and 6 peppers ``` -## Applicability +## When to Use the Private Class Data Pattern in Java Use the Private Class Data pattern when @@ -131,13 +133,13 @@ Use the Private Class Data pattern when * When you need to limit the visibility of the internal data of an object to prevent unintended modification. * In scenarios where multiple classes need to share access to some common data without exposing it directly. -## Known Uses +## Real-World Applications of Private Class Data Pattern in Java * Java Beans, where properties are accessed via getters and setters. * In many Java libraries where the internal state is hidden from the user to ensure consistency and security. * Enterprise applications where sensitive data needs to be protected from direct access. -## Consequences +## Benefits and Trade-offs of Private Class Data Pattern Benefits: @@ -150,13 +152,13 @@ Trade-offs: * Performance Overhead: Additional method calls (getters/setters) can introduce slight performance overhead. * Complexity: May increase the complexity of the class design due to the additional layer of methods for data access. -## Related Patterns +## Related Java Design Patterns * [Proxy](https://java-design-patterns.com/patterns/proxy/): Both patterns restrict access to the underlying object but Proxy controls access to the object itself, while Private Class Data controls access to the data. * [Singleton](https://java-design-patterns.com/patterns/singleton/): Ensures that a class has only one instance and provides a global point of access to it; often used to manage shared data with controlled access. * [Decorator](https://java-design-patterns.com/patterns/decorator/): Adds behavior to an object without altering its structure; can be combined with Private Class Data to manage additional state privately. -## Credits +## References and Credits * [Clean Code: A Handbook of Agile Software Craftsmanship](https://amzn.to/3UJTZJk) * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) diff --git a/producer-consumer/README.md b/producer-consumer/README.md index c6821766c..a40ef5a65 100644 --- a/producer-consumer/README.md +++ b/producer-consumer/README.md @@ -1,14 +1,16 @@ --- -title: Producer-Consumer +title: "Producer-Consumer Pattern in Java: Streamlining Production and Consumption Processes" +shortTitle: Producer-Consumer +description: "Explore the Producer-Consumer pattern, a fundamental concept in Java for managing concurrent data production and consumption with buffer management. Ideal for improving system design and performance." category: Concurrency language: en tag: - - Asynchronous - - Buffering - - Decoupling - - Messaging - - Synchronization - - Thread management + - Asynchronous + - Buffering + - Decoupling + - Messaging + - Synchronization + - Thread management --- ## Also known as @@ -16,15 +18,15 @@ tag: * Bounded Buffer * Consumer-Producer -## Intent +## Intent of Producer-Consumer Design Pattern -The Producer-Consumer design pattern is used to decouple the tasks of producing and consuming data, enabling a producer to generate data and a consumer to process that data concurrently without direct dependency on each other. +The Producer-Consumer design pattern, a critical component for concurrent Java applications, is used to decouple the tasks of producing and consuming data, enabling a producer to generate data and a consumer to process that data concurrently without direct dependency on each other. -## Explanation +## Detailed Explanation of Producer-Consumer Pattern with Real-World Examples Real-world example -> A real-world example of the Producer-Consumer design pattern can be found in a factory assembly line. Imagine a car manufacturing plant where different stages of production occur. The "producer" could be the station that assembles car engines, while the "consumer" could be the station that installs the engines into car bodies. The engines are placed onto a conveyor belt (acting as a buffer) once they are assembled. The installation station takes engines off the conveyor belt to install them into cars. This allows the engine assembly and engine installation processes to operate independently, with the conveyor belt managing the synchronization between these two stages. If the assembly station produces engines faster than the installation station can install them, the excess engines are temporarily stored on the conveyor belt. Conversely, if the installation station needs engines but the assembly station is temporarily halted, it can still work on the engines available on the belt. +> In a typical car manufacturing setup, the Producer-Consumer pattern facilitates synchronous operations, ensuring efficient assembly and installation processes. Imagine a car manufacturing plant where different stages of production occur. The "producer" could be the station that assembles car engines, while the "consumer" could be the station that installs the engines into car bodies. The engines are placed onto a conveyor belt (acting as a buffer) once they are assembled. The installation station takes engines off the conveyor belt to install them into cars. This allows the engine assembly and engine installation processes to operate independently, with the conveyor belt managing the synchronization between these two stages. If the assembly station produces engines faster than the installation station can install them, the excess engines are temporarily stored on the conveyor belt. Conversely, if the installation station needs engines but the assembly station is temporarily halted, it can still work on the engines available on the belt. In plain words @@ -34,10 +36,12 @@ Wikipedia says > Dijkstra wrote about the case: "We consider two processes, which are called the 'producer' and the 'consumer' respectively. The producer is a cyclic process that produces a certain portion of information, that has to be processed by the consumer. The consumer is also a cyclic process that needs to process the next portion of information, as has been produced by the producer. We assume the two processes to be connected for this purpose via a buffer with unbounded capacity." -**Programmatic Example** +## Programmatic Example of Producer-Consumer Pattern in Java Consider a manufacturing process of item, the producer will need to pause the production when manufacturing pipeline is full and the consumer will need to pause the consumption of item when the manufacturing pipeline is empty. We can separate the process of production and consumption which work together and pause at separate times. +In this Java example, `Producers` generate items stored in `ItemQueue`, demonstrating efficient thread management and data synchronization essential for high-performance Java applications. + We have a simple `Item` record. They are stored in `ItemQueue`. ```java @@ -173,23 +177,23 @@ Program output: 08:10:17.483 [pool-1-thread-5] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_2] consume item [10] produced by [Producer_1] ``` -## Class diagram +## Detailed Explanation of Producer-Consumer Pattern with Real-World Examples ![Producer-Consumer](./etc/producer-consumer.png "Producer-Consumer") -## Applicability +## When to Use the Producer-Consumer Pattern in Java * When you need to manage a buffer or queue where producers add data and consumers take data, often in a multithreaded environment. * When decoupling the production and consumption of data is beneficial for the application's design, performance, or maintainability. * Suitable for scenarios requiring synchronized access to a shared resource or data structure. -## Known Uses +## Real-World Applications of Producer-Consumer Pattern in Java * Thread pools where worker threads act as consumers processing tasks produced by another thread. * Logging frameworks where log messages are produced by various parts of an application and consumed by a logging service. * Message queues in distributed systems for asynchronous communication between services. -## Consequences +## Benefits and Trade-offs of Producer-Consumer Pattern Benefits: @@ -202,12 +206,12 @@ Trade-offs: * Complexity: Requires careful handling of synchronization and potential deadlocks. * Resource Management: Properly managing the buffer size to avoid overflow or underflow conditions. -## Related Patterns +## Related Java Design Patterns * [Observer](https://java-design-patterns.com/patterns/observer/): While both deal with notifying or handling events, the Observer pattern is more about event subscription and notification, whereas Producer-Consumer focuses on decoupled data production and consumption. * [Thread Pool](https://java-design-patterns.com/patterns/thread-pool/): Uses a similar decoupling approach where tasks are produced and consumed by a pool of worker threads. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/promise/README.md b/promise/README.md index 08b6544ac..76b67e2fb 100644 --- a/promise/README.md +++ b/promise/README.md @@ -1,13 +1,15 @@ --- -title: Promise +title: "Promise Pattern in Java: Streamlining Async Tasks for Better Performance" +shortTitle: Promise +description: "Explore the Promise design pattern in Java, ideal for managing asynchronous operations efficiently. Learn how it enhances code readability and maintainability with practical examples and detailed explanations." category: Concurrency language: en tag: - - Asynchronous - - Decoupling - - Messaging - - Synchronization - - Thread management + - Asynchronous + - Decoupling + - Messaging + - Synchronization + - Thread management --- ## Also known as @@ -15,11 +17,11 @@ tag: * Deferred * Future -## Intent +## Intent of Promise Design Pattern The Promise design pattern is used to handle asynchronous operations by providing a placeholder for a result that is initially unknown but will be resolved in the future. -## Explanation +## Detailed Explanation of Promise Pattern with Real-World Examples Real-world example @@ -35,11 +37,11 @@ Wikipedia says > In computer science, future, promise, delay, and deferred refer to constructs used for synchronizing program execution in some concurrent programming languages. They describe an object that acts as a proxy for a result that is initially unknown, usually because the computation of its value is not yet complete. -**Programmatic Example** +## Programmatic Example of Promise Pattern in Java The Promise design pattern is a software design pattern that's often used in concurrent programming to handle asynchronous operations. It represents a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. -In the provided code, the Promise design pattern is used to handle various asynchronous operations such as downloading a file, counting lines in a file, and calculating the character frequency in a file. +In the provided example, a Promise is used to download files and perform operations like line counting and character frequency analysis asynchronously, showcasing the pattern's utility in practical applications. ```java @Slf4j @@ -124,26 +126,26 @@ Program output: 08:19:33.426 [pool-1-thread-2] INFO com.iluwatar.promise.App -- Char with lowest frequency is: ’ ``` -## Applicability +## When to Use the Promise Pattern in Java * When you need to perform asynchronous tasks and handle their results or errors at a later point. * In scenarios where tasks can be executed in parallel and their outcomes need to be handled once they are completed. * Suitable for improving the readability and maintainability of asynchronous code. -## Tutorials +## Promise Pattern Java Tutorials * [Functional-Style Callbacks Using Java 8's CompletableFuture (InfoQ)](https://www.infoq.com/articles/Functional-Style-Callbacks-Using-CompletableFuture) * [Guide To CompletableFuture (Baeldung)](https://www.baeldung.com/java-completablefuture) * [You are missing the point to Promises (Domenic Denicola)](https://gist.github.com/domenic/3889970) -## Known Uses +## Real-World Applications of Promise Pattern in Java * Java's CompletableFuture and Future classes. * JavaScript’s Promise object for managing asynchronous operations. * Many asynchronous frameworks and libraries such as RxJava and Vert.x. * [Guava ListenableFuture](https://github.com/google/guava/wiki/ListenableFutureExplained) -## Consequences +## Benefits and Trade-offs of Promise Pattern Benefits: @@ -156,13 +158,13 @@ Trade-offs: * Complexity: Can add complexity to the codebase if overused or misused. * Debugging: Asynchronous code can be harder to debug compared to synchronous code due to the non-linear flow of execution. -## Related Patterns +## Related Java Design Patterns * [Observer](https://java-design-patterns.com/patterns/observer/): Promises can be used in conjunction with the Observer pattern to notify subscribers about the completion of asynchronous operations. * [Callback](https://java-design-patterns.com/patterns/callback/): Promises often replace callback mechanisms by providing a more structured and readable way to handle asynchronous results. * [Async Method Invocation](https://java-design-patterns.com/patterns/async-method-invocation/): Promises are often used to handle the results of asynchronous method invocations, allowing for non-blocking execution and result handling. -## Credits +## References and Credits * [Effective Java](https://amzn.to/4cGk2Jz) * [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://amzn.to/3QCmGXs) diff --git a/property/README.md b/property/README.md index b13f8fb89..0bfd89183 100644 --- a/property/README.md +++ b/property/README.md @@ -1,13 +1,15 @@ --- -title: Property +title: "Property Pattern in Java: Enhancing Flexibility with Dynamic Attribute Management" +shortTitle: Property +description: "Explore how the Property design pattern facilitates dynamic property management in Java objects, enabling runtime modifications without altering class structure. Ideal for developers looking to enhance flexibility and maintainability in their code." category: Behavioral language: en tag: - - Abstraction - - Encapsulation - - Interface - - Object composition - - Polymorphism + - Abstraction + - Encapsulation + - Interface + - Object composition + - Polymorphism --- ## Also known as @@ -15,11 +17,11 @@ tag: * Dynamic Properties * Property Bag -## Intent +## Intent of Property Design Pattern -The Property design pattern allows dynamic addition, removal, or modification of properties of an object at runtime. +The Property design pattern in Java allows dynamic addition, removal, or modification of object properties, offering a flexible solution for developers to customize object attributes at runtime. -## Explanation +## Detailed Explanation of Property Pattern with Real-World Examples Real-world example @@ -29,7 +31,7 @@ In plain words > Define and manage a dynamic set of properties for an object, allowing customization without altering its structure. -**Programmatic Example** +## Programmatic Example of Property Pattern in Java The Property design pattern, also known as Prototype inheritance, is a pattern that allows objects to be created from other objects, forming object hierarchies. This pattern is particularly useful when you want to create a new object that is a slight variation of an existing object. @@ -118,44 +120,44 @@ Program output: 08:27:52.567 [main] INFO com.iluwatar.property.App -- Player: Player_1 Character type: MAGE Stats: - - AGILITY:10 - - STRENGTH:10 - - ATTACK_POWER:10 - - ARMOR:8 - - INTELLECT:15 - - SPIRIT:10 + - AGILITY:10 + - STRENGTH:10 + - ATTACK_POWER:10 + - ARMOR:8 + - INTELLECT:15 + - SPIRIT:10 08:27:52.569 [main] INFO com.iluwatar.property.App -- Player: Player_2 Character type: WARRIOR Stats: - - AGILITY:10 - - STRENGTH:10 - - ATTACK_POWER:10 - - ARMOR:15 - - RAGE:15 + - AGILITY:10 + - STRENGTH:10 + - ATTACK_POWER:10 + - ARMOR:15 + - RAGE:15 08:27:52.569 [main] INFO com.iluwatar.property.App -- Player: Player_3 Character type: ROGUE Stats: - - AGILITY:15 - - STRENGTH:10 - - ATTACK_POWER:10 - - ARMOR:10 - - ENERGY:15 + - AGILITY:15 + - STRENGTH:10 + - ATTACK_POWER:10 + - ARMOR:10 + - ENERGY:15 08:27:52.569 [main] INFO com.iluwatar.property.App -- Player: Player_4 Character type: ROGUE Stats: - - AGILITY:15 - - STRENGTH:10 - - ATTACK_POWER:12 - - ARMOR:10 - - ENERGY:15 + - AGILITY:15 + - STRENGTH:10 + - ATTACK_POWER:12 + - ARMOR:10 + - ENERGY:15 ``` This way, we can easily create new characters with different properties without having to create a new class for each type of character. -## Applicability +## When to Use the Property Pattern in Java Use the Property pattern when @@ -163,16 +165,18 @@ Use the Property pattern when * When properties need to be added or removed dynamically at runtime. * When different instances of a class need different properties. -## Known Uses +## Real-World Applications of Property Pattern in Java * Configurations in applications where different entities require different sets of configurable parameters. * Game development where game entities (like characters or objects) need various attributes that can change during gameplay. * User profile management systems where user profiles can have dynamic attributes. -## Consequences +## Benefits and Trade-offs of Property Pattern Benefits: +Employing the Property design pattern enhances + * Flexibility: Allows for the dynamic addition, removal, and modification of properties. * Decoupling: Reduces dependencies between classes and their properties. * Ease of Use: Simplifies the management of properties in large systems. @@ -183,13 +187,13 @@ Trade-offs: * Complexity: May increase the complexity of the code, making it harder to maintain and understand. * Type Safety: Reduces type safety since properties are often managed as generic key-value pairs. -## Related Patterns +## Related Java Design Patterns * [Composite](https://java-design-patterns.com/patterns/composite/): Composite allows a tree structure of objects where each node can be a complex or simple object. Property pattern can be seen as a flattened version, managing properties without hierarchy. * [Decorator](https://java-design-patterns.com/patterns/decorator/): Both patterns enhance an object's behavior, but the Property pattern focuses on adding properties dynamically, while the Decorator adds responsibilities. * [Strategy](https://java-design-patterns.com/patterns/strategy/): Like the Property pattern, the Strategy pattern allows dynamic behavior changes, but Strategy is about changing the algorithm used by an object. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/prototype/README.md b/prototype/README.md index 0281f3802..c68c5fbc0 100644 --- a/prototype/README.md +++ b/prototype/README.md @@ -1,23 +1,25 @@ --- -title: Prototype +title: "Prototype Pattern in Java: Mastering Object Cloning for Efficient Instantiation" +shortTitle: Prototype +description: "Explore the Prototype design pattern in Java with a comprehensive guide on its implementation, advantages, and real-world applications. Learn how to efficiently clone objects and manage object creation in your Java applications." category: Creational language: en tag: - - Gang Of Four - - Instantiation - - Object composition - - Polymorphism + - Gang Of Four + - Instantiation + - Object composition + - Polymorphism --- ## Also known as * Clone -## Intent +## Intent of Prototype Design Pattern -The Prototype pattern is used to specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype. +The Prototype pattern is used to specify the kinds of objects to create using a prototypical instance, and create new instances through object cloning. -## Explanation +## Detailed Explanation of Prototype Pattern with Real-World Examples Real-world example @@ -33,7 +35,7 @@ Wikipedia says > The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. -**Programmatic Example** +## Programmatic Example of Prototype Pattern in Java In Java, the prototype pattern is recommended to be implemented as follows. First, create an interface with a method for cloning objects. In this example, `Prototype` interface accomplishes this with its `copy` method. @@ -150,11 +152,11 @@ Here's the console output from running the example. 08:36:19.014 [main] INFO com.iluwatar.prototype.App -- Orcish wolf attacks with laser ``` -## Class diagram +## Detailed Explanation of Prototype Pattern with Real-World Examples ![alt text](./etc/prototype.urm.png "Prototype pattern class diagram") -## Applicability +## When to Use the Prototype Pattern in Java * When the classes to instantiate are specified at run-time, for example, by dynamic loading. * To avoid building a class hierarchy of factories that parallels the class hierarchy of products. @@ -162,16 +164,18 @@ Here's the console output from running the example. * When object creation is expensive compared to cloning. * When the concrete classes to instantiate are unknown until runtime. -## Known uses +## Real-World Applications of Prototype Pattern in Java * In Java, the `Object.clone()` method is a classic implementation of the Prototype pattern. * GUI libraries often use prototypes for creating buttons, windows, and other widgets. * In game development, creating multiple objects (like enemy characters) with similar attributes. -## Consequences +## Benefits and Trade-offs of Prototype Pattern Benefits: +Leveraging the Prototype pattern in Java applications + * Hides the complexities of instantiating new objects. * Reduces the number of classes. * Allows adding and removing objects at runtime. @@ -181,13 +185,13 @@ Trade-offs: * Requires implementing a cloning mechanism which might be complex. * Deep cloning can be difficult to implement correctly, especially if the classes have complex object graphs with circular references. -## Related patterns +## Related Java Design Patterns * [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Both involve creating objects, but Prototype uses cloning of a prototype instance whereas Abstract Factory creates objects using factory methods. * [Singleton](https://java-design-patterns.com/patterns/singleton/): Singleton can use a prototype for creating instances if it allows cloning of its single instance. * [Composite](https://java-design-patterns.com/patterns/composite/): Prototypes are often used within composites to allow for dynamic creation of component trees. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/proxy/README.md b/proxy/README.md index 9333453cc..f237fb47e 100644 --- a/proxy/README.md +++ b/proxy/README.md @@ -1,26 +1,28 @@ --- -title: Proxy +title: "Proxy Pattern in Java: Enhancing Security and Control with Smart Proxies" +shortTitle: Proxy +description: "Explore the Proxy design pattern in Java with detailed examples. Learn how it provides controlled access, facilitates lazy initialization, and ensures security. Ideal for developers looking to implement advanced Java techniques." category: Structural language: en tag: - - Decoupling - - Encapsulation - - Gang Of Four - - Lazy initialization - - Proxy - - Security - - Wrapping + - Decoupling + - Encapsulation + - Gang Of Four + - Lazy initialization + - Proxy + - Security + - Wrapping --- ## Also known as * Surrogate -## Intent +## Intent of Proxy Design Pattern -Provide a surrogate or placeholder for another object to control access to it. +The Proxy pattern in Java provides a surrogate or placeholder to effectively control access to an object, enhancing security and resource management. -## Explanation +## Detailed Explanation of Proxy Pattern with Real-World Examples Real-world example @@ -28,13 +30,13 @@ Real-world example In plain words -> Using the proxy pattern, a class represents the functionality of another class. +> Utilizing the Java Proxy pattern, a class encapsulates the functionality of another, streamlining access control and operation efficiency. Wikipedia says > A proxy, in its most general form, is a class functioning as an interface to something else. A proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes. Use of the proxy can simply be forwarding to the real object, or can provide additional logic. In the proxy extra functionality can be provided, for example caching when operations on the real object are resource intensive, or checking preconditions before operations on the real object are invoked. -**Programmatic Example** +## Programmatic Example of Proxy Pattern in Java Imagine a tower where the local wizards go to study their spells. The ivory tower can only be accessed through a proxy which ensures that only the first three wizards can enter. Here the proxy represents the functionality of the tower and adds access control to it. @@ -123,7 +125,7 @@ Program output: 08:42:06.186 [main] INFO com.iluwatar.proxy.WizardTowerProxy -- Brown wizard is not allowed to enter! ``` -## Applicability +## When to Use the Proxy Pattern in Java Proxy is applicable whenever there is a need for a more versatile or sophisticated reference to an object than a simple pointer. Here are several common situations in which the Proxy pattern is applicable. Typically, the proxy pattern is used to @@ -134,7 +136,7 @@ Proxy is applicable whenever there is a need for a more versatile or sophisticat * Count references to an object * Provide a local representation for an object that is in a different address space. -## Known Uses +## Real-World Applications of Proxy Pattern in Java * Virtual Proxies: In applications that need heavy resources like large images or complex calculations, virtual proxies can be used to instantiate objects only when needed. * Remote Proxies: Used in remote method invocation (RMI) to manage interactions with remote objects. @@ -144,7 +146,7 @@ Proxy is applicable whenever there is a need for a more versatile or sophisticat * Mocking frameworks [Mockito](https://site.mockito.org/),[Powermock](https://powermock.github.io/), [EasyMock](https://easymock.org/) * [UIAppearance](https://developer.apple.com/documentation/uikit/uiappearance) -## Consequences +## Benefits and Trade-offs of Proxy Pattern Benefits: @@ -157,14 +159,14 @@ Trade-offs: * Overhead: Adding a proxy introduces additional layers that might add overhead. * Complexity: Increases the complexity of the system by adding more classes. -## Related Patterns +## Related Java Design Patterns * [Adapter](https://java-design-patterns.com/patterns/adapter/): The Adapter pattern changes the interface of an existing object, whereas Proxy provides the same interface as the original object. * [Ambassador](https://java-design-patterns.com/patterns/ambassador/): Ambassador is similar to Proxy as it acts as an intermediary, especially in remote communications, enhancing access control and monitoring. * [Decorator](https://java-design-patterns.com/patterns/decorator/): Both Decorator and Proxy patterns provide a level of indirection, but the Decorator pattern adds responsibilities to objects dynamically, while Proxy controls access. * [Facade](https://java-design-patterns.com/patterns/facade/): Facade provides a simplified interface to a complex subsystem, while Proxy controls access to a particular object. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) diff --git a/queue-based-load-leveling/README.md b/queue-based-load-leveling/README.md index ce11b4fac..a72d39ea3 100644 --- a/queue-based-load-leveling/README.md +++ b/queue-based-load-leveling/README.md @@ -1,16 +1,18 @@ --- -title: Queue-Based Load Leveling +title: "Queue-Based Load Leveling Pattern in Java: Balancing Workloads for Scalable Performance" +shortTitle: Queue-Based Load Leveling +description: "Master the Queue-Based Load Leveling pattern in Java with our comprehensive guide. Learn how to enhance system resilience, manage workload efficiently, and prevent overload with effective asynchronous buffering techniques." category: Resilience language: en tag: - - Asynchronous - - Buffering - - Decoupling - - Fault tolerance - - Messaging - - Scalability - - Synchronization - - Thread management + - Asynchronous + - Buffering + - Decoupling + - Fault tolerance + - Messaging + - Scalability + - Synchronization + - Thread management --- ## Also known as @@ -18,15 +20,15 @@ tag: * Load Leveling * Message Queuing -## Intent +## Intent of Queue-Based Load Leveling Design Pattern -Queue-Based Load Leveling aims to manage the load in a system by using a queue to level the workload between producers and consumers, ensuring that heavy loads are handled smoothly without overwhelming the system. +The Queue-Based Load Leveling pattern expertly manages system load balancing in Java by utilizing a queue to efficiently distribute the workload among producers and consumers, enhancing system performance and scalability. -## Explanation +## Detailed Explanation of Queue-Based Load Leveling Pattern with Real-World Examples Real-world example -> Imagine a popular restaurant with a limited number of kitchen staff (consumers) and a large number of customers placing orders (producers). During peak hours, if all customers were served immediately, the kitchen would be overwhelmed, leading to long wait times and potential mistakes in orders. To manage this, the restaurant implements a queue-based load leveling system using a ticketing machine. +> In a practical scenario, akin to a bustling restaurant, Queue-Based Load Leveling serves as a system optimization strategy, where orders are systematically queued to maintain high service quality and efficiency. During peak hours, if all customers were served immediately, the kitchen would be overwhelmed, leading to long wait times and potential mistakes in orders. To manage this, the restaurant implements a queue-based load leveling system using a ticketing machine. > > When customers place orders, they receive a ticket number and their order is placed in a queue. The kitchen staff then processes orders one at a time in the order they were received. This ensures that the kitchen can handle the workload at a manageable pace, preventing overload and maintaining service quality. Customers wait comfortably knowing their order is in line and will be handled efficiently, even during the busiest times. @@ -38,9 +40,9 @@ Wikipedia says > Message Queues are essential components for inter-process communication (IPC) and inter-thread communication, using queues to manage the passing of messages. They help in decoupling producers and consumers, allowing asynchronous processing, which is a key aspect of the Queue-Based Load Leveling pattern. -**Programmatic Example** +## Programmatic Example of Queue-Based Load Leveling Pattern in Java -The Queue-Based Load Leveling pattern helps to manage high-volume, sporadic bursts of tasks that can overwhelm a system. It uses a queue as a buffer to hold tasks, decoupling the task generation from task processing. The tasks are then processed at a manageable rate. +The Queue-Based Load Leveling pattern helps to manage high-volume, sporadic bursts of tasks that can overwhelm a system. It uses a queue as a buffer to hold tasks, decoupling the task generation from task processing. Tasks are processed at a controlled rate, ensuring optimal load management and fault tolerance, crucial for maintaining robust system architecture. First, let's look at the `MessageQueue` and `Message` classes. The `MessageQueue` acts as a buffer, storing messages until they are retrieved by the `ServiceExecutor`. The `Message` represents the tasks to be processed. @@ -174,19 +176,19 @@ Running the application produces the following console output: [pool-1-thread-2] ERROR ServiceExecutor - sleep interrupted ``` -## Applicability +## When to Use the Queue-Based Load Leveling Pattern in Java * When there are variable workloads, and you need to ensure that peak loads do not overwhelm the system * In distributed systems where tasks are produced at a different rate than they are consumed * For decoupling producers and consumers in an asynchronous messaging system -## Known Uses +## Real-World Applications of Queue-Based Load Leveling Pattern in Java * Amazon Web Services (AWS) Simple Queue Service (SQS) * RabbitMQ * Java Message Service (JMS) in enterprise Java applications -## Consequences +## Benefits and Trade-offs of Queue-Based Load Leveling Pattern Benefits: @@ -200,14 +202,14 @@ Trade-offs: * May introduce latency as messages need to be queued and dequeued * Requires additional components (queues) to be managed and monitored -## Related Patterns +## Related Java Design Patterns * Asynchronous Messaging: Queue-Based Load Leveling uses asynchronous messaging to decouple producers and consumers * [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/): Often used in conjunction with Queue-Based Load Leveling to prevent system overloads by temporarily halting message processing * [Producer-Consumer](https://java-design-patterns.com/patterns/producer-consumer/): Queue-Based Load Leveling is a specific application of the Producer-Consumer pattern where the queue serves as the intermediary * [Retry](https://java-design-patterns.com/patterns/retry/): Works with Queue-Based Load Leveling to handle transient failures by retrying failed operations -## Credits +## References and Credits * [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/3y6yv1z) * [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/3WcFVui) diff --git a/reactor/README.md b/reactor/README.md index c2f74c107..50ee482cb 100644 --- a/reactor/README.md +++ b/reactor/README.md @@ -1,16 +1,18 @@ --- -title: Reactor +title: "Reactor Pattern in Java: Mastering Non-blocking Event-Driven Architectures" +shortTitle: Reactor +description: "Explore the Reactor pattern in Java: Learn how this concurrency model handles multiple simultaneous I/O operations using a single thread for improved performance and scalability. Ideal for developers building high-performance network applications." category: Concurrency language: en tag: - - Asynchronous - - Event-driven - - Fault tolerance - - Messaging - - Reactive - - Scalability - - Synchronization - - Thread management + - Asynchronous + - Event-driven + - Fault tolerance + - Messaging + - Reactive + - Scalability + - Synchronization + - Thread management --- ## Also known as @@ -18,15 +20,15 @@ tag: * Dispatcher * Notifier -## Intent +## Intent of Reactor Design Pattern -Handle service requests that are delivered concurrently to a service handler by one or more inputs. +The Reactor pattern is designed to handle concurrent service requests efficiently, using a single or limited number of threads, making it a cornerstone for asynchronous, event-driven systems. -## Explanation +## Detailed Explanation of Reactor Pattern with Real-World Examples Real-world example -> Imagine a busy restaurant kitchen where multiple orders come in from different tables at the same time. Instead of each chef handling one order at a time, there is a head chef who acts as the dispatcher. The head chef receives all the orders and decides which chef will handle which part of each order, ensuring that all chefs are utilized efficiently. This way, the kitchen can handle many orders simultaneously, ensuring that dishes are prepared quickly and efficiently without any one chef becoming a bottleneck. This setup is analogous to the Reactor pattern, where the head chef dispatches tasks (events) to various chefs (event handlers) to process multiple tasks concurrently. +> This design pattern is analogous to a head chef in a busy kitchen, demonstrating its ability to manage high-scalability demands and maintain efficient task distribution in multithreaded environments. Instead of each chef handling one order at a time, there is a head chef who acts as the dispatcher. The head chef receives all the orders and decides which chef will handle which part of each order, ensuring that all chefs are utilized efficiently. This way, the kitchen can handle many orders simultaneously, ensuring that dishes are prepared quickly and efficiently without any one chef becoming a bottleneck. This setup is analogous to the Reactor pattern, where the head chef dispatches tasks (events) to various chefs (event handlers) to process multiple tasks concurrently. In plain words @@ -36,7 +38,7 @@ Wikipedia says > The reactor software design pattern is an event handling strategy that can respond to many potential service requests concurrently. The pattern's key component is an event loop, running in a single thread or process, which demultiplexes incoming requests and dispatches them to the correct request handler. -**Programmatic Example** +## Programmatic Example of Reactor Pattern in Java The Reactor design pattern is a concurrency model that efficiently handles multiple simultaneous I/O operations using a single or a limited number of threads. It is particularly useful in scenarios where an application needs to handle multiple clients sending service requests concurrently. @@ -155,22 +157,21 @@ Running the code produces the following output: This concludes our detailed explanation of the Reactor design pattern. The Reactor pattern allows us to handle multiple simultaneous I/O operations efficiently using a single or a limited number of threads. -## Class diagram +## Detailed Explanation of Reactor Pattern with Real-World Examples ![Reactor](./etc/reactor.png "Reactor") -## Applicability +## When to Use the Reactor Pattern in Java -* Use the Reactor pattern when you need to handle multiple simultaneous I/O operations efficiently. -* Ideal for applications requiring high scalability and low-latency, such as web servers and networking frameworks. +Employ the Reactor pattern in scenarios requiring low-latency and high-throughput in server-side applications, making it an essential strategy for modern networking frameworks and web servers. -## Known Uses +## Real-World Applications of Reactor Pattern in Java * Netty: An asynchronous event-driven network application framework for rapid development of maintainable high-performance protocol servers and clients. * Akka: A toolkit and runtime for building concurrent, distributed, and fault-tolerant applications on the JVM. * Java NIO (New I/O): Provides non-blocking I/O operations, allowing a single thread to manage multiple channels. -## Consequences +## Benefits and Trade-offs of Reactor Pattern Benefits: @@ -184,13 +185,13 @@ Trade-offs: * Debugging and maintaining asynchronous code can be challenging. * Potential difficulty in ensuring thread safety and avoiding race conditions. -## Related Patterns +## Related Java Design Patterns * [Observer](https://java-design-patterns.com/patterns/observer/): Reactor uses the Observer pattern for handling events where event handlers are notified of changes. * Proactor: Similar to Reactor but handles asynchronous I/O completion rather than readiness. * [Command](https://java-design-patterns.com/patterns/command/): Encapsulates a request as an object, allowing parameterization and queuing of requests. -## Credits +## References and Credits * [Java Concurrency in Practice](https://amzn.to/4aRMruW) * [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V) diff --git a/registry/README.md b/registry/README.md index 9e5ef6955..aa40bb809 100644 --- a/registry/README.md +++ b/registry/README.md @@ -1,21 +1,23 @@ --- -title: Registry +title: "Registry Pattern in Java: Implementing a Centralized Control Mechanism for Java Objects" +shortTitle: Registry +description: "Explore the Registry design pattern in Java: Learn how it centralizes object management for improved access and control. Perfect for software developers and architects looking to optimize Java application architecture." category: Creational language: en tag: - - API design - - Data access - - Decoupling - - Dependency management - - Enterprise patterns - - Instantiation + - API design + - Data access + - Decoupling + - Dependency management + - Enterprise patterns + - Instantiation --- -## Intent +## Intent of Registry Design Pattern -To centralize the creation and management of a global set of objects, providing a single point of access and ensuring controlled instantiation. +Registry Design Pattern centralizes the creation and management of a global set of objects, providing a single point of access and ensuring controlled instantiation. -## Explanation +## Detailed Explanation of Registry Pattern with Real-World Examples Real-world example @@ -36,7 +38,7 @@ wiki.c2.com says > A registry is a global association from keys to objects, allowing the objects to be reached from anywhere. It involves two methods: one that takes a key and an object and add objects to the registry and one that takes a key and returns the object for the key. It's similar to the MultitonPattern, but doesn't restrict instances to only those in the registry. -**Programmatic Example** +## Programmatic Example of Registry Pattern in Java The Registry design pattern is a well-known pattern used in software design where objects are stored and provide a global point of access to them. This pattern is particularly useful when you need to manage a global collection of objects, decouple the creation of objects from their usage, ensure a controlled lifecycle for objects, and avoid redundant creation of objects. @@ -110,23 +112,25 @@ Running the example produces the following output: 09:55:31.113 [main] INFO com.iluwatar.registry.App -- Julia Customer{id='2', name='Julia'} ``` -## Applicability +## When to Use the Registry Pattern in Java * When you need to manage a global collection of objects. * When you need to decouple the creation of objects from their usage. * When you need to ensure a controlled lifecycle for objects, such as services or resources. * When you want to avoid redundant creation of objects. -## Known Uses +## Real-World Applications of Registry Pattern in Java * Managing database connections in an enterprise application. * Providing a central place to register and retrieve services or components in a modular application. * Creating a central configuration registry that various parts of an application can access. -## Consequences +## Benefits and Trade-offs of Registry Pattern Benefits: +Key advantages of adopting the Registry pattern in Java + * Centralizes object management, making the application easier to maintain. * Promotes reuse and sharing of objects, which can reduce memory footprint and initialization time. * Facilitates decoupling between components. @@ -145,7 +149,7 @@ Trade-offs: * [Dependency Injection](https://java-design-patterns.com/patterns/dependency-injection/): Provides an alternative method for managing dependencies, which can sometimes replace the need for a Registry. * [Multiton](https://java-design-patterns.com/patterns/multiton/): Similar to the Registry in that it manages multiple instances, but does so based on keys, ensuring only one instance per key. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/repository/README.md b/repository/README.md index cd569348a..e2be527a2 100644 --- a/repository/README.md +++ b/repository/README.md @@ -1,19 +1,21 @@ --- -title: Repository +title: "Repository Pattern in Java: Simplifying Data Access with Abstracted Persistence" +shortTitle: Repository +description: "Learn how the Repository design pattern in Java enhances data access and abstraction, simplifying application architecture while boosting maintainability and decoupling. Ideal for Java developers seeking streamlined data management solutions." category: Data access language: en tag: - - Abstraction - - Data access - - Decoupling - - Persistence + - Abstraction + - Data access + - Decoupling + - Persistence --- -## Intent +## Intent of Repository Design Pattern -To provide a central location for data access logic, abstracting the details of data storage and retrieval from the rest of the application. +The Repository design pattern acts as a central hub for managing all Java data access logic, abstracting the details of data storage and retrieval from the rest of the application. -## Explanation +## Detailed Explanation of Repository Pattern with Real-World Examples Real-world example @@ -27,7 +29,7 @@ In plain words > Repositories are classes or components that encapsulate the logic required to access data sources. They centralize common data access functionality, providing better maintainability and decoupling the infrastructure or technology used to access databases from the domain model layer. -**Programmatic Example** +## Programmatic Example of Repository Pattern in Java Let's first look at the person entity that we need to persist. @@ -173,26 +175,26 @@ INFO [2024-05-27 07:00:32,881] com.iluwatar.repository.App: Person(id=3, name=J INFO [2024-05-27 07:00:32,881] com.iluwatar.repository.App: Person(id=4, name=Terry, surname=Law, age=36) ``` -## Applicability +## When to Use the Repository Pattern in Java -* Use when you want to decouple the business logic and data access layers of your application. +* Apply the Repository pattern when aiming to decouple business logic from data access layers in Java applications, ensuring more flexible and maintainable code. * Suitable for scenarios where multiple data sources might be used and the business logic should remain unaware of the data source specifics. * Ideal for testing purposes as it allows the use of mock repositories. -## Tutorials +## Repository Pattern Java Tutorials * [Don’t use DAO, use Repository (Thinking in Objects)](http://thinkinginobjects.com/2012/08/26/dont-use-dao-use-repository/) * [Advanced Spring Data JPA - Specifications and Querydsl (Spring)](https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/) * [Repository Pattern Benefits and Spring Implementation (Stack Overflow)](https://stackoverflow.com/questions/40068965/repository-pattern-benefits-and-spring-implementation) * [Design patterns that I often avoid: Repository pattern (InfoWorld)](https://www.infoworld.com/article/3117713/design-patterns-that-i-often-avoid-repository-pattern.html) -## Known Uses +## Real-World Applications of Repository Pattern in Java -* Spring Data JPA: Provides a repository abstraction over JPA implementations. +* Spring Data JPA exemplifies the Repository pattern by providing a robust repository abstraction layer over JPA implementations, tailored for Java. * Hibernate: Often used with DAOs that act as repositories for accessing and managing data entities. * Java EE applications frequently utilize repository patterns to separate business logic from data access code. -## Consequences +## Benefits and Trade-offs of Repository Pattern Benefits: @@ -205,12 +207,12 @@ Trade-offs: * Introduces additional layers of abstraction which might add complexity. * Potential performance overhead due to the abstraction layer. -## Related Patterns +## Related Java Design Patterns * [Data Mapper](https://java-design-patterns.com/patterns/data-mapper/): While Repository handles data access, Data Mapper is responsible for transferring data between objects and a database, maintaining the data integrity. * [Unit of Work](https://java-design-patterns.com/patterns/unit-of-work/): Often used alongside Repository to manage transactions and track changes to the data. -## Credits +## References and Credits * [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3wlDrze) * [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/resource-acquisition-is-initialization/README.md b/resource-acquisition-is-initialization/README.md index 7bbaab3fc..5c6105dce 100644 --- a/resource-acquisition-is-initialization/README.md +++ b/resource-acquisition-is-initialization/README.md @@ -1,11 +1,13 @@ --- -title: Resource Acquisition Is Initialization +title: "Resource Acquisition Is Initialization in Java: Ensuring Safe Resource Management" +shortTitle: Resource Acquisition Is Initialization (RAII) +description: "Discover how the RAII (Resource Acquisition Is Initialization) pattern can streamline resource management in Java. Learn to implement RAII with practical examples and improve code reliability and maintenance." category: Resource management language: en tag: - - Encapsulation - - Memory management - - Resource management + - Encapsulation + - Memory management + - Resource management --- ## Also known as @@ -13,11 +15,11 @@ tag: * RAII * Scope-based Resource Management -## Intent +## Intent of Resource Acquisition Is Initialization Design Pattern -Ensure that resources are properly released when they are no longer needed by tying the resource management to object lifetime. +Ensure efficient Java resource management by tying the resource lifecycle to object lifetime, utilizing the RAII pattern. -## Explanation +## Detailed Explanation of Resource Acquisition Is Initialization Pattern with Real-World Examples Real-world example @@ -25,13 +27,13 @@ Real-world example In plain words -> Resource Acquisition is Initialization allows for exception-safe resource handling and means that objects are able to manage themselves without other code to inform them that a clean-up is required after use. +> The RAII pattern in Java allows for exception-safe resource management, ensuring robust handling of critical resources. Wikipedia says > Resource acquisition is initialization (RAII) is a programming idiom used in several object-oriented, statically typed programming languages to describe a particular language behavior. Resource allocation (or acquisition) is done during object creation (specifically initialization), by the constructor, while resource deallocation (release) is done during object destruction (specifically finalization), by the destructor. -**Programmatic Example** +## Programmatic Example of RAII Pattern in Java The RAII pattern is a common idiom used in software design where the acquisition of a resource is done during object creation (initialization), and the release of the resource is done during object destruction. This pattern is particularly useful in dealing with resource leaks and is critical in writing exception-safe code in C++. In Java, RAII is achieved with try-with-resources statement and interfaces `java.io.Closeable` and `AutoCloseable`. @@ -107,18 +109,18 @@ The console output: 10:07:14.835 [main] INFO com.iluwatar.resource.acquisition.is.initialization.TreasureChest -- Treasure chest closes. ``` -## Applicability +## When to Use the Resource Acquisition Is Initialization Pattern in Java -* Use RAII when resources such as file handles, network connections, or memory need to be managed and automatically released. +* Implement RAII in Java applications to manage essential resources such as file handles, network connections, and memory seamlessly. * Suitable in environments where deterministic resource management is crucial, such as real-time systems or applications with strict resource constraints. -## Known Uses +## Real-World Applications of RAII Pattern in Java * Java `try-with-resources` statement: Ensures that resources are closed automatically at the end of the statement. * Database connections: Using connection pools where the connection is obtained at the beginning of a scope and released at the end. * File I/O: Automatically closing files using `try-with-resources`. -## Consequences +## Benefits and Trade-offs of Resource Acquisition Is Initialization Pattern Benefits: @@ -131,11 +133,11 @@ Trade-offs: * May introduce complexity in understanding object lifetimes. * Requires careful design to ensure all resources are correctly encapsulated. -## Related Patterns +## Related Java Design Patterns * [Object Pool](https://java-design-patterns.com/patterns/object-pool/): Manages a pool of reusable objects to optimize resource allocation and performance, often used for resources that are expensive to create and manage. -## Credits +## References and Credits * [Effective Java](https://amzn.to/4cGk2Jz) * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) diff --git a/retry/README.md b/retry/README.md index 92d701bd3..193866e43 100644 --- a/retry/README.md +++ b/retry/README.md @@ -1,12 +1,14 @@ --- -title: Retry +title: "Retry Pattern in Java: Building Fault-Tolerant Systems with Adaptive Retries" +shortTitle: Retry +description: "Explore the Retry pattern in Java for robust software design. Learn how to implement fault tolerance and improve application reliability through transparent retries of operations involving external communications like network requests." category: Resilience language: en tag: - - Fault tolerance - - Performance - - Retry - - Resilience + - Fault tolerance + - Performance + - Retry + - Resilience --- ## Also known as @@ -14,11 +16,11 @@ tag: * Retry Logic * Retry Mechanism -## Intent +## Intent of Retry Design Pattern -Transparently retry certain operations that involve communication with external resources, particularly over the network, isolating calling code from the retry implementation details. +The Retry pattern in Java transparently retries certain operations that involve communication with external resources, particularly over the network, isolating calling code from the retry implementation details. It is crucial for developing resilient software systems that handle transient failures gracefully. -## Explanation +## Detailed Explanation of Retry Pattern with Real-World Examples Real-world example @@ -32,9 +34,9 @@ In plain words > Enable an application to handle transient failures when it tries to connect to a service or network resource, by transparently retrying a failed operation. This can improve the stability of the application. -**Programmatic Example** +## Programmatic Example of Retry Pattern in Java -The Retry design pattern is a resilience pattern that allows an application to retry an operation in the expectation that it'll succeed. This pattern is particularly useful when the application is connecting to a network service or a remote resource, where temporary failures are common. +The Retry design pattern is a resilience pattern that allows an application to transparently attempt to execute operations multiple times in the expectation that it'll succeed. This pattern is particularly useful when the application is connecting to a network service or a remote resource, where temporary failures are common. First, we have a `BusinessOperation` interface that represents an operation that can be performed and might throw a `BusinessException`. @@ -189,18 +191,20 @@ Running the code produces the following console output. This way, the Retry pattern allows the application to handle temporary failures gracefully, improving its resilience and reliability. -## Applicability +## When to Use the Retry Pattern in Java -* Use when operations can fail transiently, such as network calls, database connections, or external service integrations. -* Ideal for scenarios where the likelihood of transient failure is high but the cost of retries is low. +Applying the Retry pattern is particularly effective -## Known Uses +* When operations can fail transiently, such as network calls, database connections, or external service integrations. +* In scenarios where the likelihood of transient failure is high but the cost of retries is low. + +## Real-World Applications of Retry Pattern in Java * In network communication libraries to handle transient failures. * Database connection libraries to manage temporary outages or timeouts. * APIs interacting with third-party services that may be temporarily unavailable. -## Consequences +## Benefits and Trade-offs of Retry Pattern Benefits: @@ -213,11 +217,11 @@ Trade-offs: * Can lead to resource exhaustion if not managed properly. * Requires careful configuration of retry parameters to avoid exacerbating the problem. -## Related Patterns +## Related Java Design Patterns * [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/): Used to stop the flow of requests to an external service after a failure threshold is reached, preventing system overload. -## Credits +## References and Credits * [Cloud Design Patterns: Prescriptive Architecture Guidance for Cloud Applications](https://amzn.to/4dLvowg) * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) diff --git a/role-object/README.md b/role-object/README.md index a45ffc237..98b29bb28 100644 --- a/role-object/README.md +++ b/role-object/README.md @@ -1,22 +1,24 @@ --- -title: Role Object +title: "Role Object Pattern in Java: Enhancing Flexibility in Object Roles and Behaviors" +shortTitle: Role Object +description: "Explore the Role Object design pattern in Java, which allows objects to dynamically assume various roles, enhancing flexibility and system adaptability. Ideal for developers looking to implement dynamic behavior in applications." category: Structural language: en tag: - - Abstraction - - Decoupling - - Extensibility - - Interface - - Object composition - - Polymorphism - - Runtime + - Abstraction + - Decoupling + - Extensibility + - Interface + - Object composition + - Polymorphism + - Runtime --- -## Intent +## Intent of Role Object Design Pattern -To dynamically assign roles to objects, enabling them to change behavior and responsibilities at runtime. +Efficiently assign dynamic roles to Java objects, enabling them to adapt behaviors and responsibilities on-the-fly, optimizing runtime flexibility. -## Explanation +## Detailed Explanation of Role Object Pattern with Real-World Examples Real-world example @@ -24,13 +26,13 @@ Real-world example In plain words -> The Role Object pattern suggests to model context-specific views of an object as separate role objects which are dynamically attached to and removed from the core object. +> The Role Object pattern in Java models context-specific views through separate, dynamically managed role objects, enhancing modular design and runtime adaptability. wiki.c2.com says > Adapt an object to different client’s needs through transparently attached role objects, each one representing a role the object has to play in that client’s context. The object manages its role set dynamically. By representing roles as individual objects, different contexts are kept separate and system configuration is simplified. -**Programmatic Example** +## Programmatic Example of Role Object Pattern in Java The Role Object design pattern is a pattern that suggests modeling context-specific views of an object as separate role objects. These role objects are dynamically attached to and removed from the core object. The resulting composite object structure, consisting of the core and its role objects, is called a subject. A subject often plays several roles and the same role is likely to be played by different subjects. @@ -140,23 +142,23 @@ Running the example outputs: 10:22:02.575 [main] INFO com.iluwatar.roleobject.ApplicationRoleObject -- Borrower Johny wants to get some money. ``` -## Applicability +## When to Use the Role Object Pattern in Java * When an object needs to change its behavior dynamically based on its role. * When multiple objects share common behaviors but should exhibit those behaviors differently based on their roles. * In scenarios where roles can be added, removed, or changed at runtime. -## Known Uses +## Real-World Applications of Role Object Pattern in Java * User role management in applications where users can have different permissions and responsibilities. * Game character roles where characters can take on different roles (e.g., healer, warrior, mage) dynamically. * Workflow systems where tasks can be assigned different roles depending on the context. -## Consequences +## Benefits and Trade-offs of Role Object Pattern Benefits: -* Promotes flexibility by allowing objects to change roles dynamically. +* Enhances software flexibility by enabling Java objects to dynamically switch roles, catering to evolving application needs. * Enhances code maintainability by decoupling role-specific behaviors from core object logic. * Facilitates the addition of new roles without modifying existing code. @@ -165,13 +167,13 @@ Trade-offs: * Increases complexity due to the need for managing multiple role objects. * Potential performance overhead due to the dynamic nature of role assignment and behavior switching. -## Related Patterns +## Related Java Design Patterns * [Strategy](https://java-design-patterns.com/patterns/strategy/): Similar in dynamically changing an object's behavior, but Role Object focuses on roles that can be combined. * [Decorator](https://java-design-patterns.com/patterns/decorator/): Both can add behaviors to objects, but Role Object allows for dynamic role switching rather than static enhancement. * [State](https://java-design-patterns.com/patterns/state/): Manages state transitions similar to role changes, but Role Object deals more with behavioral roles rather than states. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Pattern-Oriented Software Architecture Volume 1: A System of Patterns](https://amzn.to/3xZ1ELU) diff --git a/saga/README.md b/saga/README.md index 72a6d369d..47709dd68 100644 --- a/saga/README.md +++ b/saga/README.md @@ -1,21 +1,23 @@ --- -title: Saga +title: "Saga Pattern in Java: Mastering Long-Running Transactions in Distributed Systems" +shortTitle: Saga +description: "Explore the Saga pattern in Java for managing distributed transactions across microservices with resilience and fault tolerance. Learn how the Saga pattern ensures data consistency without locking resources." category: Resilience language: en tag: - - Asynchronous - - Decoupling - - Fault tolerance - - Integration - - Microservices - - Transactions + - Asynchronous + - Decoupling + - Fault tolerance + - Integration + - Microservices + - Transactions --- -## Intent +## Intent of Saga Design Pattern To manage and coordinate distributed transactions across multiple services in a fault-tolerant and reliable manner. -## Explanation +## Detailed Explanation of Saga Pattern with Real-World Examples Real-world example @@ -23,13 +25,13 @@ Real-world example In plain words -> The Saga pattern coordinates distributed transactions across microservices using a sequence of events and compensating actions to ensure data consistency and fault tolerance. +> The Saga pattern in Java coordinates distributed transactions across microservices using a sequence of events and compensating actions to ensure data consistency and fault tolerance. Wikipedia says > Long-running transactions (also known as the saga interaction pattern) are computer database transactions that avoid locks on non-local resources, use compensation to handle failures, potentially aggregate smaller ACID transactions (also referred to as atomic transactions), and typically use a coordinator to complete or abort the transaction. In contrast to rollback in ACID transactions, compensation restores the original state, or an equivalent, and is business-specific. For example, the compensating action for making a hotel reservation is canceling that reservation. -**Programmatic Example** +## Programmatic Example of Saga Pattern in Java The Saga design pattern is a sequence of local transactions where each transaction updates data within a single service. It's particularly useful in a microservices architecture where each service has its own database. The Saga pattern ensures data consistency and fault tolerance across services. Here are the key components of the Saga pattern: @@ -158,19 +160,19 @@ Running the example produces the following console output: This is a basic example of how to use the Saga design pattern. In a real-world application, the `Saga` class would manage the sequence of local transactions, ensuring that each transaction is performed in the correct order and that the Saga is rolled back if a transaction fails. -## Applicability +## When to Use the Saga Pattern in Java * When you have a complex transaction that spans multiple microservices. * When you need to ensure data consistency across services without using a traditional two-phase commit. * When you need to handle long-running transactions in an asynchronous manner. -## Known Uses +## Real-World Applications of Saga Pattern in Java * E-commerce platforms managing orders, inventory, and payment services. * Banking systems coordinating between account debits and credits across multiple services. * Travel booking systems coordinating flights, hotels, and car rentals. -## Consequences +## Benefits and Trade-offs of Saga Pattern Benefits: @@ -184,12 +186,12 @@ Trade-offs: * Requires careful design to handle partial failures and rollback scenarios. * Potential latency due to asynchronous nature. -## Related Patterns +## Related Java Design Patterns * [Event Sourcing](https://java-design-patterns.com/patterns/event-sourcing/): Used to capture state changes as a sequence of events, which can complement the Saga pattern by providing a history of state changes. * [Command Query Responsibility Segregation (CQRS)](https://java-design-patterns.com/patterns/cqrs/): Can be used in conjunction with the Saga pattern to separate command and query responsibilities, improving scalability and fault tolerance. -## Credits +## References and Credits * [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/3y6yv1z) * [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/3WcFVui) diff --git a/separated-interface/README.md b/separated-interface/README.md index baaeb8697..1b26f40aa 100644 --- a/separated-interface/README.md +++ b/separated-interface/README.md @@ -1,11 +1,13 @@ --- -title: Separated Interface +title: "Separated Interface Pattern in Java: Streamlining Java Development with Interface Isolation" +shortTitle: Separated Interface +description: "Explore the Separated Interface design pattern in Java: Enhance software flexibility and maintainability by decoupling interfaces from implementations. Ideal for developers looking to improve code scalability and adaptability." category: Structural language: en tag: - - API design - - Decoupling - - Interface + - API design + - Decoupling + - Interface --- ## Also known as @@ -13,11 +15,11 @@ tag: * API Segregation * Client-Server Interface -## Intent +## Intent of Separated Interface Design Pattern -To define a client interface in a separate package from its implementation to allow for easier swapping of implementations and better separation of concerns. +The Separated Interface design pattern defines a client interface in a separate package from its implementation to allow for easier swapping of implementations and better separation of concerns. -## Explanation +## Detailed Explanation of Separated Interface Pattern with Real-World Examples Real-world example @@ -29,9 +31,9 @@ In plain words > Defines a client interface separate from its implementation to allow for flexible and interchangeable components. -**Programmatic Example** +## Programmatic Example of Separated Interface Pattern in Java -The Separated Interface design pattern is a software design pattern that encourages the separation of the definition of an interface from its implementation. This allows the client to be completely unaware of the implementation, promoting loose coupling and enhancing flexibility. +The Java Separated Interface design pattern is a crucial software architecture strategy that promotes separating the interface definition from its implementation, crucial for enhancing system flexibility and scalability. This allows the client to be completely unaware of the implementation, promoting loose coupling and enhancing flexibility. In the given code, the `InvoiceGenerator` class is the client that uses the `TaxCalculator` interface to calculate tax. The `TaxCalculator` interface is implemented by two classes: `ForeignTaxCalculator` and `DomesticTaxCalculator`. These implementations are injected into the `InvoiceGenerator` class at runtime, demonstrating the Separated Interface pattern. @@ -108,24 +110,24 @@ Console output: 11:38:53.210 [main] INFO com.iluwatar.separatedinterface.App -- Domestic Tax applied: 60.0 ``` -In this way, the Separated Interface pattern allows us to decouple the interface of a component from its implementation, enhancing flexibility and maintainability. +In this way, the Separated Interface pattern allows us to decouple the interface of a component from its implementation, enhancing flexibility and maintainability and making it ideal for dynamic Java application environments. -## Applicability +## When to Use the Separated Interface Pattern in Java * Use when you want to decouple the interface of a component from its implementation. -* Useful in large systems where different teams work on different parts of the system. +* Particularly effective in large-scale Java systems, where separate teams handle different components, the Separated Interface pattern ensures seamless integration and easier maintenance. * Ideal when the implementation might change over time or vary between deployments. -## Tutorial +## Separated Interface Pattern Tutorials * [Separated Interface Design Pattern Explained (Ram N Java)](https://www.youtube.com/watch?v=d3k-hOA7k2Y) -## Known Uses +## Real-World Applications of Separated Interface Pattern in Java * Java's JDBC (Java Database Connectivity) API separates the client interface from the database driver implementations. * Remote Method Invocation (RMI) in Java, where the client and server interfaces are defined separately from the implementations. -## Consequences +## Benefits and Trade-offs of Separated Interface Pattern Benefits: @@ -138,13 +140,13 @@ Trade-offs: * Initial setup might be more complex. * May lead to increased number of classes and interfaces in the codebase. -## Related Patterns +## Related Java Design Patterns * [Adapter](https://java-design-patterns.com/patterns/adapter/): Adapts one interface to another, which can be used alongside Separated Interface to integrate different implementations. * [Bridge](https://java-design-patterns.com/patterns/bridge/): Separates an object’s interface from its implementation, similar to Separated Interface but usually applied to larger-scale architectural issues. * [Dependency Injection](https://java-design-patterns.com/patterns/dependency-injection/): Often used to inject the implementation of a separated interface, promoting loose coupling. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/serialized-entity/README.md b/serialized-entity/README.md index 5925d7636..f7306dcdf 100644 --- a/serialized-entity/README.md +++ b/serialized-entity/README.md @@ -1,22 +1,24 @@ --- -title: Serialized Entity +title: "Serialized Entity Pattern in Java: Streamlining Data Persistence and Exchange" +shortTitle: Serialized Entity +description: "Explore the Serialized Entity design pattern in Java for efficient object serialization and storage. Learn how this pattern facilitates easy data transfer and persistence across different systems." categories: Data access language: en tag: - - Data access - - Data transfer - - Persistence + - Data access + - Data transfer + - Persistence --- ## Also known as * Object Serialization -## Intent +## Intent of Serialized Entity Design Pattern -Enable easy conversion of Java objects to and from a serialized format, allowing them to be easily stored and transferred. +The Serialized Entity pattern in Java allows for the object serialization to simplify data transfer and storage. It enables easy conversion of Java objects to and from a serialized format, allowing them to be efficiently stored and transferred. -## Explanation +## Detailed Explanation of Serialized Entity Pattern with Real-World Examples Real-world example @@ -30,11 +32,11 @@ Wikipedia says > In computing, serialization is the process of translating a data structure or object state into a format that can be stored (e.g. files in secondary storage devices, data buffers in primary storage devices) or transmitted (e.g. data streams over computer networks) and reconstructed later (possibly in a different computer environment). When the resulting series of bits is reread according to the serialization format, it can be used to create a semantically identical clone of the original object. For many complex objects, such as those that make extensive use of references, this process is not straightforward. Serialization of objects does not include any of their associated methods with which they were previously linked. -**Programmatic Example** +## Programmatic Example of Serialized Entity Pattern in Java The Serialized Entity design pattern is a way to easily persist Java objects to the database. It uses the `Serializable` interface and the DAO (Data Access Object) pattern. The pattern first uses `Serializable` to convert a Java object into a set of bytes, then it uses the DAO pattern to store this set of bytes as a BLOB (Binary Large OBject) in the database. -First, we have the `Country` class, which is a simple POJO (Plain Old Java Object) that represents the data that will be serialized and stored in the database. It implements the `Serializable` interface, which means it can be converted to a byte stream and restored from it. +First, we have the `Country` class, which is a simple POJO (Plain Old Java Object) that represents the data that will be serialized and stored in the database. Implementing the Java `Serializable` interface is crucial in the Serialized Entity design pattern, which means that the object can be converted to a byte stream and restored from it. ```java @Getter @@ -163,19 +165,19 @@ Console output: This is a basic example of the Serialized Entity design pattern. It shows how to serialize Java objects, store them in a database, and then retrieve and deserialize them. -## Applicability +## When to Use the Serialized Entity Pattern in Java -* Use when you need to persist the state of an object or transfer objects between different tiers of an application. +* This pattern is especially useful for applications requiring data persistence across various states in Java environments. * Useful in scenarios where objects need to be shared over a network or saved to a file. -## Known Uses +## Real-World Applications of Serialized Entity Pattern in Java * Java's built-in serialization mechanism using `Serializable` interface. * Storing session data in web applications. * Caching objects to improve performance. * Transferring objects in distributed systems using RMI or other RPC mechanisms. -## Consequences +## Benefits and Trade-offs of Serialized Entity Pattern Benefits: @@ -189,13 +191,13 @@ Trade-offs: * Serialized formats may not be easily readable or editable by humans. * Changes to the class structure may break compatibility with previously serialized data. -## Related Patterns +## Related Java Design Patterns * [Data Transfer Object (DTO)](https://java-design-patterns.com/patterns/data-transfer-object/): Used to encapsulate data and send it over the network. Often serialized for transmission. * [Memento](https://java-design-patterns.com/patterns/memento/): Provides a way to capture and restore an object's state, often using serialization. * [Proxy](https://java-design-patterns.com/patterns/proxy/): Proxies can serialize requests to interact with remote objects. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/serialized-lob/README.md b/serialized-lob/README.md index 04fecd934..06eea05f4 100644 --- a/serialized-lob/README.md +++ b/serialized-lob/README.md @@ -1,11 +1,13 @@ --- -title: Serialized LOB +title: "Serialized LOB Pattern in Java: Managing Large Data Objects with Ease" +shortTitle: Serialized LOB +description: "Explore the Serialized LOB pattern for managing large objects in Java applications. Learn how it simplifies data access and storage of files, multimedia, and large strings efficiently." category: Data access language: en tag: - - Data access - - Data processing - - Persistence + - Data access + - Data processing + - Persistence --- ## Also known as @@ -14,21 +16,21 @@ tag: * Serialized BLOB * Serialized CLOB -## Intent +## Intent of Serialized LOB Design Pattern -To manage and store large objects (LOBs) like files, images, or large strings in a database efficiently using serialization. +Efficiently manage and store large data objects, such as multimedia files and extensive text strings, using the Serialized LOB pattern in Java, a strategy for robust database optimization. -## Explanation +## Detailed Explanation of Serialized LOB Pattern with Real-World Examples Real-world example -> Consider a social media platform where users can upload and share images and videos. Instead of storing these large multimedia files on a separate file server, the platform uses the Serialized LOB design pattern to store the files directly in the database. Each uploaded image or video is serialized into a binary large object (BLOB) and stored within the user's record. This approach ensures that the multimedia files are managed within the same transactional context as other user data, providing consistency and simplifying data access and retrieval. +> Imagine a social media platform optimized for performance, where users can upload and seamlessly share multimedia content, leveraging Java's Serialized LOB pattern for enhanced data handling. Instead of storing these large multimedia files on a separate file server, the platform uses the Serialized LOB design pattern to store the files directly in the database. Each uploaded image or video is serialized into a binary large object (BLOB) and stored within the user's record. This approach ensures that the multimedia files are managed within the same transactional context as other user data, providing consistency and simplifying data access and retrieval. In plain words > The Serialized LOB design pattern manages the storage of large objects, such as files or multimedia, by serializing and storing them directly within a database. -**Programmatic Example** +## Programmatic Example of Serialized LOB Pattern in Java The Serialized Large Object (LOB) design pattern is a way to handle large objects in a database. It involves serializing an object graph into a single large object (a BLOB or CLOB, for Binary Large Object or Character Large Object, respectively) and storing it in the database. When the object graph needs to be retrieved, it is read from the database and deserialized back into the original object graph. @@ -185,18 +187,18 @@ Name = Grass,Type = Herb -------------------------- ``` -## Applicability +## When to Use the Serialized LOB Pattern in Java * Use when you need to store large objects in a database and want to optimize data access and storage. * Ideal for applications that deal with large binary or character data such as multimedia files, logs, or documents. -## Known Uses +## Real-World Applications of Serialized LOB Pattern in Java * Storing and retrieving images or multimedia files in a database. * Managing large text documents or logs in enterprise applications. * Handling binary data in applications that require efficient data retrieval and storage. -## Consequences +## Benefits and Trade-offs of Serialized LOB Pattern Benefits: @@ -210,13 +212,13 @@ Trade-offs: * Potential performance overhead during serialization and deserialization. * Requires careful management of serialization format to maintain backward compatibility. -## Related Patterns +## Related Java Design Patterns * [DAO (Data Access Object)](https://java-design-patterns.com/patterns/dao/): Often used in conjunction with Serialized LOB to encapsulate data access logic. * Active Record: Can use Serialized LOB for managing large data within the same record. * [Repository](https://java-design-patterns.com/patterns/repository/): Uses Serialized LOB to handle complex queries and data manipulation involving large objects. -## Credits +## References and Credits * [Effective Java](https://amzn.to/4cGk2Jz) * [Java Persistence with Hibernate](https://amzn.to/44tP1ox) diff --git a/servant/README.md b/servant/README.md index 8927f3a65..67fb496ab 100644 --- a/servant/README.md +++ b/servant/README.md @@ -1,24 +1,26 @@ --- -title: Servant +title: "Servant Pattern in Java: Facilitating Rich Interactions with Servant Helpers" +shortTitle: Servant +description: "Explore the Servant design pattern in Java, an essential technique for decoupling operations from object classes. Learn how this pattern facilitates reusable and efficient code management through our detailed examples and explanations." category: Structural language: en tag: - - Decoupling - - Interface - - Messaging - - Object composition - - Resource management + - Decoupling + - Interface + - Messaging + - Object composition + - Resource management --- ## Also known as * Helper -## Intent +## Intent of Servant Design Pattern The Servant pattern is used to perform specific operations for a group of objects without changing the classes of the elements on which it operates. -## Explanation +## Detailed Explanation of Servant Pattern with Real-World Examples Real-world example @@ -26,13 +28,13 @@ Real-world example In plain words -> The Servant pattern centralizes common functionality for a group of classes, enabling decoupled and reusable operations without altering the classes themselves. +> The Java Servant pattern effectively centralizes common functionality for multiple classes, enabling decoupled and reusable operations in software development without altering the original classes, promoting efficient Java design practices. Wikipedia says > In software engineering, the servant pattern defines an object used to offer some functionality to a group of classes without defining that functionality in each of them. A Servant is a class whose instance (or even just class) provides methods that take care of a desired service, while objects for which (or with whom) the servant does something, are taken as parameters. -**Programmatic Example** +## Programmatic Example of Servant Pattern in Java The Servant design pattern is a behavioral design pattern that defines a class that provides some sort of service to a group of classes. This pattern is particularly useful when these classes lack some common functionality that can't be added to the superclass. The Servant class brings this common functionality to a group of classes. @@ -128,18 +130,18 @@ Running the application produces: In this example, the `Servant` class provides services to the `Royalty` objects. The `Servant` class doesn't know about the specific implementation of the `Royalty` objects, it only knows that it can provide certain services to them. This is a good example of the Servant design pattern. -## Applicability +## When to Use the Servant Pattern in Java -* Use the Servant pattern when you need to provide a common functionality to a group of classes without polluting their class definitions. +* Use the Servant pattern when you need to provide a common functionality to a group of classes without polluding their class definitions, perfect for enhancing Java application architecture. * Suitable when the operations performed on the objects are not the primary responsibility of the objects themselves. -## Known Uses +## Real-World Applications of Servant Pattern in Java * In GUI applications to handle operations like rendering or hit-testing which are common across different UI components. * In games where various entities (like players, enemies, or items) need common behavior such as movement or collision detection. * Logging or auditing functionalities that are required across multiple business objects. -## Consequences +## Benefits and Trade-offs of Servant Pattern Benefits: @@ -151,14 +153,14 @@ Trade-offs: * Can lead to an increase in the number of classes, potentially making the system harder to understand. * May introduce tight coupling between the Servant and the classes it serves if not designed carefully. -## Related Patterns +## Related Java Design Patterns * [Adapter](https://java-design-patterns.com/patterns/adapter/): The Servant pattern is similar to the Adapter pattern in that both provide a way to work with classes without modifying them, but the Servant pattern focuses on providing additional behavior to multiple classes rather than adapting one interface to another. * [Facade](https://java-design-patterns.com/patterns/facade/): Both patterns provide a simplified interface to a set of functionalities, but the Servant pattern is typically used for adding functionalities to a group of classes, while the Facade pattern hides the complexities of a subsystem. * [Strategy](https://java-design-patterns.com/patterns/strategy/): The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. The Servant pattern can be used in conjunction with the Strategy pattern to define operations that apply to multiple classes. * View Helper: The View Helper pattern is related as it also centralizes common functionality, but it focuses on separating presentation logic from business logic in web applications. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525) diff --git a/server-session/README.md b/server-session/README.md index 924f63288..4ce452b53 100644 --- a/server-session/README.md +++ b/server-session/README.md @@ -1,28 +1,30 @@ --- -title: Server Session +title: "Server Session Pattern in Java: Managing User Sessions with Enhanced Security" +shortTitle: Server Session +description: "Explore the Server Session Pattern for Java applications. Learn how this design pattern helps manage user sessions securely and maintain state across multiple client requests with detailed examples and uses." category: Resource management language: en tag: - - Client-server - - Cookies - - Session management - - State tracking - - Web development + - Client-server + - Cookies + - Session management + - State tracking + - Web development --- ## Also known as * Server-Side Session Management -## Intent +## Intent of Server Session Design Pattern -Manage user session data on the server-side to maintain state across multiple client requests. +Effectively manage user session data on the server-side with Java's Server Session pattern to maintain consistent state across multiple client interactions, enhancing both security and user experience. -## Explanation +## Detailed Explanation of Server Session Pattern with Real-World Examples Real-world example -> Imagine a hotel where each guest is given a unique room key card upon check-in. This key card stores the guest's personal preferences, such as preferred room temperature, wake-up call times, and minibar choices. Whenever the guest interacts with hotel services, such as ordering room service or accessing the gym, the system retrieves their preferences using the information on the key card. The hotel’s central server maintains these preferences, ensuring consistent and personalized service throughout the guest's stay. Similarly, the Server Session design pattern manages user data on the server, providing a seamless experience across multiple interactions within a web application. +> Imagine a hotel where each guest is given a unique room key card upon check-in. Similar to how a hotel key card stores a guest's personal preferences (such as preferred room temperature, wake-up call times, and minibar choices), the Server Session pattern in Java securely stores user preferences server-side, ensuring a personalized and secure user experience. Whenever the guest interacts with hotel services, such as ordering room service or accessing the gym, the system retrieves their preferences using the information on the key card. The hotel’s central server maintains these preferences, ensuring consistent and personalized service throughout the guest's stay. Similarly, the Server Session design pattern manages user data on the server, providing a seamless experience across multiple interactions within a web application. In plain words @@ -32,7 +34,7 @@ Wikipedia says > A session token is a unique identifier that is generated and sent from a server to a client to identify the current interaction session. The client usually stores and sends the token as an HTTP cookie and/or sends it as a parameter in GET or POST queries. The reason to use session tokens is that the client only has to handle the identifier—all session data is stored on the server (usually in a database, to which the client does not have direct access) linked to that identifier. -**Programmatic Example** +## Programmatic Example of Server Session Pattern in Java The Server Session design pattern is a behavioral design pattern that assigns the responsibility of storing session data on the server side. This pattern is particularly useful in the context of stateless protocols like HTTP where all requests are isolated events independent of previous requests. @@ -135,19 +137,19 @@ Console output for starting the `App` class's `main` method: This is a basic example of the Server Session design pattern. The actual implementation of the `handle` methods in the `LoginHandler` and `LogoutHandler` classes would depend on the specific requirements of your application. -## Applicability +## When to Use the Server Session Pattern in Java * Use when building web applications that require maintaining user state information across multiple requests. * Suitable for applications needing to track user interactions, preferences, or authentication state. * Ideal for scenarios where client-side storage is insecure or insufficient. -## Known Uses +## Real-World Applications of Server Session Pattern in Java * Java EE applications using HttpSession for session management. * Spring Framework's `@SessionAttributes` for handling user session data. * Apache Tomcat's session management mechanism. -## Consequences +## Benefits and Trade-offs of Server Session Pattern Benefits: @@ -161,13 +163,13 @@ Trade-offs: * Requires session management logic to handle session timeouts and data persistence. * Potential scalability issues with high user concurrency. -## Related Patterns +## Related Java Design Patterns * [State](https://java-design-patterns.com/patterns/state/): Manages state-specific behavior, which can be utilized within session management to handle different user states. * [Proxy](https://java-design-patterns.com/patterns/proxy/): Can be used to add a layer of control over session data access. * [Singleton](https://java-design-patterns.com/patterns/singleton/): Often used to create a single instance of a session manager. -## Credits +## References and Credits * [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap) * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) diff --git a/service-layer/README.md b/service-layer/README.md index d5413332b..4e50542c7 100644 --- a/service-layer/README.md +++ b/service-layer/README.md @@ -1,28 +1,32 @@ --- -title: Service Layer +title: "Service Layer Pattern in Java: Enhancing Application Architecture with Robust Service Layers" +shortTitle: Service Layer +description: "Explore the Service Layer pattern for Java applications, a key design solution for separating business logic from presentation logic. Learn its uses, benefits, and implementation with real-world examples and class diagrams to optimize your architectural strategies." category: Architectural language: en tag: - - API design - - Business - - Decoupling - - Enterprise patterns - - Layered architecture + - API design + - Business + - Decoupling + - Enterprise patterns + - Layered architecture --- ## Also known as * Application Facade -## Intent +## Intent of Service Layer Design Pattern -Encapsulate business logic in a distinct layer to promote separation of concerns and to provide a well-defined API for the presentation layer. +The Service Layer pattern is crucial for Java developers focusing on building robust application architectures that separate business processes from user interface concerns. -## Explanation +The pattern encapsulate business logic in a distinct layer to promote separation of concerns and to provide a well-defined API for the presentation layer. + +## Detailed Explanation of Service Layer Pattern with Real-World Examples Real-world example -> Consider a large restaurant where orders are taken by waitstaff and then sent to different kitchen sections (e.g., grill, salad, dessert). Each section specializes in a part of the meal, but the waitstaff don't interact directly with the kitchen staff. Instead, all orders go through a head chef who coordinates the workflow. The head chef acts like the service layer, handling the business logic (order coordination) and providing a unified interface for the waitstaff (presentation layer) to interact with the kitchen (data access layer). +> Imagine a complex restaurant system where orders are managed through a centralized 'service layer' to ensure efficient operation and clear communication between the front and back of the house. Each section specializes in a part of the meal, but the waitstaff don't interact directly with the kitchen staff. Instead, all orders go through a head chef who coordinates the workflow. The head chef acts like the service layer, handling the business logic (order coordination) and providing a unified interface for the waitstaff (presentation layer) to interact with the kitchen (data access layer). In plain words @@ -32,7 +36,9 @@ Wikipedia says > Service layer is an architectural pattern, applied within the service-orientation design paradigm, which aims to organize the services, within a service inventory, into a set of logical layers. Services that are categorized into a particular layer share functionality. This helps to reduce the conceptual overhead related to managing the service inventory, as the services belonging to the same layer address a smaller set of activities. -**Programmatic Example** +## Programmatic Example of Service Layer Pattern in Java + +Our Java implementation uses the Service Layer pattern to streamline interactions between data access objects (DAOs) and the business logic, ensuring a clean separation of concerns. The example application demonstrates interactions between a client `App` and a service `MagicService` that allows interaction between wizards, spellbooks and spells. The service is implemented with 3-layer architecture (entity, dao, service). @@ -347,42 +353,44 @@ INFO [2024-05-27 09:16:40,681] com.iluwatar.servicelayer.app.App: Find wizards INFO [2024-05-27 09:16:40,683] com.iluwatar.servicelayer.app.App: Aderlard Boud has 'Fireball' ``` -## Class diagram +## Detailed Explanation of Service Layer Pattern with Real-World Examples ![Service Layer](./etc/service-layer.png "Service Layer") -## Applicability +## When to Use the Service Layer Pattern in Java * Use when you need to separate business logic from presentation logic. * Ideal for applications with complex business rules and workflows. * Suitable for projects requiring a clear API for the presentation layer. -## Known Uses +## Real-World Applications of Service Layer Pattern in Java * Java EE applications where Enterprise JavaBeans (EJB) are used to implement the service layer. * Spring Framework applications using the @Service annotation to denote service layer classes. * Web applications that need to separate business logic from controller logic. -## Consequences +## Benefits and Trade-offs of Service Layer Pattern Benefits: +Implementing a Service Layer in Java + * Promotes code reuse by encapsulating business logic in one place. * Enhances testability by isolating business logic. -* Improves maintainability and flexibility of the application. +* Improves maintainability and flexibility of enterprise applications. Trade-offs: * May introduce additional complexity by adding another layer to the application. * Can result in performance overhead due to the extra layer of abstraction. -## Related Patterns +## Related Java Design Patterns * [Facade](https://java-design-patterns.com/patterns/facade/): Simplifies interactions with complex subsystems by providing a unified interface. * [DAO (Data Access Object)](https://java-design-patterns.com/patterns/dao/): Often used together with the Service Layer to handle data persistence. * [MVC (Model-View-Controller)](https://java-design-patterns.com/patterns/model-view-controller/): The Service Layer can be used to encapsulate business logic in the model component. -## Credits +## References and Credits * [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap) * [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/service-locator/README.md b/service-locator/README.md index 7117ee301..68c803e70 100644 --- a/service-locator/README.md +++ b/service-locator/README.md @@ -1,23 +1,25 @@ --- -title: Service Locator +title: "Service Locator Pattern in Java: Simplifying Service Access in Complex Systems" +shortTitle: Service Locator +description: "Master the Service Locator pattern in Java with our comprehensive guide. Learn how it simplifies dependency management in large-scale applications, promoting cleaner code and reusability." category: Structural language: en tag: - - Decoupling - - Dependency management - - Enterprise patterns - - Instantiation + - Decoupling + - Dependency management + - Enterprise patterns + - Instantiation --- ## Also known as * Service Registry -## Intent +## Intent of Service Locator Design Pattern -The Service Locator design pattern provides a way to decouple the creation of clients and services by using a central registry to locate service instances. +The Java Service Locator pattern provides a method to decouple Java clients and services by using a central service registry. -## Explanation +## Detailed Explanation of Service Locator Pattern with Real-World Examples Real-world example @@ -31,9 +33,9 @@ Wikipedia says > The service locator pattern is a design pattern used in software development to encapsulate the processes involved in obtaining a service with a strong abstraction layer. This pattern uses a central registry known as the "service locator", which on request returns the information necessary to perform a certain task. Proponents of the pattern say the approach simplifies component-based applications where all dependencies are cleanly listed at the beginning of the whole application design, consequently making traditional dependency injection a more complex way of connecting objects. Critics of the pattern argue that it is an antipattern which obscures dependencies and makes software harder to test. -**Programmatic Example** +## Programmatic Example of Service Locator Pattern in Java -The Service Locator design pattern is used to abstract the processes involved in obtaining a service. It uses a central registry, the "service locator", which returns the necessary information to perform a task upon request. This pattern is particularly useful in large-scale applications where services need to be centrally managed and reused. +The Service Locator design pattern is used to abstract the processes involved in obtaining a service. It uses a central registry, the "service locator", which returns the necessary information to perform a task upon request. This Java design pattern is particularly useful in enterprise Java applications where services need centralized management. In this example, we have a `Service` interface and a `ServiceLocator` class. The `Service` interface defines the methods that all services must implement. The `ServiceLocator` class is responsible for retrieving and caching these services. @@ -91,19 +93,19 @@ Here is the output from running the example: 15:39:51.420 [main] INFO com.iluwatar.servicelocator.ServiceImpl -- Service jndi/serviceA is now executing with id 56 ``` -## Applicability +## When to Use the Service Locator Pattern in Java * Use when you want to decouple service creation from client classes to reduce dependencies and improve code maintainability. * Applicable in large-scale enterprise applications where multiple services are used and dependencies need to be managed centrally. * Suitable when service instances need to be reused or shared among multiple clients. -## Known Uses +## Real-World Applications of Service Locator Pattern in Java * Enterprise Java applications often use Service Locator to manage business services. * Spring Framework uses a similar concept with its BeanFactory and ApplicationContext for dependency injection. * EJB (Enterprise JavaBeans) uses the Service Locator pattern to find and access EJB components. -## Consequences +## Benefits and Trade-offs of Service Locator Pattern Benefits: @@ -117,13 +119,13 @@ Trade-offs: * May add complexity to the codebase, especially in terms of configuration and maintenance. * Potential performance overhead due to the lookup mechanism. -## Related Patterns +## Related Java Design Patterns * [Factory](https://java-design-patterns.com/patterns/factory/): Both patterns deal with object creation but Service Locator focuses on locating services while Factory focuses on creating them. * [Dependency Injection](https://java-design-patterns.com/patterns/dependency-injection/): An alternative to Service Locator that injects dependencies directly into clients rather than having clients request them from a locator. * [Singleton](https://java-design-patterns.com/patterns/singleton/): Service Locator often uses Singleton pattern to ensure a single instance of the locator. -## Credits +## References and Credits * [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap) * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) diff --git a/service-to-worker/README.md b/service-to-worker/README.md index b9d444c02..fb234342c 100644 --- a/service-to-worker/README.md +++ b/service-to-worker/README.md @@ -1,30 +1,32 @@ --- -title: Service to Worker +title: "Service to Worker Pattern in Java: Enhancing UI and Business Logic Integration" +shortTitle: Service to Worker +description: "Discover the Service to Worker design pattern in Java: an essential strategy for separating control flow and view management to enhance web application maintainability and scalability." category: Architectural language: en tag: - - Business - - Decoupling - - Layered architecture - - Presentation - - Web development + - Business + - Decoupling + - Layered architecture + - Presentation + - Web development --- -## Intent +## Intent of Service to Worker Design Pattern -The Service to Worker design pattern combines the Dispatcher View and Service Locator patterns to facilitate the separation of processing, control flow, and view management in web applications. +The Service to Worker design pattern in Java combines the Dispatcher View and Service Locator patterns to facilitate the separation of processing, control flow, and view management in web applications. -## Explanation +## Detailed Explanation of Service to Worker Pattern with Real-World Examples Real-world example -> Imagine a large restaurant chain with a central kitchen and multiple waitstaff. When a customer places an order, the waitstaff (Controller) takes the order and hands it over to the kitchen (Service). The kitchen then processes the order, prepares the dish, and hands it back to the waitstaff. The waitstaff finally delivers the dish to the customer (View). This setup allows the kitchen staff to focus solely on cooking without worrying about customer interactions, while the waitstaff can concentrate on customer service without worrying about the cooking process. +> Imagine a large restaurant chain with a central kitchen and multiple waitstaff. When a customer places an order, the waitstaff (Controller) takes the order and hands it over to the kitchen (Service). The kitchen then processes the order, prepares the dish, and hands it back to the waitstaff. The waitstaff finally delivers the dish to the customer (View). This scenario mirrors Java web applications using the Service to Worker pattern, where backend logic (like the kitchen) is separated from frontend interactions (like the waitstaff), improving focus and efficiency in design pattern implementation. In plain words > Separates the processing logic from the view in web applications to improve maintainability and scalability. -**Programmatic Example** +## Programmatic Example of Service to Worker Pattern in Java The Service to Worker design pattern separates the processing logic from the view in web applications to improve maintainability and scalability. It combines the Dispatcher View and Service Locator patterns to facilitate the separation of processing, control flow, and view management in web applications. @@ -94,18 +96,18 @@ Console output: This is a simple example of how the Service to Worker pattern can be implemented in a Java application. -## Applicability +## When to Use the Service to Worker Pattern in Java * Use when you need to separate the controller logic from the view to improve code maintainability and enable team members to work on different parts of the application independently. * Suitable for Java web applications that utilize MVC architecture. * Appropriate for scenarios requiring complex request processing before displaying a view. -## Known Uses +## Real-World Applications of Service to Worker Pattern in Java * Java-based web frameworks like Struts and Spring MVC. * Enterprise web applications requiring a clean separation between presentation logic and business logic. -## Consequences +## Benefits and Trade-offs of Service to Worker Pattern Benefits: @@ -118,12 +120,12 @@ Trade-offs: * Increases the complexity of the application structure. * May introduce additional overhead due to the layered architecture. -## Related Patterns +## Related Java Design Patterns * [Model-View-Controller (MVC)](https://java-design-patterns.com/patterns/model-view-controller/): Service to Worker is a specialized form of MVC, focusing on separating request handling and view management. * [Front Controller](https://java-design-patterns.com/patterns/front-controller/): Often used in conjunction with Service to Worker to centralize request handling and routing. -## Credits +## References and Credits * [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap) * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) diff --git a/sharding/README.md b/sharding/README.md index e5cc05842..fef24abee 100644 --- a/sharding/README.md +++ b/sharding/README.md @@ -1,11 +1,13 @@ --- -title: Sharding +title: "Sharding Pattern in Java: Mastering Horizontal Partitioning to Boost Application Throughput" +shortTitle: Sharding +description: "Explore how Sharding, or horizontal partitioning, enhances database scalability and performance. This guide covers the Sharding pattern's intent, implementation, and benefits for Java developers." category: Data access language: en tag: - - Data access - - Optimization - - Scalability + - Data access + - Optimization + - Scalability --- ## Also known as @@ -13,11 +15,11 @@ tag: * Data Partitioning * Horizontal Partitioning -## Intent +## Intent of Sharding Design Pattern -Sharding is used to distribute data across multiple databases or servers to improve performance and scalability. +Sharding, a pivotal Java design pattern, significantly boosts database scalability and performance through horizontal partitioning. -## Explanation +## Detailed Explanation of Sharding Pattern with Real-World Examples Real-world example @@ -33,7 +35,7 @@ Wikipedia says > > There are numerous advantages to the horizontal partitioning approach. Since the tables are divided and distributed into multiple servers, the total number of rows in each table in each database is reduced. This reduces index size, which generally improves search performance. A database shard can be placed on separate hardware, and multiple shards can be placed on multiple machines. This enables a distribution of the database over a large number of machines, greatly improving performance. In addition, if the database shard is based on some real-world segmentation of the data (e.g., European customers v. American customers) then it may be possible to infer the appropriate shard membership easily and automatically, and query only the relevant shard. -**Programmatic Example** +## Programmatic Example of Sharding Pattern in Java Sharding is a type of database partitioning that separates very large databases into smaller, faster, more easily managed parts called data shards. The word shard means a small part of a whole. In software architecture, it refers to a horizontal partition in a database or search engine. Each individual partition is referred to as a shard or database shard. @@ -204,18 +206,19 @@ Finally, here is the program output: 18:32:26.506 [main] INFO com.iluwatar.sharding.HashShardManager -- Data {key=4, value='data4', type=TYPE_1} is stored in Shard 1 ``` -## Applicability +## When to Use the Sharding Pattern in Java * Use when dealing with large datasets that exceed the capacity of a single database. +* Ideal for Java applications requiring robust scalability, sharding improves performance by distributing database loads effectively. * Useful for applications requiring high availability and fault tolerance. * Effective in environments where read and write operations can be parallelized across shards. -## Known Uses +## Real-World Applications of Sharding Pattern in Java * Distributed databases such as Apache Cassandra, MongoDB, and Amazon DynamoDB. * Large-scale web applications like social networks, e-commerce platforms, and SaaS products. -## Consequences +## Benefits and Trade-offs of Sharding Pattern Benefits: @@ -229,14 +232,14 @@ Trade-offs: * Potential challenges in rebalancing shards as data grows. * Increased latency for cross-shard queries. -## Related Patterns +## Related Java Design Patterns * [Caching](https://java-design-patterns.com/patterns/caching/): Can be used in conjunction with sharding to further improve performance. * [Data Mapper](https://java-design-patterns.com/patterns/data-mapper/): Helps in abstracting and encapsulating the details of database interactions, which can be complex in a sharded environment. * [Repository](https://java-design-patterns.com/patterns/repository/): Provides a way to manage data access logic centrally, which is useful when dealing with multiple shards. * [Service Locator](https://java-design-patterns.com/patterns/service-locator/): Can be used to find and interact with different shards in a distributed system. -## Credits +## References and Credits * [Building Scalable Web Sites: Building, Scaling, and Optimizing the Next Generation of Web Applications](https://amzn.to/4bqpejJ) * [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/3y6yv1z) diff --git a/single-table-inheritance/README.md b/single-table-inheritance/README.md index c37682256..0ed1f6ead 100644 --- a/single-table-inheritance/README.md +++ b/single-table-inheritance/README.md @@ -1,12 +1,14 @@ --- -title: Single Table Inheritance +title: "Single Table Inheritance Pattern in Java: Streamlining Object Mapping with Unified Table Structures" +shortTitle: Single Table Inheritance +description: "Discover how the Single Table Inheritance pattern simplifies database schema in Java applications. Learn its use, benefits, and implementation in our comprehensive guide." category: Data access language: en tag: - - Data access - - Encapsulation - - Persistence - - Polymorphism + - Data access + - Encapsulation + - Persistence + - Polymorphism --- ## Also known as @@ -14,11 +16,13 @@ tag: * Class Table Inheritance * STI -## Intent +## Intent of Single Table Inheritance Design Pattern -Simplify the storage of an inheritance hierarchy in a single database table, where rows represent objects of different classes and columns represent the union of all attributes. +Single Table Inheritance pattern simplifies database schema in Java applications. -## Explanation +Streamline the storage of an inheritance hierarchy in a single database table, where rows represent objects of different classes and columns represent the union of all attributes. + +## Detailed Explanation of Single Table Inheritance Pattern with Real-World Examples Real-world example @@ -32,7 +36,7 @@ Wikipedia says > Single table inheritance is a way to emulate object-oriented inheritance in a relational database. When mapping from a database table to an object in an object-oriented language, a field in the database identifies what class in the hierarchy the object belongs to. All fields of all the classes are stored in the same table, hence the name "Single Table Inheritance". -**Programmatic Example** +## Programmatic Example of Single Table Inheritance Pattern in Java Single Table Inheritance is a design pattern that maps an inheritance hierarchy of classes to a single database table. Each row in the table represents an instance of a class in the hierarchy. A special discriminator column is used to identify the class to which each row belongs. @@ -215,24 +219,26 @@ Console output: The Single Table Inheritance pattern is a simple and efficient way to map an inheritance hierarchy to a relational database. However, it can lead to sparse tables if subclasses have many unique fields. In such cases, other patterns like Class Table Inheritance or Concrete Table Inheritance might be more appropriate. -## Applicability +## When to Use the Single Table Inheritance Pattern in Java * Use when you have a class hierarchy with subclasses that share a common base class and you want to store all instances of the hierarchy in a single table. * Ideal for small to medium-sized applications where the simplicity of a single table outweighs the performance cost of null fields for some subclasses. -### Tutorials +## Single Table Inheritance Pattern Tutorials * [Hibernate Tutorial 18 - Implementing Inheritance - Single Table Strategy (Java Brains)](https://www.youtube.com/watch?v=M5YrLtAHtOo) -## Known uses +## Real-World Applications of Single Table Inheritance Pattern in Java * Hibernate and JPA implementations in Java applications often use Single Table Inheritance for ORM mapping. * Rails ActiveRecord supports Single Table Inheritance out of the box. -## Consequences +## Benefits and Trade-offs of Single Table Inheritance Pattern Benefits: +Using the Single Table Inheritance pattern in Java ORM + * Simplifies database schema by reducing the number of tables. * Easier to manage relationships and queries since all data is in one table. @@ -242,12 +248,12 @@ Trade-offs: * May cause performance issues for large hierarchies due to table size and the need to filter by type. * Changes in the inheritance hierarchy require schema changes. -## Related patterns +## Related Java Design Patterns * Class Table Inheritance: Uses separate tables for each class in the hierarchy, reducing null values but increasing complexity in joins. * Concrete Table Inheritance: Each class in the hierarchy has its own table, reducing redundancy but increasing the number of tables. -## Credits +## References and Credits * [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3wlDrze) * [Java Persistence with Hibernate](https://amzn.to/44tP1ox) diff --git a/singleton/README.md b/singleton/README.md index f8559d694..626a2ed65 100644 --- a/singleton/README.md +++ b/singleton/README.md @@ -1,27 +1,29 @@ --- -title: Singleton +title: "Singleton Pattern in Java: Implementing Global Access Points in Java Applications" +shortTitle: Singleton +description: "Explore the Singleton Pattern in Java with our comprehensive guide. Learn how to implement efficient object management for your Java applications, ensuring optimal use of resources and easy access with examples and detailed explanations." category: Creational language: en tag: - - Gang of Four - - Instantiation - - Lazy initialization - - Resource management + - Gang of Four + - Instantiation + - Lazy initialization + - Resource management --- ## Also known as * Single Instance -## Intent +## Intent of Singleton Design Pattern -Ensure a class only has one instance, and provide a global point of access to it. +Ensure a Java class only has one instance, and provide a global point of access to this singleton instance. -## Explanation +## Detailed Explanation of Singleton Pattern with Real-World Examples Real-world example -> A real-world analogy for the Singleton pattern is a government issuing a passport. In a country, each citizen can only be issued one valid passport at a time. The passport office ensures that no duplicate passports are issued to the same person. Whenever a citizen needs to travel, they must use this single passport, which serves as the unique, globally recognized identifier for their travel credentials. This controlled access and unique instance management in the real world mirrors how the Singleton pattern controls the instantiation of a class in software. +> A real-world analogy for the Singleton pattern is a government issuing a passport. In a country, each citizen can only be issued one valid passport at a time. The passport office ensures that no duplicate passports are issued to the same person. Whenever a citizen needs to travel, they must use this single passport, which serves as the unique, globally recognized identifier for their travel credentials. This controlled access and unique instance management mirrors how the Singleton pattern ensures efficient object management in Java applications. In plain words @@ -31,7 +33,7 @@ Wikipedia says > In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. -**Programmatic Example** +## Programmatic Example of Singleton Pattern in Java Joshua Bloch, Effective Java 2nd Edition p.18 @@ -59,14 +61,14 @@ enumIvoryTower1=com.iluwatar.singleton.EnumIvoryTower@1221555852 enumIvoryTower2=com.iluwatar.singleton.EnumIvoryTower@1221555852 ``` -## Applicability +## When to Use the Singleton Pattern in Java Use the Singleton pattern when * There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point * When the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code -## Known uses +## Real-World Applications of Singleton Pattern in Java * The logging class * Configuration classes in many applications @@ -76,7 +78,7 @@ Use the Singleton pattern when * [java.awt.Desktop#getDesktop()](http://docs.oracle.com/javase/8/docs/api/java/awt/Desktop.html#getDesktop--) * [java.lang.System#getSecurityManager()](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#getSecurityManager--) -## Consequences +## Benefits and Trade-offs of Singleton Pattern Benefits: @@ -92,13 +94,13 @@ Trade-offs: * Potentially more complex lifecycle management. * Can introduce bottlenecks if used in a concurrent context without careful synchronization. -## Related Patterns +## Related Java Design Patterns * [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Often used to ensure a class only has one instance. * [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Singleton pattern can be implemented using a Factory Method to encapsulate the creation logic. * [Prototype](https://java-design-patterns.com/patterns/prototype/): Avoids the need to create instances, can work alongside Singleton to manage unique instances. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/spatial-partition/README.md b/spatial-partition/README.md index 330cd4dc1..26f070d5b 100644 --- a/spatial-partition/README.md +++ b/spatial-partition/README.md @@ -1,13 +1,15 @@ --- -title: Spatial Partition +title: "Spatial Partition Pattern in Java: Optimizing Spatial Queries for Enhanced Performance" +shortTitle: Spatial Partition +description: "Explore the Spatial Partition design pattern for Java, ideal for optimizing game development and simulations. Learn how it enhances performance by efficiently managing objects in space, with examples and practical applications." category: Structural language: en tag: - - Game programming - - Optimization - - Performance - - Resource management - - Scalability + - Game programming + - Optimization + - Performance + - Resource management + - Scalability --- ## Also known as @@ -15,11 +17,11 @@ tag: * Space Partitioning * Spatial Indexing -## Intent +## Intent of Spatial Partition Design Pattern Efficiently organize a large number of objects in space to optimize queries and operations. -## Explanation +## Detailed Explanation of Spatial Partition Pattern with Real-World Examples Real-world example @@ -33,13 +35,13 @@ In plain words Wikipedia says -> The Spatial Partition design pattern, also known as Space Partitioning, involves dividing a space into non-overlapping regions to manage and query spatial data efficiently. This method is widely used in computer graphics, particularly for optimizing tasks like collision detection, ray tracing, and rendering large scenes with numerous objects. By organizing objects into hierarchical structures such as BSP trees, Quadtrees, or Octrees, spatial queries can be performed more efficiently, significantly reducing computational overhead. +> The Spatial Partition design pattern, also known as Space Partitioning, involves dividing a space into non-overlapping regions to manage and query spatial data efficiently. This method is widely used in computer graphics, particularly for optimizing tasks like collision detection, ray tracing, and rendering large scenes with numerous objects. Organizing objects into hierarchical structures like BSP trees, Quadtrees, or Octrees under the Spatial Partition pattern allows for more efficient spatial queries, a significant advantage in Java applications for complex graphic rendering and collision detection. > > For example, in ray tracing, space partitioning helps quickly determine the objects a ray might intersect by narrowing down the search space, leading to faster rendering times. Similarly, in game development, Quadtrees can efficiently manage 2D game environments by segmenting the space into smaller regions, facilitating quicker collision detection and rendering. -**Programmatic Example** +## Programmatic Example of Spatial Partition Pattern in Java -The Spatial Partition design pattern is a way to handle objects in a large space, such as a game world or a simulation environment. It allows us to efficiently manage these objects and perform operations like collision detection or range queries. The pattern works by dividing the space into smaller, manageable regions, and each object is associated with the region it belongs to. This way, we can limit our operations to a specific region, instead of checking every object against every other object. +The Spatial Partition design pattern in Java is a strategic approach for handling multiple objects in expansive game worlds or detailed simulation environments, boosting query efficiency and operational speed. It allows us to efficiently manage these objects and perform operations like collision detection or range queries. The pattern works by dividing the space into smaller, manageable regions, and each object is associated with the region it belongs to. This way, we can limit our operations to a specific region, instead of checking every object against every other object. In the provided code, we have an example of a war game where the positions of players are updated every frame. The simple way to handle interactions on the battlefield is to check each player's position against every other player's position. However, this approach includes a lot of unnecessary checks between players who are too far apart to influence each other. The Spatial Partition pattern can help us optimize this operation. @@ -91,22 +93,22 @@ In this code, `SpatialPartition` is a class that represents the spatial partitio This way, we can reduce the time complexity of finding the units within a certain range from O(n^2) to O(nlogn), decreasing the computations required significantly in case of a large number of units. -## Applicability +## When to Use the Spatial Partition Pattern in Java * Use when managing a large number of objects in a spatial environment, such as in games or simulations. * Useful for optimizing spatial queries like finding nearby objects or detecting collisions. -## Tutorials +## Spatial Partition Pattern Java Tutorials * [Coding Challenge #98.1: Quadtree - Part 1 (The Coding Train)](https://www.youtube.com/watch?v=OJxEcs0w_kE) -## Known Uses +## Real-World Applications of Spatial Partition Pattern in Java * Quadtree in 2D games for collision detection. * Octree in 3D environments for rendering and physics calculations. * KD-tree in spatial databases for efficient range searches. -## Consequences +## Benefits and Trade-offs of Spatial Partition Pattern Benefits: @@ -119,12 +121,12 @@ Trade-offs: * Increased complexity in implementation. * May require periodic rebalancing or restructuring as objects move. -## Related Patterns +## Related Java Design Patterns * [Composite](https://java-design-patterns.com/patterns/composite/): Helps manage hierarchical data structures like trees used in spatial partitioning. * [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Can be used to manage memory efficiently for objects stored in spatial partitions. -## Credits +## References and Credits * [Game Programming Patterns](https://amzn.to/3K96fOn) * [Introduction to Algorithms](https://amzn.to/4aC5hW0) diff --git a/special-case/README.md b/special-case/README.md index a924a522f..eda6ad0ff 100644 --- a/special-case/README.md +++ b/special-case/README.md @@ -1,31 +1,33 @@ --- -title: Special Case +title: "Special Case Pattern in Java: Simplifying Exception Handling with Predefined Cases" +shortTitle: Special Case +description: "Explore the Special Case design pattern in Java for handling exceptional cases without cluttering the main code logic. Learn its applicability, real-world examples, and benefits for clean, maintainable code." category: Structural language: en tag: - - Abstraction - - Code simplification - - Decoupling - - Error handling - - Polymorphism - - Runtime + - Abstraction + - Code simplification + - Decoupling + - Error handling + - Polymorphism + - Runtime --- ## Also known as * Exceptional Case -## Intent +## Intent of Special Case Design Pattern -To handle exceptional cases or specific conditions without cluttering the main code logic. +The Special Case design pattern in Java offers a robust framework for addressing unique or exceptional conditions in software development without complicating the main codebase. -## Explanation +## Detailed Explanation of Special Case Pattern with Real-World Examples Real-world example > Consider a toll booth system on a highway. Normally, vehicles pass through the booth, and the system charges a toll based on the vehicle type. However, there are special cases: emergency vehicles like ambulances and fire trucks, which should not be charged. > -> In this scenario, the "Special Case" design pattern can be applied by creating a class for the toll booth system that handles regular vehicles and another for emergency vehicles. The emergency vehicle class would override the toll calculation method to ensure no charge is applied, encapsulating this special behavior without cluttering the main toll calculation logic with conditional checks. This keeps the codebase clean and ensures the special case is handled consistently. +> For instance, in a toll management system, the Special Case pattern facilitates separate handling for emergency vehicles, ensuring a streamlined toll process without additional checks. The emergency vehicle class would override the toll calculation method to ensure no charge is applied, encapsulating this special behavior without cluttering the main toll calculation logic with conditional checks. This keeps the codebase clean and ensures the special case is handled consistently. In plain words @@ -35,7 +37,7 @@ In [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) Ma > If you’ll pardon the unresistable pun, I see [Null Object](https://java-design-patterns.com/patterns/null-object/) as special case of Special Case. -**Programmatic Example** +## Programmatic Example of Special Case Pattern in Java The Special Case Pattern is a software design pattern that is used to handle a specific, often uncommon, case separately from the general case in the code. This pattern is useful when a class has behavior that requires conditional logic based on its state. Instead of cluttering the class with conditional logic, we can encapsulate the special behavior in a subclass. @@ -44,7 +46,6 @@ In an e-commerce system, the presentation layer relies on the application layer The `Db` class is a singleton that holds data for users, accounts, and products. It provides methods to seed data into the database and find data in the database. ```java - @RequiredArgsConstructor @Getter public class Db { @@ -241,21 +242,23 @@ Here is the output from running the example. In conclusion, the Special Case Pattern helps to keep the code clean and easy to understand by separating the special case from the general case. It also promotes code reuse and makes the code easier to maintain. -## Applicability +## When to Use the Special Case Pattern in Java * Use when you want to encapsulate and handle special cases or error conditions in a manner that avoids conditional logic scattered throughout the main codebase. * Useful in scenarios where certain operations have known exceptional cases that require different handling. -## Known Uses +## Real-World Applications of Special Case Pattern in Java * Implementing null object patterns to avoid null checks. * Handling specific business rules or validation logic in e-commerce applications. * Managing different file formats or protocols in data processing applications. -## Consequences +## Benefits and Trade-offs of Special Case Pattern Benefits: +Adopting the Special Case design pattern + * Simplifies the main logic by removing special case handling from the core algorithms. * Enhances code readability and maintainability by isolating special cases. @@ -264,13 +267,13 @@ Trade-offs: * May introduce additional classes or interfaces, increasing the number of components in the system. * Requires careful design to ensure that special cases are correctly encapsulated and do not introduce unexpected behaviors. -## Related Patterns +## Related Java Design Patterns * [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used to add special case behavior to objects dynamically without modifying their code. * [Null Object](https://java-design-patterns.com/patterns/null-object/): Used to provide a default behavior for null references, which is a specific type of special case. * [Strategy](https://java-design-patterns.com/patterns/strategy/): Allows dynamic switching of special case behaviors by encapsulating them in different strategy classes. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/specification/README.md b/specification/README.md index 4d67527c6..4ccb68cc5 100644 --- a/specification/README.md +++ b/specification/README.md @@ -1,13 +1,15 @@ --- -title: Specification +title: "Specification Pattern in Java: Enhancing Business Rules with Decoupled Logic" +shortTitle: Specification +description: "Dive deep into the Specification design pattern in Java, a strategic solution for encapsulating business rules. Learn how to implement, combine, and apply this pattern effectively in your software development projects." category: Behavioral language: en tag: - - Business - - Domain - - Encapsulation - - Enterprise patterns - - Extensibility + - Business + - Domain + - Encapsulation + - Enterprise patterns + - Extensibility --- ## Also known as @@ -15,11 +17,11 @@ tag: * Filter * Criteria -## Intent +## Intent of Specification Design Pattern Encapsulate business rules and criteria that an object must satisfy to enable checking these rules in various parts of the application. -## Explanation +## Detailed Explanation of Specification Pattern with Real-World Examples Real-world example @@ -29,13 +31,13 @@ Real-world example In plain words -> The Specification design pattern allows for the encapsulation and reuse of business rules and criteria in a flexible, combinable manner. +> The Specification design pattern in Java enables the efficient encapsulation and reuse of business rules, offering a flexible and dynamic way to combine criteria for robust software development Wikipedia says > In computer programming, the specification pattern is a particular software design pattern, whereby business rules can be recombined by chaining the business rules together using boolean logic. -**Programmatic Example** +## Programmatic Example of Specification Pattern in Java Let's consider a creature pool example. We have a collection of creatures with specific properties. These properties might belong to a predefined, limited set (represented by enums like `Size`, `Movement`, and `Color`) or they might be continuous values (e.g., the mass of a `Creature`). In cases with continuous values, it's better to use a "parameterized specification," where the property value is provided as an argument when the `Creature` is instantiated, allowing for greater flexibility. Additionally, predefined and/or parameterized properties can be combined using boolean logic, offering almost limitless selection possibilities (this is known as a "composite specification," explained further below). The advantages and disadvantages of each approach are detailed in the table at the end of this document. @@ -204,19 +206,23 @@ Console output: 12:49:24.818 [main] INFO com.iluwatar.specification.app.App -- Troll [size=large, movement=walking, color=dark, mass=4000.0kg] ``` -## Applicability +Adopting the Specification pattern significantly enhances the flexibility and reusability of business rules within Java applications, contributing to more maintainable code. -* Use when you need to filter objects based on different criteria. -* Use when the filtering criteria can change dynamically. +## When to Use the Specification Pattern in Java + +Apply the Java Specification pattern when + +* You need to filter objects based on different criteria. +* The filtering criteria can change dynamically. * Ideal for use cases involving complex business rules that must be reused across different parts of an application. -## Known Uses +## Real-World Applications of Specification Pattern in Java * Validating user inputs in enterprise applications. * Filtering search results in e-commerce applications. * Business rule validation in domain-driven design (DDD). -## Consequences +## Benefits and Trade-offs of Specification Pattern Benefits: @@ -229,13 +235,13 @@ Trade-offs: * Can lead to a proliferation of small classes, increasing complexity. * Might introduce performance overhead due to the dynamic checking of specifications. -## Related Patterns +## Related Java Design Patterns * [Composite](https://java-design-patterns.com/patterns/composite/): Often used together with Specification to combine multiple specifications. * [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used to add additional criteria to a specification dynamically. * [Strategy](https://java-design-patterns.com/patterns/strategy/): Both patterns involve encapsulating a family of algorithms. Strategy encapsulates different strategies or algorithms, while Specification encapsulates business rules. -## Credits +## References and Credits * [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3wlDrze) * [Implementing Domain-Driven Design](https://amzn.to/4dmBjrB) diff --git a/state/README.md b/state/README.md index 14be4b022..7fdc242ae 100644 --- a/state/README.md +++ b/state/README.md @@ -1,22 +1,24 @@ --- -title: State +title: "State Pattern in Java: Enhancing Behavior Dynamics with State Encapsulation" +shortTitle: State +description: "Explore the State Pattern, a core component of Java design patterns that enables dynamic behavior change in objects with internal state shifts. Includes real-world examples, applicability, benefits, and detailed code snippets." category: Behavioral language: en tag: - - Decoupling - - Gang of Four - - State tracking + - Decoupling + - Gang of Four + - State tracking --- ## Also known as * Objects for States -## Intent +## Intent of State Design Pattern -Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. +Enable an object to alter its behavior dynamically as its internal state changes, optimizing Java application responsiveness. -## Explanation +## Detailed Explanation of State Pattern with Real-World Examples Real-world example @@ -36,7 +38,7 @@ Wikipedia says > The state pattern is a behavioral software design pattern that allows an object to alter its behavior when its internal state changes. This pattern is close to the concept of finite-state machines. The state pattern can be interpreted as a strategy pattern, which is able to switch a strategy through invocations of methods defined in the pattern's interface. -**Programmatic Example** +## Programmatic Example of State Pattern in Java In our programmatic example there is a mammoth with alternating moods. @@ -153,36 +155,36 @@ Program output: The mammoth is calm and peaceful. ``` -## Applicability +## When to Use the State Pattern in Java * An object's behavior depends on its state, and it must change its behavior at runtime depending on that state. * Operations have large, multipart conditional statements that depend on the object's state. -## Known Uses +## Real-World Applications of State Pattern in Java * `java.util.Iterator` in Java's Collections Framework uses different states for iteration. * TCP connection classes in network programming often implement states like `Established`, `Listen`, and `Closed`. -## Consequences +## Benefits and Trade-offs of State Pattern Benefits: * Localizes state-specific behavior and partitions behavior for different states. * Makes state transitions explicit. -* State objects can be shared among different contexts. +* Reusable State objects can be efficiently shared among various contexts in Java, enhancing memory management and performance. Trade-offs: * Can result in a large number of classes for states. * Context class can become complicated with the state transition logic. -## Related Patterns +## Related Java Design Patterns * [Flyweight](https://java-design-patterns.com/patterns/flyweight/): State objects may be shared between different contexts. * [Singleton](https://java-design-patterns.com/patterns/singleton/): State objects are often singletons. * [Strategy](https://java-design-patterns.com/patterns/strategy/): Both patterns have similar structures, but the State pattern's implementations depend on the context’s state. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) diff --git a/step-builder/README.md b/step-builder/README.md index 133baafd7..a651cff45 100644 --- a/step-builder/README.md +++ b/step-builder/README.md @@ -1,25 +1,27 @@ --- -title: Step Builder +title: "Step Builder Pattern in Java: Crafting Fluent Interfaces for Complex Object Construction" +shortTitle: Step Builder +description: "Master the Step Builder pattern in Java to streamline complex object creation. Learn through detailed explanations and examples. Perfect for software developers aiming to enhance code readability and maintainability." category: Creational language: en tag: - - Code simplification - - Domain - - Encapsulation - - Extensibility - - Instantiation - - Interface + - Code simplification + - Domain + - Encapsulation + - Extensibility + - Instantiation + - Interface --- ## Also known as * Fluent Builder -## Intent +## Intent of Step Builder Design Pattern -Separate the construction of a complex object step-by-step, allowing an object to be built incrementally. +The Step Builder pattern in Java is an advanced technique to create complex objects with clarity and flexibility. It is perfect for scenarios requiring meticulous step-by-step object construction. -## Explanation +## Detailed Explanation of Step Builder Pattern with Real-World Examples Real-world example @@ -33,9 +35,9 @@ Wikipedia says > The Step Builder pattern is a variation of the Builder design pattern, designed to provide a flexible solution for constructing complex objects step-by-step. This pattern is particularly useful when an object requires multiple initialization steps, which can be done incrementally to ensure clarity and flexibility in the creation process. -**Programmatic Example** +## Programmatic Example of Step Builder Pattern in Java -The Step Builder pattern is an extension of the Builder pattern that guides the user through the creation of an object in a step-by-step manner. This pattern improves the user experience by only showing the next step methods available, and not showing the build method until it's the right time to build the object. +The Step Builder pattern in Java is an extension of the Builder pattern that guides the user through the creation of an object in a step-by-step manner. This pattern improves the user experience by only showing the next step methods available, and not showing the build method until it's the right time to build the object. Let's consider a `Character` class that has many attributes such as `name`, `fighterClass`, `wizardClass`, `weapon`, `spell`, and `abilities`. @@ -160,27 +162,29 @@ Console output: 12:58:13.889 [main] INFO com.iluwatar.stepbuilder.App -- This is a Rogue named Desmond armed with a with nothing. ``` -## Class diagram +## Detailed Explanation of Step Builder Pattern with Real-World Examples ![Step Builder](./etc/step-builder.png "Step Builder") -## Applicability +## When to Use the Step Builder Pattern in Java + +The Step Builder pattern in Java is used * When constructing an object that requires multiple initialization steps. * When object construction is complex and involves many parameters. * When you want to provide a clear, readable, and maintainable way to construct an object in a step-by-step manner. -## Tutorials +## Step Builder Pattern Java Tutorials * [Step Builder (Marco Castigliego)](http://rdafbn.blogspot.co.uk/2012/07/step-builder-pattern_28.html) -## Known Uses +## Real-World Applications of Step Builder Pattern in Java * Complex configuration settings in Java applications. * Constructing objects for database records with multiple fields. * Building UI elements where each step configures a different part of the interface. -## Consequences +## Benefits and Trade-offs of Step Builder Pattern Benefits: @@ -193,13 +197,13 @@ Trade-offs: * May result in more complex code due to the additional classes and interfaces required. * Can lead to verbose code when many steps are involved. -## Related Patterns +## Related Java Design Patterns * [Builder](https://java-design-patterns.com/patterns/builder/): Both patterns help in constructing complex objects. Step Builder is a variation that emphasizes incremental step-by-step construction. * [Fluent Interface](https://java-design-patterns.com/patterns/fluentinterface/): Often used in conjunction with the Step Builder pattern to provide a fluent API for constructing objects. * [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Sometimes used with the Step Builder pattern to encapsulate the creation logic of the builder itself. -## Credits +## References and Credits * [Clean Code: A Handbook of Agile Software Craftsmanship](https://amzn.to/3wRnjp5) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/strangler/README.md b/strangler/README.md index ff7b0ca9a..569a2151f 100644 --- a/strangler/README.md +++ b/strangler/README.md @@ -1,22 +1,24 @@ --- -title: Strangler +title: "Strangler Pattern in Java: Modernizing Legacy Systems with Incremental Updates" +shortTitle: Strangler +description: "Explore the Strangler design pattern for Java, a strategic approach to incrementally modernize legacy systems without disruption. Learn how it facilitates smooth transitions to new architectures, with real-world applications and code examples." category: Structural language: en tag: - - Migration - - Modernization - - Refactoring + - Migration + - Modernization + - Refactoring --- ## Also known as * Strangler Fig -## Intent +## Intent of Strangler Design Pattern -Incrementally replace the legacy system by building a new system alongside the old one, eventually strangling the old system. +The Strangler Pattern incrementally replaces the legacy system by building a new system alongside the old one, eventually strangling the old system. Using the pattern offer a seamless transition from old to new systems. -## Explanation +## Detailed Explanation of Strangler Pattern with Real-World Examples Real-world example @@ -30,9 +32,9 @@ Wikipedia says > The Strangler Design Pattern involves incrementally migrating a legacy system by gradually replacing it with a new system. It wraps old code with new code, redirecting or logging uses of the old code to ensure a seamless transition. This pattern is named after the strangler fig plant, which grows around a host tree and eventually replaces it entirely. It's particularly useful for modernizing monolithic applications and transitioning them to microservices architecture with minimal risk and disruption. -**Programmatic Example** +## Programmatic Example of Strangler Pattern in Java -The Strangler design pattern is a software design pattern that incrementally migrates a legacy system by gradually replacing specific pieces of functionality with new applications and services. As features from the legacy system are replaced, the new system eventually replaces all of the old system's features, strangling the old system and allowing you to decommission it. +The Strangler design pattern in Java is a software design pattern that incrementally migrates a legacy system by gradually replacing specific pieces of functionality with new applications and services. As features from the legacy system are replaced, the new system eventually replaces all the old system's features, strangling the old system and allowing you to decommission it. In the provided code, we have an example of the Strangler pattern in action. The `OldArithmetic` class represents the legacy system, while the `HalfArithmetic` and `NewArithmetic` classes represent the new system at different stages of development. @@ -158,23 +160,24 @@ Console output: This is a typical example of the Strangler pattern. The legacy system (`OldArithmetic`) is gradually replaced by the new system (`HalfArithmetic` and `NewArithmetic`). The new system is developed incrementally, and at each stage, it strangles a part of the legacy system until the legacy system is completely replaced. -## Applicability +## When to Use the Strangler Pattern in Java * Use when you need to replace a monolithic or legacy system incrementally. * Ideal for scenarios where the system cannot be replaced in one go due to risk or complexity. * Suitable when you need to modernize parts of an application while ensuring continuous operation. +* Perfect for applications requiring updates with zero downtime, the Strangler pattern supports incremental updates in complex Java systems. -## Tutorials +## Strangler Pattern Java Tutorials * [Legacy Application Strangulation: Case Studies (Paul Hammant)](https://paulhammant.com/2013/07/14/legacy-application-strangulation-case-studies/) -## Known Uses +## Real-World Applications of Strangler Pattern in Java * Replacing a legacy monolithic application with a microservices architecture. * Transitioning from an on-premise system to a cloud-based system. * Incrementally migrating from an old database schema to a new one without downtime. -## Consequences +## Benefits and Trade-offs of Strangler Pattern Benefits: @@ -188,13 +191,13 @@ Trade-offs: * May introduce temporary performance overhead due to coexistence of old and new systems. * Potentially increases the initial development time due to the need for integration. -## Related Patterns +## Related Java Design Patterns * [Adapter](https://java-design-patterns.com/patterns/adapter/): Used to make new systems interact with the old system during the transition period. * [Facade](https://java-design-patterns.com/patterns/facade/): Can provide a unified interface to the old and new systems, simplifying client interactions. * Microservices: The target architecture in many cases where the Strangler Pattern is applied. -## Credits +## References and Credits * [Building Microservices](https://amzn.to/3UACtrU) * [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/strategy/README.md b/strategy/README.md index 53982d3bc..08004ad25 100644 --- a/strategy/README.md +++ b/strategy/README.md @@ -1,28 +1,30 @@ --- -title: Strategy +title: "Strategy Pattern in Java: Streamlining Object Behaviors with Interchangeable Algorithms" +shortTitle: Strategy +description: "Explore the Strategy design pattern in Java with a detailed guide and practical examples. Learn how to implement flexible and interchangeable algorithms effectively in your Java applications for enhanced design and maintenance." category: Behavioral language: en tag: - - Decoupling - - Extensibility - - Gang of Four - - Interface - - Polymorphism + - Decoupling + - Extensibility + - Gang of Four + - Interface + - Polymorphism --- ## Also known as * Policy -## Intent +## Intent of Strategy Design Pattern -Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently of the clients that use it. +Define a family of algorithms in Java, encapsulate each one, and make them interchangeable to enhance software development using the Strategy design pattern. Strategy lets the algorithm vary independently of the clients that use it. -## Explanation +## Detailed Explanation of Strategy Pattern with Real-World Examples Real-world example -> An analogous real-world example of the Strategy design pattern is the navigation systems in cars. Different navigation algorithms (such as shortest route, fastest route, and scenic route) can be used to determine the best path from one location to another. Each algorithm encapsulates a specific strategy for calculating the route. The user (client) can switch between these algorithms based on their preferences without changing the navigation system itself. This allows for flexible and interchangeable navigation strategies within the same system. +> A practical real-world example of the Strategy design pattern in Java is evident in car navigation systems, where algorithm flexibility is paramount. Different navigation algorithms (such as shortest route, fastest route, and scenic route) can be used to determine the best path from one location to another. Each algorithm encapsulates a specific strategy for calculating the route. The user (client) can switch between these algorithms based on their preferences without changing the navigation system itself. This allows for flexible and interchangeable navigation strategies within the same system. In plain words @@ -32,11 +34,11 @@ Wikipedia says > In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. -**Programmatic Example** +## Programmatic Example of Strategy Pattern in Java Slaying dragons is a dangerous job. With experience, it becomes easier. Veteran dragonslayers have developed different fighting strategies against different types of dragons. -Let's first introduce the `DragonSlayingStrategy` interface and its implementations. +Let's explore how to implement the `DragonSlayingStrategy` interface in Java, demonstrating various Strategy pattern applications. ```java @FunctionalInterface @@ -173,7 +175,7 @@ Program output: 13:06:36.637 [main] INFO com.iluwatar.strategy.LambdaStrategy -- You cast the spell of disintegration and the dragon vaporizes in a pile of dust! ``` -## Applicability +## When to Use the Strategy Pattern in Java Use the Strategy pattern when: @@ -182,16 +184,16 @@ Use the Strategy pattern when: * An algorithm uses data that clients shouldn't know about. * A class defines many behaviors and these appear as multiple conditional statements in its operations. -## Tutorial +## Strategy Pattern Java Tutorials * [Strategy Pattern Tutorial (DigitalOcean)](https://www.digitalocean.com/community/tutorials/strategy-design-pattern-in-java-example-tutorial) -## Known Uses +## Real-World Applications of Strategy Pattern in Java * Java's `java.util.Comparator` interface is a common example of the Strategy pattern. * In GUI frameworks, layout managers (such as those in Java's AWT and Swing) are strategies. -## Consequences +## Benefits and Trade-offs of Strategy Pattern Benefits: @@ -205,12 +207,12 @@ Trade-offs: * Clients must be aware of different Strategies. * Increase in the number of objects. -## Related patterns +## Related Java Design Patterns * [Decorator](https://java-design-patterns.com/patterns/decorator/): Enhances an object without changing its interface but is more concerned with responsibilities than algorithms. * [State](https://java-design-patterns.com/patterns/state/): Similar in structure but used to represent state-dependent behavior rather than interchangeable algorithms. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Functional Programming in Java](https://amzn.to/3JUIc5Q) diff --git a/subclass-sandbox/README.md b/subclass-sandbox/README.md index 18cae602b..1dbea163e 100644 --- a/subclass-sandbox/README.md +++ b/subclass-sandbox/README.md @@ -1,25 +1,27 @@ --- -title: Subclass Sandbox +title: "Subclass Sandbox Pattern in Java: Enhancing Code Reusability with Sandbox Techniques" +shortTitle: Subclass Sandbox +description: "Explore the Subclass Sandbox design pattern in Java, perfect for allowing flexible behavior customization in object-oriented programming. Ideal for game development and extending class behavior." category: Behavioral language: en tag: - - Abstraction - - Code simplification - - Decoupling - - Extensibility - - Game programming - - Polymorphism + - Abstraction + - Code simplification + - Decoupling + - Extensibility + - Game programming + - Polymorphism --- ## Also known as * Hook Method -## Intent +## Intent of Subclass Sandbox Design Pattern -To allow subclasses to alter the core behavior of a class by providing specific implementations of certain methods while keeping the overall structure unchanged. +The Subclass Sandbox design pattern in Java allows subclasses to alter the core behavior of a class by providing specific implementations of certain methods while keeping the overall structure unchanged. -## Explanation +## Detailed Explanation of Subclass Sandbox Pattern with Real-World Examples Real-world example @@ -33,7 +35,9 @@ In plain words > A base class defines an abstract sandbox method and several provided operations. Marking them protected makes it clear that they are for use by derived classes. Each derived sandboxed subclass implements the sandbox method using the provided operations. -**Programmatic Example** +## Programmatic Example of Subclass Sandbox Pattern in Java + +Using the Subclass Sandbox pattern, developers can create distinct functionalities within Java applications, enhancing game development and software design. Suppose you want to create various superpowers in a game, where each superpower needs to move with a sound effect and spawn particles. Should you create many classes with similar methods or derive them from a base class? The Subclass Sandbox pattern enables you to handle this efficiently by deriving these classes from a common base class. @@ -124,21 +128,23 @@ Program output: 13:10:23.180 [main] INFO com.iluwatar.subclasssandbox.GroundDive -- Spawn 20 particle with type GROUNDDIVE_PARTICLE ``` -## Applicability +## When to Use the Subclass Sandbox Pattern in Java * Use when you want to create a framework that allows users to define their own behaviors by extending classes. * Applicable in scenarios where you need to enforce a specific algorithm structure while allowing certain steps to be overridden. -## Known Uses +## Real-World Applications of Subclass Sandbox Pattern in Java * Template method pattern in GUI frameworks where the framework provides the structure and the subclasses implement the specifics. * Game development where the core game loop is defined, but specific behaviors are provided by subclassing. * Java libraries like the `AbstractList` where core methods are defined and certain behaviors can be customized by extending classes. -## Consequences +## Benefits and Trade-offs of Subclass Sandbox Pattern Benefits: +The Subclass Sandbox pattern in Java + * Encourages code reuse by allowing shared code in the superclass. * Simplifies the addition of new behaviors through subclassing. * Enhances code readability and maintainability by separating the algorithm's structure from specific implementations. @@ -149,12 +155,12 @@ Trade-offs: * Requires careful design to ensure that the base class is flexible enough for various extensions. * Increases complexity in understanding the code flow due to multiple layers of inheritance. -## Related Patterns +## Related Java Design Patterns * [Strategy](https://java-design-patterns.com/patterns/strategy/): Both involve interchangeable behaviors, but Strategy pattern uses composition over inheritance. * [Template Method](https://java-design-patterns.com/patterns/template-method/): Similar in enforcing a structure where certain steps can be overridden by subclasses. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/table-module/README.md b/table-module/README.md index e9cf624e9..e69892bb7 100644 --- a/table-module/README.md +++ b/table-module/README.md @@ -1,22 +1,24 @@ --- -title: Table Module +title: "Table Module Pattern in Java: Enhancing Maintainability with Organized Data Handling Modules" +shortTitle: Table Module +description: "Explore the Table Module pattern in Java with our in-depth guide. Learn how it simplifies database interaction by encapsulating data access logic, enhances code maintenance, and secures data operations." category: Data access language: en tag: - - Data access - - Encapsulation - - Persistence + - Data access + - Encapsulation + - Persistence --- ## Also known as * Record Set -## Intent +## Intent of Table Module Design Pattern -Encapsulates database table data access logic in a single module, allowing for easy retrieval and manipulation of data without exposing the database structure. +The Table Module pattern expertly encapsulates database table data access logic in a single, efficient module, ideal for Java applications. -## Explanation +## Detailed Explanation of Table Module Pattern with Real-World Examples Real-world example @@ -26,7 +28,7 @@ In plain words > The Table Module pattern centralizes and encapsulates database access logic for a specific table, simplifying data retrieval and manipulation while hiding database complexities. -**Programmatic Example** +## Programmatic Example of Table Module Pattern in Java In the user system example, the domain logic for user login and registration needs to be managed. By using the Table Module pattern, we can create an instance of the `UserTableModule` class to encapsulate and handle all business logic associated with the rows in the user table. @@ -141,23 +143,23 @@ The program output: This example shows how the Table Module pattern centralizes database operations for the `users` table, making the application more modular and easier to maintain. -## Applicability +## When to Use the Table Module Pattern in Java * Use when you need to manage data access logic for a database table in a centralized module. * Ideal for applications that interact heavily with database tables and require encapsulation of database queries. -* Suitable for systems where the database schema may evolve over time, as the changes can be managed within the table module. +* Particularly suitable for dynamic systems, the Table Module pattern ensures scalable database management as your Java application's schema evolves. -## Tutorials +## Table Module Pattern Java Tutorials * [Architecture patterns: Domain model and friends (Inviqa)](https://inviqa.com/blog/architecture-patterns-domain-model-and-friends) -## Known Uses +## Real-World Applications of Table Module Pattern in Java * In enterprise applications where multiple modules need to interact with the same database tables. * Web applications that require CRUD operations on database tables. * Java-based ORM frameworks such as Hibernate or JPA utilize similar concepts for managing data access. -## Consequences +## Benefits and Trade-offs of Table Module Pattern Benefits: @@ -170,7 +172,7 @@ Trade-offs: * May lead to a large module if the table has many operations, potentially reducing readability. * Can become a bottleneck if not properly optimized, especially in high-load scenarios. -## Related Patterns +## Related Java Design Patterns * Active Record: Unlike Table Module, Active Record combines data access and domain logic in the same class. * [Data Access Object (DAO)](https://java-design-patterns.com/patterns/dao/): Provides an abstract interface to some type of database or other persistence mechanism, often used alongside Table Module to separate low-level data access operations from high-level business logic. @@ -179,7 +181,7 @@ Trade-offs: * [Repository](https://java-design-patterns.com/patterns/repository/): Abstracts the data layer, allowing more complex queries, whereas Table Module is usually simpler and table-centric. * [Transaction Script](https://java-design-patterns.com/patterns/transaction-script/): Organizes business logic by procedures where each procedure handles a single request from the presentation layer, contrasting with the Table Module's data-centric approach. -## Credits +## References and Credits * [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap) * [Java Persistence with Hibernate](https://amzn.to/44tP1ox) diff --git a/template-method/README.md b/template-method/README.md index aa307fbac..a05d77ff0 100644 --- a/template-method/README.md +++ b/template-method/README.md @@ -1,24 +1,26 @@ --- -title: Template method +title: "Template Method Pattern in Java: Streamlining Complex Algorithms with Predefined Scaffolds" +shortTitle: Template Method +description: "Discover the essentials of the Template Method pattern in Java, including how it simplifies code, promotes reusability, and allows flexibility in algorithm design. Perfect for developers looking to refine their object-oriented programming skills." category: Behavioral language: en tag: - - Abstraction - - Code simplification - - Decoupling - - Extensibility - - Gang of Four - - Inheritance - - Object composition - - Polymorphism - - Reusability + - Abstraction + - Code simplification + - Decoupling + - Extensibility + - Gang of Four + - Inheritance + - Object composition + - Polymorphism + - Reusability --- -## Intent +## Intent of Template method Design Pattern Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. -## Explanation +## Detailed Explanation of Template method Pattern with Real-World Examples Real-world example @@ -26,13 +28,13 @@ Real-world example In plain words -> Template Method pattern outlines the general steps in the parent class and lets the concrete child implementations define the details. +> The Java Template Method pattern outlines the core steps in the parent class, allowing child classes to tailor detailed implementations, enhancing code reusability and design flexibility in Java programming. Wikipedia says > In object-oriented programming, the template method is one of the behavioral design patterns identified by Gamma et al. in the book Design Patterns. The template method is a method in a superclass, usually an abstract superclass, and defines the skeleton of an operation in terms of a number of high-level steps. These steps are themselves implemented by additional helper methods in the same class as the template method. -**Programmatic Example** +## Programmatic Example of Template Method Pattern in Java Our programmatic example is about thieves and stealing. The general steps in stealing an item are the same. First, you pick the target, next you confuse him somehow and finally, you steal the item. However, there are many ways to implement these steps. @@ -142,7 +144,7 @@ The program output: 11:06:01.723 [main] INFO com.iluwatar.templatemethod.SubtleMethod -- While in close contact grab the shop keeper's wallet. ``` -## Applicability +## When to Use the Template method Pattern in Java The Template Method pattern should be used @@ -150,16 +152,16 @@ The Template Method pattern should be used * When common behavior among subclasses should be factored and localized in a common class to avoid code duplication. This is a good example of "refactoring to generalize" as described by Opdyke and Johnson. You first identify the differences in the existing code and then separate the differences into new operations. Finally, you replace the differing code with a template method that calls one of these new operations * To control subclasses extensions. You can define a template method that calls "hook" operations at specific points, thereby permitting extensions only at those points -## Tutorials +## Template method Pattern Java Tutorials * [Template Method Design Pattern In Java (DigitalOcean)](https://www.digitalocean.com/community/tutorials/template-method-design-pattern-in-java) -## Known uses +## Real-World Applications of Template method Pattern in Java * Java's AbstractList and AbstractSet classes in the Collections Framework use the Template Method pattern to define common algorithms for list and set operations. * Frameworks like JUnit use Template Method to define the setup and teardown process in test cases. -## Consequences +## Benefits and Trade-offs of Template method Pattern Benefits: @@ -172,13 +174,13 @@ Trade-offs: * Can lead to an increase in the number of classes, making the system more complex. * Requires careful design to ensure that the steps exposed to subclasses are useful and meaningful. -## Related Patterns +## Related Java Design Patterns * [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Often used with Template Method to create objects needed for specific steps of the algorithm. * [Strategy](https://java-design-patterns.com/patterns/strategy/): While Template Method defines the skeleton of an algorithm and lets subclasses implement specific steps, the Strategy Pattern defines a family of algorithms and makes them interchangeable. * [Subclass Sandbox](https://java-design-patterns.com/patterns/subclass-sandbox/): Complements Template Method by ensuring that subclasses can safely override specific steps of an algorithm without causing unintended side effects. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/throttling/README.md b/throttling/README.md index fc7525103..d35c346de 100644 --- a/throttling/README.md +++ b/throttling/README.md @@ -1,24 +1,26 @@ --- -title: Throttling +title: "Throttling Pattern in Java: Optimizing Resource Usage in High-Demand Applications" +shortTitle: Throttling +description: "Explore the Throttling design pattern in Java to manage application stability and prevent system overload. Learn how rate limiting ensures consistent performance and system resilience. Ideal for developers and software architects." category: Resource management language: en tag: - - API design - - Fault tolerance - - Performance - - Resilience - - Scalability + - API design + - Fault tolerance + - Performance + - Resilience + - Scalability --- ## Also known as * Rate Limiting -## Intent +## Intent of Throttling Design Pattern -Throttling limits the number of requests a system can process within a given time frame to prevent overload and ensure stability. +The Throttling Pattern, also known as Rate Limiting, limits the number of requests a system can process within a given time frame to prevent overload and ensure stability. It is crucial for resource management in Java applications. -## Explanation +## Detailed Explanation of Throttling Pattern with Real-World Examples Real-world example @@ -32,9 +34,9 @@ In plain words > Control the consumption of resources used by an instance of an application, an individual tenant, or an entire service. This can allow the system to continue to function and meet service level agreements, even when an increase in demand places an extreme load on resources. -**Programmatic Example** +## Programmatic Example of Throttling Pattern in Java -In this example a young human and an old dwarf walk into a bar. They start ordering beers from the bartender. The bartender immediately sees that the young human shouldn't consume too many drinks too fast and refuses to serve if enough time has not passed. For the old dwarf, the serving rate can be higher. +In this Java example, we demonstrate throttling. A young human and an old dwarf walk into a bar. They start ordering beers from the bartender. The bartender immediately sees that the young human shouldn't consume too many drinks too fast and refuses to serve if enough time has not passed. For the old dwarf, the serving rate can be higher. `BarCustomer` class presents the clients of the `Bartender` API. `CallsCount` tracks the number of calls per `BarCustomer`. @@ -211,19 +213,19 @@ An excerpt from the example's console output: 18:46:37.148 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today! ``` -## Applicability +## When to Use the Throttling Pattern in Java * You need to protect resources from being overwhelmed by too many requests. * You want to ensure fair usage of a service among multiple users. * You need to maintain the quality of service under high load conditions. -## Known Uses +## Real-World Applications of Throttling Pattern in Java * APIs of major cloud providers like AWS, Google Cloud, and Azure use throttling to manage resource usage. * Web services to prevent denial-of-service (DoS) attacks by limiting the number of requests from a single IP address. * Online platforms like social media sites and e-commerce websites to ensure even distribution of server load. -## Consequences +## Benefits and Trade-offs of Throttling Pattern Benefits: @@ -237,12 +239,12 @@ Trade-offs: * Requires careful tuning to balance between resource protection and user experience. * Could lead to denial of service to legitimate users if not configured correctly. -## Related Patterns +## Related Java Design Patterns * [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/): Works in tandem with throttling to prevent repeated attempts to access an overloaded service. * Bulkhead: Isolates different parts of the system to limit the impact of throttling on other components. -## Credits +## References and Credits * [Throttling pattern (Microsoft)](https://docs.microsoft.com/en-us/azure/architecture/patterns/throttling) * [Cloud Design Patterns: Prescriptive Architecture Guidance for Cloud Applications](https://amzn.to/4dLvowg) diff --git a/tolerant-reader/README.md b/tolerant-reader/README.md index 04e449c10..720764214 100644 --- a/tolerant-reader/README.md +++ b/tolerant-reader/README.md @@ -1,23 +1,25 @@ --- -title: Tolerant Reader +title: "Tolerant Reader Pattern in Java: Enhancing API Resilience and Compatibility" +shortTitle: Tolerant Reader +description: "Discover how the Tolerant Reader pattern can boost your API's resilience by ignoring unrecognized data, ensuring backward compatibility and seamless integration. Learn through examples and best practices on implementing this robust communication mechanism." category: Resilience language: en tag: - - API design - - Decoupling - - Fault tolerance - - Integration + - API design + - Decoupling + - Fault tolerance + - Integration --- ## Also known as * Lenient Consumer -## Intent +## Intent of Tolerant Reader Design Pattern -Allows a system to be more resilient to changes in the data structures it consumes by ignoring elements that it does not recognize. +The Tolerant Reader pattern enhances system resilience to changes in data structures by strategically ignoring unrecognized elements, promoting robust API design. -## Explanation +## Detailed Explanation of Tolerant Reader Pattern with Real-World Examples Real-world example @@ -25,13 +27,13 @@ Real-world example In plain words -> Tolerant Reader pattern is used to create robust communication mechanisms between services. +> Utilize the Tolerant Reader pattern to establish robust and resilient communication between services, ensuring data compatibility and integration. [Robustness Principle](https://java-design-patterns.com/principles/#robustness-principle) says > Be conservative in what you do, be liberal in what you accept from others. -**Programmatic Example** +## Programmatic Example of Tolerant Reader Pattern in Java We are persisting `RainbowFish` objects to file. Later on they need to be restored. What makes it problematic is that `RainbowFish` data structure is versioned and evolves over time. New version of `RainbowFish` needs to be able to restore old versions as well. @@ -169,18 +171,18 @@ Program output: 15:38:00.619 [main] INFO com.iluwatar.tolerantreader.App -- deserializedFishV2 name=Scar age=5 length=12 weight=15 ``` -## Applicability +## When to Use the Tolerant Reader Pattern in Java -* Use when a system needs to consume data from external sources that may change over time. +* Apply the Tolerant Reader pattern when your system consumes data from evolving external sources, maintaining efficiency and data integrity. * Applicable when backward compatibility is required in API design. * Suitable for integration scenarios where different systems exchange data and evolve independently. -## Known Uses +## Real-World Applications of Tolerant Reader Pattern in Java * JSON or XML parsers that skip unknown elements. * API clients in microservices architectures that interact with multiple versions of a service. -## Consequences +## Benefits and Trade-offs of Tolerant Reader Pattern Benefits: @@ -193,13 +195,13 @@ Trade-offs: * May result in silent failures if important data is ignored. * Can complicate debugging and tracing of issues due to missing or unrecognized data. -## Related Patterns +## Related Java Design Patterns * [Adapter](https://java-design-patterns.com/patterns/adapter/): Both patterns deal with data transformation and integration, but the Adapter Pattern focuses on converting interfaces, while Tolerant Reader focuses on ignoring unrecognized data. * [Facade](https://java-design-patterns.com/patterns/facade/): Simplifies interactions with complex systems, similar to how Tolerant Reader simplifies data consumption by ignoring irrelevant data. * [Strategy](https://java-design-patterns.com/patterns/strategy/): Can be used in conjunction with Tolerant Reader to dynamically switch between different data handling strategies. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/trampoline/README.md b/trampoline/README.md index a42a43bc6..cb4162baf 100644 --- a/trampoline/README.md +++ b/trampoline/README.md @@ -1,12 +1,14 @@ --- -title: Trampoline +title: "Trampoline Pattern in Java: Mastering Recursion Without Stack Overflow" +shortTitle: Trampoline +description: "Discover how to implement the Trampoline pattern in Java to efficiently manage recursive functions and prevent stack overflow errors, with real-world examples and programming insights." category: Functional language: en tag: - - Code simplification - - Functional decomposition - - Performance - - Recursion + - Code simplification + - Functional decomposition + - Performance + - Recursion --- ## Also known as @@ -14,11 +16,11 @@ tag: * Bounce * Tail-Call Optimization -## Intent +## Intent of Trampoline Design Pattern -To optimize recursive function calls by converting them into iterative loops, avoiding stack overflow errors. +The Trampoline Pattern in Java optimizes recursive function calls by converting them into iterative loops, avoiding stack overflow errors. -## Explanation +## Detailed Explanation of Trampoline Pattern with Real-World Examples Real-world example @@ -28,13 +30,13 @@ Real-world example In plain words -> Trampoline pattern allows recursion without running out of stack memory. +> The Trampoline pattern in Java allows efficient recursion without running out of stack memory, optimizing deep recursive calls for better performance and stack safety. Wikipedia says > In Java, trampoline refers to using reflection to avoid using inner classes, for example in event listeners. The time overhead of a reflection call is traded for the space overhead of an inner class. Trampolines in Java usually involve the creation of a GenericListener to pass events to an outer class. -**Programmatic Example** +## Programmatic Example of Trampoline Pattern in Java Here's the `Trampoline` implementation in Java. @@ -120,14 +122,14 @@ Program output: 19:22:24.472 [main] INFO com.iluwatar.trampoline.TrampolineApp - The number of orcs perished in the war: 3628800 ``` -## Applicability +## When to Use the Trampoline Pattern in Java Use the Trampoline pattern when * When dealing with algorithms that use recursion heavily and risk running into stack overflow errors. * When tail-call optimization is not supported by the Java language natively. -## Tutorials +## Trampoline Pattern Java Tutorials * [Laziness, trampolines, monoids and other functional amenities: This is not your father's Java(Mario Fusco)](https://www.slideshare.net/mariofusco/lazine) * [Trampoline.java (totallylazy)](https://github.com/bodar/totallylazy/blob/master/src/com/googlecode/totallylazy/Trampoline.java) @@ -135,13 +137,13 @@ Use the Trampoline pattern when * [Trampolining: A practical guide for awesome Java Developers (John McClean)](https://medium.com/@johnmcclean/trampolining-a-practical-guide-for-awesome-java-developers-4b657d9c3076) * [What is a trampoline function? (Stack Overflow)](https://stackoverflow.com/questions/189725/what-is-a-trampoline-function) -## Known Uses +## Real-World Applications of Trampoline Pattern in Java * Implementing algorithms that require deep recursion, such as certain tree traversals, combinatorial algorithms, and mathematical computations. * Functional programming libraries and frameworks where tail-call optimization is necessary for performance and stack safety. * [cyclops-react](https://github.com/aol/cyclops-react) -## Consequences +## Benefits and Trade-offs of Trampoline Pattern Benefits: @@ -154,13 +156,13 @@ Trade-offs: * May introduce additional complexity in terms of understanding and implementing the trampoline mechanism. * Requires converting naturally recursive algorithms into a continuation-passing style. -## Related Patterns +## Related Java Design Patterns * [Iterator](https://java-design-patterns.com/patterns/iterator/): Both patterns aim to transform potentially recursive operations into iterative processes, though the iterator pattern is more general-purpose. * [State](https://java-design-patterns.com/patterns/state/): Like the Trampoline, the State pattern can also handle complex state transitions, which can sometimes involve recursive-like state changes. * [Strategy](https://java-design-patterns.com/patterns/strategy/): This pattern can be related in terms of defining a family of algorithms (or continuations in the case of the Trampoline) and making them interchangeable. -## Credits +## References and Credits * [Functional Programming in Java](https://amzn.to/3JUIc5Q) * [Functional Programming for Java Developers: Tools for Better Concurrency, Abstraction, and Agility](https://amzn.to/4dRu4rJ) diff --git a/transaction-script/README.md b/transaction-script/README.md index b3fc87ece..dacc95a04 100644 --- a/transaction-script/README.md +++ b/transaction-script/README.md @@ -1,24 +1,26 @@ --- -title: Transaction Script +title: "Transaction Script Pattern in Java: Simplifying Business Logic with Consolidated Scripts" +shortTitle: Transaction Script +description: "Explore the Transaction Script design pattern for Java applications. Learn how to organize simple business logic into efficient scripts with real-world examples and improve your coding efficiency." category: Data access language: en tag: - - Business - - Data access - - Domain - - Persistence - - Transactions + - Business + - Data access + - Domain + - Persistence + - Transactions --- ## Also known as * Scripted Transactions -## Intent +## Intent of Transaction Script Design Pattern -Organize business logic by procedures where each procedure handles a single request from the presentation. +The Transaction Script pattern in Java organizes business logic by procedures where each procedure handles a single request from the presentation. -## Explanation +## Detailed Explanation of Transaction Script Pattern with Real-World Examples Real-world example @@ -32,9 +34,9 @@ Wikipedia says > The Transaction Script design pattern is a straightforward way to organize business logic in applications, particularly suitable for scenarios where each request from the presentation layer can be handled by a single procedure. This pattern is often used in simple applications or in systems where rapid development and ease of understanding are crucial. Each transaction script is responsible for a particular task, such as processing an order or calculating a result, and typically interacts directly with the database. -**Programmatic example** +## Programmatic Example of Transaction Script Pattern in Java -Our programmatic example is about booking hotel rooms. +Our Transaction Script pattern in Java example is about booking hotel rooms. The `Hotel` class takes care of booking and cancelling room reservations. @@ -230,26 +232,27 @@ Console output: This pattern is suitable for simple business logic and can be easily understood and maintained. -## Applicability +## When to Use the Transaction Script Pattern in Java * Use when business logic is simple and can be easily organized into individual procedures. * Suitable for applications with simple transaction requirements or where the logic doesn't justify complex architectures like Domain Model. -## Tutorials +## Transaction Script Pattern Java Tutorials * [Transaction Script Pattern (DZone)](https://dzone.com/articles/transaction-script-pattern#:~:text=Transaction%20Script%20(TS)%20is%20the,need%20big%20architecture%20behind%20them.) * [Transaction Script (InformIT)](https://www.informit.com/articles/article.aspx?p=1398617) -### Known Uses +## Real-World Applications of Transaction Script Pattern in Java * Early-stage startups and small-scale applications where rapid development is crucial. * Enterprise applications with well-defined procedures like banking transactions or e-commerce order processing. * Legacy systems where business logic is already written as scripts. -## Consequences +## Benefits and Trade-offs of Transaction Script Pattern Benefits: +* Leveraging the Transaction Script pattern enhances code simplicity and accelerates development cycles, especially in startup environments. * Simple and straightforward to implement. * Easy to understand and maintain for straightforward business logic. * Fast development cycle for small applications. @@ -260,13 +263,13 @@ Trade-offs: * Not suitable for complex business logic; can become unmanageable as the application grows. * Harder to test in isolation compared to more structured approaches like Domain Model. -## Related patterns +## Related Java Design Patterns * [Domain Model](https://java-design-patterns.com/patterns/domain-model/): Unlike Transaction Script, Domain Model organizes business logic around the data model and is better suited for complex business rules. * [Service Layer](https://java-design-patterns.com/patterns/service-layer/): Often used together with Transaction Script to define an application's boundary and encapsulate the business logic. * [Table Module](https://java-design-patterns.com/patterns/table-module/): Similar to Transaction Script but organizes logic using a single class per table rather than a procedure per request. -## Credits +## References and Credits * [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/3WcFVui) * [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/twin/README.md b/twin/README.md index 532e67a80..b2913e0a9 100644 --- a/twin/README.md +++ b/twin/README.md @@ -1,19 +1,21 @@ --- -title: Twin +title: "Twin Pattern in Java: Doubling Functionality with Synchronized Twins" +shortTitle: Twin +description: "Explore the Twin design pattern in Java with examples. Learn how to implement flexible, decoupled systems without multiple inheritance for enhanced modularity and system resilience. Ideal for software developers looking to advance their coding practices." category: Structural language: en tag: - - Decoupling - - Object composition - - Performance - - Resilience + - Decoupling + - Object composition + - Performance + - Resilience --- -## Intent +## Intent of Twin Design Pattern -To provide a way to handle multiple, related classes in a manner that allows them to work together without inheriting from a common base class. +The Twin design pattern in Java provides a way to handle multiple, related classes in a manner that allows them to work together without inheriting from a common base class. -## Explanation +## Detailed Explanation of Twin Pattern with Real-World Examples Real-world example @@ -29,7 +31,7 @@ Wikipedia says > The Twin pattern is a software design pattern that allows developers to simulate multiple inheritance in languages that don't support it. Instead of creating a single class inheriting from multiple parents, two closely linked subclasses are created, each inheriting from one of the parents. These subclasses are mutually dependent, working together as a pair to achieve the desired functionality. This approach avoids the complications and inefficiencies often associated with multiple inheritance, while still allowing the reuse of functionalities from different classes. -**Programmatic Example** +## Programmatic Example of Twin Pattern in Java Consider a game where a ball needs to function as both a `GameItem` and a `Thread`. Instead of inheriting from both, we use the Twin pattern with two closely linked objects: `BallItem` and `BallThread`. @@ -188,22 +190,22 @@ Console output: This setup allows `BallItem` and `BallThread` to act together as a single cohesive unit in the game, leveraging the capabilities of both `GameItem` and `Thread` without multiple inheritance. -## Applicability +## When to Use the Twin Pattern in Java * Use when you need to decouple classes that share common functionality but cannot inherit from a common base class due to various reasons such as the use of different frameworks or languages. * Useful in performance-critical applications where inheritance might introduce unnecessary overhead. * Applicable in systems requiring resilience through the ability to replace or update one of the twins without affecting the other. -## Tutorials +## Twin Pattern Java Tutorials * [Twin – A Design Pattern for Modeling Multiple Inheritance (Hanspeter Mössenböck)](http://www.ssw.uni-linz.ac.at/Research/Papers/Moe99/Paper.pdf) -## Known Uses +## Real-World Applications of Twin Pattern in Java * User interfaces where different frameworks are used for rendering and logic. * Systems integrating legacy code with new implementations where direct inheritance is not feasible. -## Consequences +## Benefits and Trade-offs of Twin Pattern Benefits: @@ -216,13 +218,13 @@ Trade-offs: * Can lead to code duplication if not managed properly. * Increased complexity in managing the interaction between twin classes. -## Related Patterns +## Related Java Design Patterns * [Adapter](https://java-design-patterns.com/patterns/adapter/): Both patterns deal with compatibility issues, but Adapter focuses on converting interfaces while Twin deals with class collaboration without inheritance. * [Bridge](https://java-design-patterns.com/patterns/bridge/): Similar in decoupling abstraction from implementation, but Twin specifically avoids inheritance. * [Proxy](https://java-design-patterns.com/patterns/proxy/): Manages object access, similar to how Twin handles interaction, but Proxy typically focuses on control and logging. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525) diff --git a/type-object/README.md b/type-object/README.md index 25206f8ad..dbdd6a405 100644 --- a/type-object/README.md +++ b/type-object/README.md @@ -1,16 +1,18 @@ --- -title: Type Object +title: "Type Object Pattern in Java: Enhancing Flexibility with Dynamic Class Definitions" +shortTitle: Type Object +description: "Discover how the Type Object Pattern in Java allows for dynamic and flexible class creation without altering existing code. Ideal for developers looking to understand and apply this powerful design pattern in real-world Java applications." category: Creational language: en tag: - - Abstraction - - Code simplification - - Data processing - - Game programming - - Extensibility - - Instantiation - - Object composition - - Polymorphism + - Abstraction + - Code simplification + - Data processing + - Game programming + - Extensibility + - Instantiation + - Object composition + - Polymorphism --- ## Also known as @@ -18,11 +20,11 @@ tag: * Type Descriptor * Type Safe Enumeration -## Intent +## Intent of Type Object Design Pattern Allow creation of flexible and extensible sets of related types. -## Explanation +## Detailed Explanation of Type Object Pattern with Real-World Examples Real-world example @@ -30,15 +32,15 @@ Real-world example In plain words -> The Type Object pattern allows for the creation and management of flexible and extensible sets of related types dynamically, without modifying existing code. +> Explore how the Java Type Object pattern enables dynamic creation and management of flexible and extensible sets of related classes, ideal for Java developers seeking modularity without modifying existing codebase. gameprogrammingpatterns.com says > Define a type object class and a typed object class. Each type object instance represents a different logical type. Each typed object stores a reference to the type object that describes its type. -**Programmatic example** +## Programmatic Example of Type Object Pattern in Java -The Type Object pattern is a design pattern that allows for the creation of flexible and reusable objects by creating a class with a field that represents the 'type' of the object. This pattern is useful when the types needed are not known upfront, or when there is a need to modify or add new types conveniently without recompiling repeatedly. +The Type Object pattern is a design pattern that allows for the creation of flexible and reusable objects by creating a class with a field that represents the 'type' of the object. This design pattern proves invaluable for scenarios where anticipated Java types are undefined upfront, or when modifications or additions are required, ensuring efficient Java development without frequent recompilations. In the provided code, the Type Object pattern is implemented in a mini candy-crush game. The game has many different candies, which may change over time as the game is upgraded. @@ -205,12 +207,12 @@ public class App { Let's break down what happens in `App` class. 1. The `main` method is the entry point of the application. It starts by initializing several variables: - - `givenTime` is set to 50 milliseconds. This is the time limit for the game. - - `toWin` is set to 500 points. This is the target score to win the game. - - `pointsWon` is initialized to 0. This variable keeps track of the total points won so far. - - `numOfRows` is set to 3. This is the number of rows in the game grid. - - `start` and `end` are both set to the current system time in milliseconds. These variables are used to track the elapsed time. - - `round` is initialized to 0. This variable keeps track of the current round number. + - `givenTime` is set to 50 milliseconds. This is the time limit for the game. + - `toWin` is set to 500 points. This is the target score to win the game. + - `pointsWon` is initialized to 0. This variable keeps track of the total points won so far. + - `numOfRows` is set to 3. This is the number of rows in the game grid. + - `start` and `end` are both set to the current system time in milliseconds. These variables are used to track the elapsed time. + - `round` is initialized to 0. This variable keeps track of the current round number. 2. The game enters a loop that continues until either the player has won enough points (`pointsWon >= toWin`) or the time limit has been reached (`end - start < givenTime`). @@ -292,7 +294,7 @@ Console output: In this implementation, the Type Object pattern allows for the flexible creation of `Candy` objects. The type of each candy is determined at runtime by parsing a JSON file, which makes it easy to add, modify, or remove candy types without having to recompile the code. -## Applicability +## When to Use the Type Object Pattern in Java This pattern can be used when: @@ -301,17 +303,17 @@ This pattern can be used when: * Suitable for situations where the number of types is large and may change over time. * The difference between the different 'types' of objects is the data, not the behaviour. -## Tutorials +## Type Object Pattern Java Tutorials * [Types as Objects Pattern (Jon Pearce)](http://www.cs.sjsu.edu/~pearce/modules/patterns/analysis/top.htm) -## Known uses +## Real-World Applications of Type Object Pattern in Java * Java Collections Framework: Utilizing various collection types like List, Set, and Map. * Graphics Libraries: Defining different shapes with specific properties and behaviors. * Game Development: Creating different types of characters or items with unique attributes and behaviors. -## Consequences +## Benefits and Trade-offs of Type Object Pattern Benefits: @@ -324,13 +326,13 @@ Trade-offs: * Can increase complexity if not managed properly. * May lead to performance overhead due to dynamic type checking and handling. -## Related patterns +## Related Java Design Patterns * [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Often used in conjunction with Type Object to create instances of the types. * [Strategy](https://java-design-patterns.com/patterns/strategy/): Similar in that it defines a family of algorithms or behaviors, but focuses more on interchangeable behaviors. * [Prototype](https://java-design-patterns.com/patterns/prototype/): Can be used to create new instances by copying existing ones, supporting dynamic and flexible type creation. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/unit-of-work/README.md b/unit-of-work/README.md index fcbc2f189..5b490d296 100644 --- a/unit-of-work/README.md +++ b/unit-of-work/README.md @@ -1,23 +1,25 @@ --- -title: Unit Of Work +title: "Unit of Work Pattern in Java: Orchestrating Efficient Transaction Management" +shortTitle: Unit of Work +description: "Discover how the Unit of Work pattern can streamline your Java applications. This guide offers a comprehensive explanation, real-world applications, and code examples to enhance your project’s efficiency and maintain data integrity." category: Data access language: en tag: - - Data access - - Decoupling - - Persistence - - Transactions + - Data access + - Decoupling + - Persistence + - Transactions --- -## Intent +## Intent of Unit Of Work Design Pattern -The Unit of Work pattern maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems. +Learn how the Java Unit of Work pattern expertly manages and maintains a list of objects impacted by business transactions, coordinating database changes and solving concurrency issues effectively. -## Explanation +## Detailed Explanation of Unit Of Work Pattern with Real-World Examples Real-world example -> Imagine a library where a librarian tracks all the books that are borrowed and returned throughout the day. Instead of updating the library's inventory system every time a single transaction occurs, the librarian keeps a list of all the changes and updates the system once at the end of the day. This approach ensures that all changes are processed together, maintaining the integrity of the inventory and reducing the number of individual updates needed. This is analogous to the Unit of Work pattern in software, where all changes to a set of objects are tracked and committed as a single transaction to maintain consistency and efficiency. +> Consider a library scenario where a librarian meticulously tracks all books borrowed and returned, utilizing the Unit of Work design pattern to update the inventory system efficiently. Instead of updating the library's inventory system every time a single transaction occurs, the librarian keeps a list of all the changes and updates the system once at the end of the day. This approach ensures that all changes are processed together, maintaining the integrity of the inventory and reducing the number of individual updates needed. This is analogous to the Unit of Work pattern in software, where all changes to a set of objects are tracked and committed as a single transaction to maintain consistency and efficiency. In plain words @@ -27,7 +29,7 @@ In plain words > Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems. -**Programmatic Example** +## Programmatic Example of Unit of Work Pattern in Java Arms dealer has a database containing weapon information. Merchants all over the town are constantly updating this information causing a high load on the database server. To make the load more manageable we apply to Unit of Work pattern to send many small updates in batches. @@ -176,25 +178,25 @@ Here is the console output. 21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Commit finished. ``` -## Applicability +## When to Use the Unit Of Work Pattern in Java -* Use when you need to manage multiple operations that need to be treated as a single transaction. +* he Unit of Work pattern is ideal for managing multiple database operations in Java that must be executed as a single transaction, ensuring data consistency and integrity. * Ideal in scenarios where changes to the business objects must be tracked and saved in a coordinated manner. * Useful when working with object-relational mapping (ORM) frameworks in Java such as Hibernate. -## Tutorials +## Unit Of Work Pattern Java Tutorials * [Repository and Unit of Work Pattern (Wolfgang Ofner)](https://www.programmingwithwolfgang.com/repository-and-unit-of-work-pattern/) * [Unit Of Work Design Pattern (Code Project)](https://www.codeproject.com/Articles/581487/Unit-of-Work-Design-Pattern) * [Unit of Work - a Design Pattern (Mono)](https://mono.software/2017/01/13/unit-of-work-a-design-pattern/) -## Known Uses +## Real-World Applications of Unit of Work Pattern in Java * Implementations in Java-based ORM frameworks like Hibernate. * Enterprise applications where multiple database operations need to be atomic. * Complex transactional systems where multiple objects are modified and persisted together. -## Consequences +## Benefits and Trade-offs of Unit Of Work Pattern Benefits: @@ -207,13 +209,13 @@ Trade-offs: * Can introduce complexity in managing the life cycle of objects within the unit of work. * Potential performance overhead if not managed properly, especially with large datasets. -## Related Patterns +## Related Java Design Patterns * [Identity Map](https://java-design-patterns.com/patterns/identity-map/): Helps to ensure that each object is only loaded once per transaction, reducing redundancy and improving performance. * [Repository](https://java-design-patterns.com/patterns/repository/): Often used in conjunction with Unit of Work to abstract the persistence logic and provide a cleaner way to access data. * [Transaction Script](https://java-design-patterns.com/patterns/transaction-script/): While different in its procedural approach, it can complement Unit of Work by managing transactional logic at a higher level. -## Credits +## References and Credits * [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3wlDrze) * [Java Persistence with Hibernate](https://amzn.to/44tP1ox) diff --git a/update-header.sh b/update-header.sh new file mode 100755 index 000000000..48da4dcd6 --- /dev/null +++ b/update-header.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +# Find all README.md files in subdirectories one level deep +# and replace "### " with "## " at the beginning of lines +find . -maxdepth 2 -type f -name "README.md" -exec sed -i '' 's/^### /## /' {} \; + +echo "Headers updated in README.md files." diff --git a/update-method/README.md b/update-method/README.md index 186f1ed8f..bd1fa2f75 100644 --- a/update-method/README.md +++ b/update-method/README.md @@ -1,25 +1,27 @@ --- -title: Update Method +title: "Update Method Pattern in Java: Enhancing Game Loop Efficiency with Systematic Updates" +shortTitle: Update Method +description: "Explore the Update Method design pattern for Java, ideal for real-time games and applications. Learn how it optimizes performance by updating objects frame-by-frame to maintain synchronized, efficient operations." category: Behavioral language: en tag: - - Abstraction - - Data processing - - Decoupling - - Event-driven - - Game programming - - Polymorphism + - Abstraction + - Data processing + - Decoupling + - Event-driven + - Game programming + - Polymorphism --- ## Also known as * Update Mechanism -## Intent +## Intent of Update Method Design Pattern -Update method pattern simulates a collection of independent objects by telling each to process one frame of behavior at a time. +The Update Method pattern in Java simulates a collection of independent objects by telling each to process one frame of behavior at a time. -## Explanation +## Detailed Explanation of Update Method Pattern with Real-World Examples Real-world example @@ -33,9 +35,9 @@ gameprogrammingpatterns.com says > The game world maintains a collection of objects. Each object implements an update method that simulates one frame of the object’s behavior. Each frame, the game updates every object in the collection. -**Programmatic Example** +## Programmatic Example of Update Method Pattern in Java -The Update Method design pattern is a behavioral pattern that simulates a collection of independent objects by telling each to process one frame of behavior at a time. This pattern is commonly used in game development, where each object in the game world needs to be updated once per frame. +The Update Method design pattern is a behavioral pattern that simulates a collection of independent game or application objects by telling each to process one frame of behavior at a time. This pattern is commonly used in game development, where each object in the game world needs to be updated once per frame. The `World` class represents the game world. It maintains a list of entities (`List entities`) and a boolean flag (`isRunning`) to indicate whether the game is running. @@ -183,19 +185,20 @@ Console output: This is a basic implementation of the Update Method pattern. In a real-world application, the `Entity` class would likely have additional methods and properties, and the `update` method would contain more complex logic to simulate the entity's behavior. -## Applicability +## When to Use the Update Method Pattern in Java Update Method works well when: +* Typically applied in scenarios where multiple objects need synchronous updates without the overhead of manual synchronization, making it a go-to for advanced Java developers. * The application has a number of objects or systems that need to run simultaneously. * Each object’s behavior is mostly independent of the others. * The objects need to be simulated over time. -## Known Uses +## Real-World Applications of Update Method Pattern in Java * Real-time games and data processing applications where world objects need to be updated once per frame. -## Consequences +## Benefits and Trade-offs of Update Method Pattern Benefits: @@ -209,12 +212,12 @@ Trade-offs: * The state needs to be stored to enable resuming updates after each frame * Entities are simulated each frame, but they are not truly concurrent -## Related Patterns +## Related Java Design Patterns * [Component](https://java-design-patterns.com/patterns/component/): Often used in game development to allow entities to be composed of various components, each potentially having its own update method. * [Game Loop](https://java-design-patterns.com/patterns/game-loop/): Continuously updates game state and renders the game, which may include the Update Method for various game objects. -## Credits +## References and Credits * [Game Programming Patterns](https://amzn.to/3wLTbvr) * [Game Programming Patterns - Update Method](http://gameprogrammingpatterns.com/update-method.html) diff --git a/value-object/README.md b/value-object/README.md index 33226a0bb..88478b931 100644 --- a/value-object/README.md +++ b/value-object/README.md @@ -1,17 +1,19 @@ --- -title: Value Object +title: "Value Object Pattern in Java: Enhancing Performance with Immutable Data Types" +shortTitle: Value Object +description: "Explore the Value Object pattern in Java with our in-depth guide. Learn how immutable objects enhance performance and memory efficiency in software design. Ideal for developers looking to optimize Java applications." category: Structural language: en tag: - - Data access - - Data binding - - Domain - - Encapsulation - - Enterprise patterns - - Immutable - - Optimization - - Performance - - Persistence + - Data access + - Data binding + - Domain + - Encapsulation + - Enterprise patterns + - Immutable + - Optimization + - Performance + - Persistence --- ## Also known as @@ -21,15 +23,15 @@ tag: * Inline Value * Integrated Value -## Intent +## Intent of Value Object Design Pattern -To create immutable objects that represent a descriptive aspect of the domain with no conceptual identity. It aims to enhance performance and reduce memory overhead by storing frequently accessed immutable data directly within the object that uses it, rather than separately. +The Value Object pattern in Java creates immutable objects that represent a descriptive aspect of the domain with no conceptual identity. It aims to enhance performance and reduce memory overhead by storing frequently accessed immutable data directly within the object that uses it, rather than separately. -## Explanation +## Detailed Explanation of Value Object Pattern with Real-World Examples Real-world example -> Consider the case of a business card. In the real world, a business card contains information such as the person's name, job title, phone number, and email address. This information represents a specific and complete set of attributes describing the contact details of an individual but doesn't have an identity itself beyond this information. +> Consider the case of a business card. In our example, a BusinessCard class is implemented as a Value Object to demonstrate immutable data handling and efficiency in Java applications. In the real world, a business card contains information such as the person's name, job title, phone number, and email address. This information represents a specific and complete set of attributes describing the contact details of an individual but doesn't have an identity itself beyond this information. > > In a software system, you can create a `BusinessCard` class as a Value Object. This class would be immutable, meaning once a `BusinessCard` object is created with a person's details, those details cannot change. If you need a different business card, you create a new instance rather than modifying the existing one. The equality of two `BusinessCard` objects would be based on their contained data rather than their memory addresses, ensuring that two business cards with the same details are considered equal. This mirrors how business cards in real life are used and compared based on their content, not on the physical card itself. @@ -41,7 +43,7 @@ Wikipedia says > In computer science, a value object is a small object that represents a simple entity whose equality is not based on identity: i.e. two value objects are equal when they have the same value, not necessarily being the same object. -**Programmatic Example** +## Programmatic Example of Value Object Pattern in Java There is a class for hero statistics in a role-playing game. The statistics contain attributes such as strength, intelligence, and luck. The statistics of different heroes should be equal when all the attributes are equal. @@ -84,10 +86,11 @@ Here's the console output. 20:11:12.203 [main] INFO com.iluwatar.value.object.App - Is statA and statC equal : false ``` -## Applicability +## When to Use the Value Object Pattern in Java Use the Value Object when +* Apply the Value Object pattern when you need high-performance Java applications with reduced memory overhead, especially in systems requiring efficient data management. * When representing a set of attributes that together describe an entity but without an identity. * When the equality of the objects is based on the value of the properties, not the identity. * When you need to ensure that objects cannot be altered once created. @@ -95,11 +98,11 @@ Use the Value Object when * Memory footprint reduction is critical, especially in environments with limited resources. * Objects frequently access a particular piece of immutable data. -## Tutorials +## Value Object Pattern Java Tutorials * [VALJOs - Value Java Objects (Stephen Colebourne)](http://blog.joda.org/2014/03/valjos-value-java-objects.html) -## Known uses +## Real-World Applications of Value Object Pattern in Java * Implementing complex data types like monetary values, measurements, and other domain-specific values. * [java.util.Optional](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html) @@ -107,7 +110,7 @@ Use the Value Object when * [java.awt.Color](https://docs.oracle.com/javase/8/docs/api/java/awt/Color.html) * [joda-time, money, beans](http://www.joda.org/) -## Consequences +## Benefits and Trade-offs of Value Object Pattern Benefits: @@ -124,7 +127,7 @@ Trade-offs: * Increases complexity in object design and can lead to tightly coupled systems. * Modifying the embedded value necessitates changes across all objects that embed this value, which can complicate maintenance. -## Related Patterns +## Related Java Design Patterns * [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Often used to create instances of value objects. * [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Shares objects to support large quantities using a minimal amount of memory, somewhat similar in intent but different in implementation. @@ -132,7 +135,7 @@ Trade-offs: * [Prototype](https://java-design-patterns.com/patterns/prototype/): Can be used to clone existing value objects, though cloning is less common with immutable objects. * [Singleton](https://java-design-patterns.com/patterns/singleton/): Ensures a class has only one instance and provides a global point of access to it, can be used to manage a shared embedded value. -## Credits +## References and Credits * [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3wlDrze) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/version-number/README.md b/version-number/README.md index 46445f7ee..6178f2317 100644 --- a/version-number/README.md +++ b/version-number/README.md @@ -1,13 +1,15 @@ --- -title: Version Number +title: "Version Number Pattern in Java: Implementing Robust Version Management in Java Applications" +shortTitle: Version Number +description: "Explore the Version Number pattern in Java to manage concurrent data access and maintain data integrity. Learn how to implement it effectively with examples and best practices." category: Data access language: en tag: - - Compatibility - - Data access - - Persistence - - State tracking - - Versioning + - Compatibility + - Data access + - Persistence + - State tracking + - Versioning --- ## Also known as @@ -15,11 +17,11 @@ tag: * Entity Versioning * Versioning -## Intent +## Intent of Version Number Design Pattern -Ensure data consistency and integrity by tracking changes to data with version numbers. +Ensure data consistency and integrity in Java applications by tracking changes with version numbers—a crucial component of concurrent data management. -## Explanation +## Detailed Explanation of Version Number Pattern with Real-World Examples Real-world example @@ -27,13 +29,13 @@ Real-world example In plain words -> Version Number pattern grants protection against concurrent updates to same entity. +> The Version Number pattern in Java provides robust protection against concurrent updates, ensuring reliable data versioning in distributed systems. Wikipedia says > The Version Number pattern is a technique used to manage concurrent access to data in databases and other data stores. It involves associating a version number with each record, which is incremented every time the record is updated. This pattern helps ensure that when multiple users or processes attempt to update the same data simultaneously, conflicts can be detected and resolved. -**Programmatic Example** +## Programmatic Example of Version Number Pattern in Java Alice and Bob are working on the book, which stored in the database. Our heroes are making changes simultaneously, and we need some mechanism to prevent them from overwriting each other. @@ -147,19 +149,19 @@ Program output: 14:51:04.123 [main] INFO com.iluwatar.versionnumber.App -- Exception: Tried to update stale version 0 while actual version is 1 ``` -## Applicability +## When to Use the Version Number Pattern in Java * Use when you need to handle concurrent data modifications in a distributed system. * Suitable for systems where data consistency and integrity are crucial. * Ideal for applications using databases that support versioning or row versioning features. -## Tutorials +## Version Number Pattern Java Tutorials * [JPA entity versioning (byteslounge.com)](https://www.byteslounge.com/tutorials/jpa-entity-versioning-version-and-optimistic-locking) * [Optimistic Locking in JPA (Baeldung)](https://www.baeldung.com/jpa-optimistic-locking) * [Versioning Entity (java2s.com)](http://www.java2s.com/Tutorial/Java/0355__JPA/VersioningEntity.htm) -## Known Uses +## Real-World Applications of Version Number Pattern in Java * Hibernate (Java Persistence API) uses version numbers to implement optimistic locking. * Microsoft SQL Server and Oracle databases support version-based concurrency control. @@ -167,7 +169,7 @@ Program output: * [Elasticsearch](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#index-versioning) * [Apache Solr](https://lucene.apache.org/solr/guide/6_6/updating-parts-of-documents.html) -## Consequences +## Benefits and Trade-offs of Version Number Pattern Benefits: @@ -181,12 +183,12 @@ Trade-offs: * Can lead to increased complexity in database schema and application logic. * Potential performance overhead due to version checks and conflict resolution. -## Related Patterns +## Related Java Design Patterns * [Optimistic Offline Lock](https://java-design-patterns.com/patterns/optimistic-offline-lock/): Uses version numbers to detect conflicts rather than preventing them from occurring. * Pessimistic Offline Lock: An alternative approach to concurrency control where data is locked for updates to prevent conflicts. -## Credits +## References and Credits * [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/3y6yv1z) * [J2EE Design Patterns](https://amzn.to/4dpzgmx) diff --git a/virtual-proxy/README.md b/virtual-proxy/README.md index d37f35b25..e5b32fd09 100644 --- a/virtual-proxy/README.md +++ b/virtual-proxy/README.md @@ -1,11 +1,13 @@ --- -title: Virtual Proxy +title: "Virtual Proxy Pattern in Java: Enhancing Performance with Lazy Loading Techniques" +shortTitle: Virtual Proxy +description: "Explore the Virtual Proxy Design Pattern in Java to improve your applications. Learn how this pattern optimizes performance and manages resources efficiently by controlling the creation and access of resource-intensive objects. Ideal for developers looking to enhance system responsiveness." category: Structural language: en tag: - - Caching - - Decoupling - - Lazy initialization + - Caching + - Decoupling + - Lazy initialization --- ## Also known as @@ -13,15 +15,15 @@ tag: * Lazy Initialization Proxy * Virtual Surrogate -## Intent +## Intent of Virtual Proxy Design Pattern -Provide a surrogate or placeholder for another object to control its creation and access, particularly when dealing with resource-intensive operations. +The Virtual Proxy Design Pattern is a crucial component in Java design patterns, enabling efficient resource management and performance optimization through controlled object creation. It provides a surrogate or placeholder for another object to control its creation and access, particularly when dealing with resource-intensive operations. -## Explanation +## Detailed Explanation of Virtual Proxy Pattern with Real-World Examples Real-world example -> Imagine a high-end art gallery that showcases expensive and delicate pieces of art. To protect the actual artwork and reduce the risk of damage or theft, the gallery initially displays high-quality photographs of the artworks. When a serious buyer expresses genuine interest, the gallery then brings out the original artwork from a secure storage area for viewing. +> Just as a high-end art gallery uses photographs to save resources and reduce risks, the Virtual Proxy Pattern in Java manages resource-intensive operations by displaying only necessary objects, significantly enhancing system efficiency. To protect the actual artwork and reduce the risk of damage or theft, the gallery initially displays high-quality photographs of the artworks. When a serious buyer expresses genuine interest, the gallery then brings out the original artwork from a secure storage area for viewing. > > In this analogy, the high-quality photograph serves as the virtual proxy for the actual artwork. The real artwork is only fetched and displayed when truly necessary, thus saving resources and reducing risk, similar to how the Virtual Proxy pattern defers object creation until it is needed. @@ -33,7 +35,9 @@ Wikipedia says > A proxy that controls access to a resource that is expensive to create. -**Programmatic Example** +## Programmatic Example of Virtual Proxy Pattern in Java + +The Virtual Proxy design pattern in Java can optimize resource utilization and system performance. Consider an online video streaming platform where video objects are resource-intensive due to their large data size and required processing power. To efficiently manage resources, the system uses a virtual proxy to handle video objects. The virtual proxy defers the creation of actual video objects until they are explicitly required for playback, thus saving system resources and improving response times for users. @@ -109,7 +113,7 @@ Program output: 14:54:30.604 [main] INFO com.iluwatar.virtual.proxy.RealVideoObject -- Processing and playing video content... ``` -## Applicability +## When to Use the Virtual Proxy Pattern in Java Use the Virtual Proxy pattern when: @@ -117,11 +121,11 @@ Use the Virtual Proxy pattern when: * The performance of a system can be significantly improved by deferring the creation of objects until they are needed. * There is a need for control over resource usage in systems dealing with large quantities of high-overhead objects. -## Tutorials +## Virtual Proxy Pattern Java Tutorials * [The Proxy Pattern in Java (Baeldung)](https://www.baeldung.com/java-proxy-pattern) -## Known Uses +## Real-World Applications of Virtual Proxy Pattern in Java * Lazy Initialization: Create objects only when they are actually needed. * Resource Management: Efficiently manage resources by creating heavy objects only on demand. @@ -131,7 +135,7 @@ Use the Virtual Proxy pattern when: * In Java, the `java.awt.Image` class uses virtual proxies to load images on demand. * Hibernate ORM framework uses proxies to implement lazy loading of entities. -## Consequences +## Benefits and Trade-offs of Virtual Proxy Pattern Benefits: @@ -143,13 +147,13 @@ Trade-offs: * Introduces complexity in the codebase. * Can lead to unexpected behaviors if not handled properly, especially in multithreaded environments. -## Related Patterns +## Related Java Design Patterns * [Proxy](https://java-design-patterns.com/patterns/proxy/): Virtual Proxy is a specific type of the Proxy pattern focused on lazy initialization. * [Lazy Loading](https://java-design-patterns.com/patterns/lazy-loading/): Directly related as the core idea of Virtual Proxy is to defer object creation. * [Decorator](https://java-design-patterns.com/patterns/decorator/): Similar in structure, but Decorators add behavior to the objects while proxies control access. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/visitor/README.md b/visitor/README.md index 2db1fcd7d..674062606 100644 --- a/visitor/README.md +++ b/visitor/README.md @@ -1,20 +1,22 @@ --- -title: Visitor +title: "Visitor Pattern in Java: Implementing Robust Operations Across Diverse Object Structures" +shortTitle: Visitor +description: "Explore the Visitor design pattern in Java with detailed examples and class diagrams. Learn how to implement operations without altering object structures for clean and maintainable code." category: Behavioral language: en tag: - - Decoupling - - Extensibility - - Gang of Four - - Object composition - - Polymorphism + - Decoupling + - Extensibility + - Gang of Four + - Object composition + - Polymorphism --- -## Intent +## Intent of Visitor Design Pattern To represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. -## Explanation +## Detailed Explanation of Visitor Pattern with Real-World Examples Real-world example @@ -24,13 +26,13 @@ Real-world example In plain words -> Visitor pattern defines operations that can be performed on the nodes of the data structure. +> The Java Visitor pattern defines operations that can be performed on nodes of various data structures, enhancing Java application extensibility. Wikipedia says > In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying the structures. -**Programmatic Example** +## Programmatic Example of Visitor Pattern in Java Consider a tree structure with army units. Commander has two sergeants under it and each sergeant has three soldiers under them. Given that the hierarchy implements the visitor pattern, we can easily create new objects that interact with the commander, sergeants, soldiers, or all of them. @@ -219,25 +221,25 @@ Program output: 14:58:06.118 [main] INFO com.iluwatar.visitor.CommanderVisitor -- Good to see you commander ``` -## Class diagram +## Detailed Explanation of Visitor Pattern with Real-World Examples ![Visitor](./etc/visitor_1.png "Visitor") -## Applicability +## When to Use the Visitor Pattern in Java Use the Visitor pattern when -* Use the Visitor pattern when you need to perform an operation on a group of similar kinds of objects, and you want to avoid polluting their classes with this operation. +* Implement the Visitor design pattern in Java when you need to efficiently perform operations across groups of similar objects without modifying their classes, and you want to avoid polluting their classes with this operation. * Use it when a class structure is stable, but you need to perform new operations on the structure without changing it. * It's beneficial when the set of classes are fixed and only the operations need to be extended. -## Tutorials +## Visitor Pattern Java Tutorials * [Visitor (Refactoring Guru)](https://refactoring.guru/design-patterns/visitor) * [Visitor Pattern Tutorial with Java Examples (DZone)](https://dzone.com/articles/design-patterns-visitor) * [Visitor Design Pattern (Sourcemaking)](https://sourcemaking.com/design_patterns/visitor) -## Known uses +## Real-World Applications of Visitor Pattern in Java * Compiler design, where the Visitor pattern can be used for operations like pretty printing, semantic checks, etc. * Abstract Syntax Tree (AST) processing. @@ -247,7 +249,7 @@ Use the Visitor pattern when * [javax.lang.model.element.Element](http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/Element.html) and [Element Visitor](http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/ElementVisitor.html) * [java.nio.file.FileVisitor](http://docs.oracle.com/javase/8/docs/api/java/nio/file/FileVisitor.html) -## Consequences +## Benefits and Trade-offs of Visitor Pattern Benefits: @@ -261,13 +263,13 @@ Trade-offs: * Circular dependencies: In complex systems, this pattern can introduce circular dependencies between visitor and element classes. * Breaking encapsulation: Visitor pattern requires that the element classes expose enough details to allow the visitor to do its job, potentially breaking encapsulation. -## Related Patterns +## Related Java Design Patterns * [Composite](https://java-design-patterns.com/patterns/composite/): The Visitor pattern is often used in conjunction with the Composite pattern, where the visitor can perform operations over a composite structure. * [Interpreter](https://java-design-patterns.com/patterns/interpreter/): Visitors can be used to implement the non-terminal expressions in the Interpreter pattern. * [Strategy](https://java-design-patterns.com/patterns/strategy/): Visitor can be considered a way of making strategies work on objects that they were not designed to operate on. -## Credits +## References and Credits * [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) * [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)