* 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
title, shortTitle, description, category, language, tag
| title | shortTitle | description | category | language | tag | |||||
|---|---|---|---|---|---|---|---|---|---|---|
| Monostate Pattern in Java: Achieving Singleton Behavior with Class-Level State | Monostate | Learn how the Monostate design pattern works in Java. Discover its benefits, implementation details, and use cases. Perfect for ensuring shared state across multiple class instances. | Creational | en |
|
Also known as
- Borg
Intent of Monostate Design Pattern
The Monostate pattern is an alternative approach to achieving a singleton-like behavior in object-oriented design, ensuring a shared state in Java applications. It enforces a unique behavior where all instances of a class share the same state. Unlike the Singleton pattern, which restricts a class to a single instance, Monostate allows for multiple instances but ensures they all have a shared state.
Detailed Explanation of Monostate Pattern with Real-World Examples
Real-word example
Imagine a library with multiple desks where patrons can access the library's catalog. While each desk appears to be independent, any changes made to the catalog (like adding or removing a book) are immediately reflected at all desks. This setup ensures that no matter which desk a patron uses, they see the exact same, up-to-date catalog, similar to how the Monostate pattern maintains a shared state across all instances in Java. This is analogous to the Monostate pattern, where multiple instances of a class share the same state, ensuring consistent data across all instances.
In plain words
Monostate allows multiple instances of a class to share the same state by channeling their state management through a common shared structure. This ensures consistent state across all instances while maintaining the facade of independent objects.
wiki.c2.com says
A monostate is a "conceptual singleton" - all data members of a monostate are static, so all instances of the monostate use the same (static) data. Applications using a monostate can create any number of instances that they desire, as each instance uses the same data.
Programmatic Example of Monostate Pattern in Java
The Monostate pattern in Java ensures that all instances of a class share the same state, making it a great Singleton alternative for maintaining consistent data. This is achieved by using static fields in the class. Any changes to these fields will be reflected across all instances of the class. This pattern is useful when you want to avoid global variables but still need a shared state across multiple instances.
Let's take a look at the LoadBalancer class from the monostate module:
public class LoadBalancer {
private static List<Server> servers = new ArrayList<>();
private static int nextServerIndex = 0;
public LoadBalancer() {
// Initialize servers
servers.add(new Server("192.168.0.1", 8080, 1));
servers.add(new Server("192.168.0.2", 8080, 2));
servers.add(new Server("192.168.0.3", 8080, 3));
}
public void serverRequest(Request request) {
Server server = servers.get(nextServerIndex);
server.serve(request);
nextServerIndex = (nextServerIndex + 1) % servers.size();
}
}
In this class, servers and nextServerIndex are static fields. This means that they are shared across all instances of LoadBalancer. The method serverRequest is used to serve a request and then update the nextServerIndex to the next server in the list.
Now, let's see how this works in practice:
public class App {
public static void main(String[] args) {
LoadBalancer loadBalancer1 = new LoadBalancer();
LoadBalancer loadBalancer2 = new LoadBalancer();
// Both instances share the same state
loadBalancer1.serverRequest(new Request("Hello")); // Server 1 serves the request
loadBalancer2.serverRequest(new Request("Hello World")); // Server 2 serves the request
}
}
In this example, we create two instances of LoadBalancer: loadBalancer1 and loadBalancer2. They share the same state. When we make a request via loadBalancer1, the request is served by the first server. When we make a request via loadBalancer2, the request is served by the second server, not the first one, because the nextServerIndex has been updated by loadBalancer1. This demonstrates the Monostate pattern in action.
When to Use the Monostate Pattern in Java
Use the Monostate pattern in Java design patterns when
-
Shared State Across Instances: All instances of a class must share the same state. Changes in one instance should be reflected across all instances. Monostate offers more flexibility compared to the traditional Singleton pattern.
-
Transparent Usage: Unlike Singleton, which can be less transparent in its usage, Monostate allows for a more transparent way of sharing state across instances. Clients interact with instances of the Monostate class as if they were regular instances, unaware of the shared state.
-
Subclass Flexibility: Monostate provides an advantage over Singleton when it comes to extending behavior through subclasses. Subclasses of a Monostate class can introduce additional behavior or modify existing behavior while still sharing the same state as instances of the base class. This allows for dynamic and diverse behaviors across different parts of an application, all while maintaining a shared state.
-
Avoiding Global Variables: The pattern is applicable when you want to avoid global variables but still need a shared state across multiple instances.
-
Integration with Existing Systems: Monostate can be more easily integrated into existing systems that expect to work with instances rather than a single global instance. This can lead to a smoother transition when refactoring code to use shared state.
-
Consistent Configuration or State Management: In scenarios where you need consistent configuration management or state management across different parts of an application, Monostate provides a pattern to ensure all parts of the system are in sync.
Real-World Applications of Monostate Pattern in Java
- Configuration settings that need to be shared and accessible by various parts of an application.
- Resource pools where the state needs to be consistent across different consumers.
Benefits and Trade-offs of Monostate Pattern
Benefits:
- Provides a shared state without restricting the creation of multiple instances.
- Ensures consistency of data across instances.
Trade-offs:
- Can lead to hidden dependencies due to shared state, making the system harder to understand and debug.
- Reduces the flexibility to have instances with independent states.
Related Java Design Patterns
- Singleton: Both Singleton and Monostate patterns ensure a single shared state, but the Monostate pattern in Java allows for multiple instances with the same state, making it a unique object-oriented design approach.
- Flyweight: Flyweight shares state to reduce memory usage, similar to how Monostate shares state among instances.