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
This commit is contained in:
Ilkka Seppälä
2024-06-08 19:54:44 +03:00
committed by GitHub
parent cb946c0cdc
commit 6cd2d0353a
219 changed files with 3308 additions and 2819 deletions
+20 -18
View File
@@ -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)
+22 -20
View File
@@ -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)
+25 -17
View File
@@ -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)
+19 -17
View File
@@ -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)
+21 -17
View File
@@ -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 Adaptees 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 Adaptees 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)
+21 -21
View File
@@ -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)
+25 -21
View File
@@ -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 others 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)
+18 -16
View File
@@ -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)
+31 -17
View File
@@ -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)
+18 -14
View File
@@ -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)
+20 -18
View File
@@ -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)
+22 -15
View File
@@ -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 Blochs 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)
+26 -20
View File
@@ -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)
+22 -16
View File
@@ -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 games implementation language isnt 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 cant 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)
+24 -18
View File
@@ -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)
+18 -16
View File
@@ -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)
+20 -16
View File
@@ -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)
+21 -15
View File
@@ -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)
+15 -13
View File
@@ -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)
+23 -15
View File
@@ -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)
+21 -15
View File
@@ -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<Car> getSedanCarsOwnedSortedByDate(List<Person> 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)
+24 -19
View File
@@ -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)
@@ -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)
+22 -16
View File
@@ -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)
+22 -16
View File
@@ -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)
+17 -16
View File
@@ -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)
+25 -22
View File
@@ -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)
+17 -15
View File
@@ -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)
+18 -16
View File
@@ -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)
+20 -18
View File
@@ -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)
+25 -23
View File
@@ -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<T, U> {
@@ -65,7 +67,7 @@ public class Converter<T, U> {
}
```
The specialized converters inherit from this base class as follows.
Specialized converters inherit from this base class:
```java
public class UserConverter extends Converter<UserDto, User> {
@@ -84,7 +86,7 @@ public class UserConverter extends Converter<UserDto, User> {
}
```
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)
+22 -24
View File
@@ -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<Book>`, 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)
+21 -18
View File
@@ -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)
+19 -17
View File
@@ -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)
+20 -17
View File
@@ -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)
+21 -17
View File
@@ -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)
+18 -16
View File
@@ -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.
* ObjectRelational 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)
+17 -15
View File
@@ -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)
+21 -19
View File
@@ -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)
+16 -14
View File
@@ -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)
+18 -16
View File
@@ -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)
+24 -22
View File
@@ -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)
+22 -20
View File
@@ -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. Its 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)
+29 -27
View File
@@ -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)
+19 -17
View File
@@ -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)
+20 -18
View File
@@ -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)
+13 -11
View File
@@ -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)
+31 -21
View File
@@ -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)
+19 -17
View File
@@ -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.
* Javas 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)
+20 -18
View File
@@ -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)
+19 -16
View File
@@ -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)
+23 -17
View File
@@ -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)
+29 -15
View File
@@ -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)
+17 -15
View File
@@ -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)
+27 -20
View File
@@ -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)
+31 -27
View File
@@ -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)
+21 -17
View File
@@ -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)
+21 -19
View File
@@ -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)
+21 -19
View File
@@ -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)
+19 -17
View File
@@ -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)
+24 -22
View File
@@ -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 patterns 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)
+21 -19
View File
@@ -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)
+21 -19
View File
@@ -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 modelviewcontroller 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)
+22 -20
View File
@@ -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.
* Javas 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.
* Javas 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)
+21 -19
View File
@@ -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)
+26 -21
View File
@@ -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)
+19 -19
View File
@@ -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)
+20 -16
View File
@@ -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)
+21 -17
View File
@@ -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)
+21 -21
View File
@@ -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)
+18 -14
View File
@@ -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 systems 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)
@@ -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)

Before

Width:  |  Height:  |  Size: 145 KiB

After

Width:  |  Height:  |  Size: 145 KiB

@@ -32,7 +32,7 @@
<artifactId>java-design-patterns</artifactId>
<version>1.26.0-SNAPSHOT</version>
</parent>
<artifactId>hexagonal</artifactId>
<artifactId>hexagonal-architecture</artifactId>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>

Some files were not shown because too many files have changed in this diff Show More