Singleton
Intent Ensure a class only has one instance, and provide a global point of access to it. Explanation Real-world example There can only be one ivory tower where the wizards study their magic. The same enchanted ivory tower is always used by the wizards. The ivory tower here is a singleton. In plain words Ensures that only one object of a particular class is ever created. Wikipedia says In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object.
Step Builder
Intent An extension of the Builder pattern that fully guides the user through the creation of the object with no chances of confusion. The user experience will be much more improved by the fact that he will only see the next step methods available, NO build method until is the right time to build the object. Class diagram Applicability Use the Step Builder pattern when 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 when in the process of constructing the order is important.
Tolerant Reader
Intent Tolerant Reader is an integration pattern that helps creating robust communication systems. The idea is to be as tolerant as possible when reading data from another service. This way, when the communication schema changes, the readers must not break. Explanation Real world example We are persisting rainbowfish objects to file and later on they need to be restored. What makes it problematic is that rainbowfish data structure is versioned and evolves over time.
Unit Of Work
Intent When a business transaction is completed, all the updates are sent as one big unit of work to be persisted in one go to minimize database round-trips. Explanation Real-world example Arms dealer has a database containing weapon information. Merchants all over the town are constantly updating this information and it causes a high load on the database server. To make the load more manageable we apply to Unit of Work pattern to send many small updates in batches.
Value Object
Intent Provide objects which follow value semantics rather than reference semantics. This means value objects’ equality is not based on identity. Two value objects are equal when they have the same value, not necessarily being the same object. Explanation Real-world example There is a class for hero statistics in a role-playing game. The statistics contain attributes such as strength, intelligence, and luck. The statistics of different heroes should be equal when all the attributes are equal.
Async Method Invocation
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. Explanation Real world example Launching space rockets is an exciting business. The mission command gives an order to launch and after some undetermined time, the rocket either launches successfully or fails miserably.
Balking
Intent Balking Pattern is used to prevent an object from executing a certain code if it is in an incomplete or inappropriate state. Explanation Real world example 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. In plain words Using the balking pattern, a certain code executes only if the object is in particular state.
Event Queue
Intent The intent of the event queue design pattern, also known as message queues, is to decouple the relationship between the sender and receiver of events within a system. By decoupling the two parties, they do not interact with the event queue simultaneously. Essentially, the event queue handles and processes requests in an asynchronous manner, therefore, this system can be described as a first in, first out design pattern model. Event Queue is a suitable pattern if there is a resource with limited accessibility (i.
Event-based Asynchronous
Intent The Event-based Asynchronous Pattern makes available the advantages of multithreaded applications while hiding many of the complex issues inherent in multithreaded design. Using a class that supports this pattern can allow you to: Perform time-consuming tasks, such as downloads and database operations, “in the background,” without interrupting your application. Execute multiple operations simultaneously, receiving notifications when each completes. Wait for resources to become available without stopping (“hanging”) your application. Communicate with pending asynchronous operations using the familiar events-and-delegates model.
Guarded Suspension
Intent Use Guarded suspension pattern to handle a situation when you want to execute a method on object which is not in a proper state. Class diagram Applicability Use Guarded Suspension pattern when the developer knows that the method execution will be blocked for a finite period of time Related patterns Balking
Half-Sync/Half-Async
Intent The Half-Sync/Half-Async pattern decouples synchronous I/O from asynchronous I/O in a system to simplify concurrent programming effort without degrading execution efficiency. Class diagram Applicability Use Half-Sync/Half-Async pattern when a system possesses following characteristics: the system must perform tasks in response to external events that occur asynchronously, like hardware interrupts in OS it is inefficient to dedicate separate thread of control to perform synchronous I/O for each external source of event the higher level tasks in the system can be simplified significantly if I/O is performed synchronously.
Leader/Followers
Intent The Leader/Followers pattern provides a concurrency model where multiple threads can efficiently de-multiplex events and dispatch event handlers that process I/O handles shared by the threads. Class diagram Applicability Use Leader-Followers pattern when multiple threads take turns sharing a set of event sources in order to detect, de-multiplex, dispatch and process service requests that occur on the event sources. Real world examples ACE Thread Pool Reactor framework JAWS Real-time CORBA Credits Douglas C.
Lockable Object
Intent The lockable object design pattern ensures that there is only one user using the target object. Compared to the built-in synchronization mechanisms such as using the synchronized keyword, this pattern can lock objects for an undetermined time and is not tied to the duration of the request. Explanation Real-world example The Sword Of Aragorn is a legendary object that only one creature can possess at the time. Every creature in the middle earth wants to possess is, so as long as it’s not locked, every creature will fight for it.
Master-Worker
Also known as Master-slave or Map-reduce Intent Used for centralised parallel processing. Class diagram Applicability This pattern can be used when data can be divided into multiple parts, all of which need to go through the same computation to give a result, which need to be aggregated to get the final result. Explanation In this pattern, parallel processing is performed using a system consisting of a master and some number of workers, where a master divides the work among the workers, gets the result back from them and assimilates all the results to give final result.
Monitor
Intent Monitor pattern is used to create thread-safe objects and prevent conflicts between threads in concurrent applications. Explanation In plain words Monitor pattern is used to enforce single-threaded access to data. Only one thread at a time is allowed to execute code within the monitor object. Wikipedia says In concurrent programming (also known as parallel programming), a monitor is a synchronization construct that allows threads to have both mutual exclusion and the ability to wait (block) for a certain condition to become false.
Producer Consumer
Intent Producer Consumer Design pattern is a classic concurrency pattern which reduces coupling between Producer and Consumer by separating Identification of work with Execution of Work. Explanation Real-world example Consider a manufacturing process of item, the producer will need to pause the production when manufacturing pipeline is full and the consumer will need to pause the consumption of item when the manufacturing pipeline is empty. We can separate the process of production and consumption which work together and pause at separate times.
Promise
Also known as CompletableFuture Intent A Promise represents a proxy for a value not necessarily known when the promise is created. It allows you to associate dependent promises to an asynchronous action’s eventual success value or failure reason. Promises are a way to write async code that still appears as though it is executing in a synchronous way. Explanation The Promise object is used for asynchronous computations. A Promise represents an operation that hasn’t completed yet, but is expected in the future.
Reactor
Intent The Reactor design pattern handles service requests that are delivered concurrently to an application by one or more clients. The application can register specific handlers for processing which are called by reactor on specific events. Dispatching of event handlers is performed by an initiation dispatcher, which manages the registered event handlers. Demultiplexing of service requests is performed by a synchronous event demultiplexer. Class diagram Applicability Use Reactor pattern when
Reader Writer Lock
Intent Regular lock does not distinguish the ‘read lock’ and ‘write lock’, as when access the data structure patterns consists of many threads reading the data, each thread will have to lock it which produces unnecessary serialization. The existence of reader-writer lock resolves this issue as it is well known as “multiple concurrent readers, single writer locks”, used to consist of multiple threads reading the data concurrently and allow only one thread to write or modify the data.
Thread Pool
Intent It is often the case that tasks to be executed are short-lived and the number of tasks is large. Creating a new thread for each task would make the system spend more time creating and destroying the threads than executing the actual tasks. Thread Pool solves this problem by reusing existing threads and eliminating the latency of creating new threads. Explanation Real-world example We have a large number of relatively short tasks at hand.
Thread-local storage
Intent Provide an ability to have a copy of a variable for each thread, making it thread-safe. Explanation During code assembling compiler add .tdata directive, which means that variables below will store in different places from thread to thread. This means changing variable in one thread won’t affect the same variable in other thread. Real world example On constructions each worker has its own shovel. When one of them broke his shovel, other still can continue work due to they have own instrument.
Version Number
Name / classification Version Number. Also known as Entity Versioning, Optimistic Locking. Intent Resolve concurrency conflicts when multiple clients are trying to update same entity simultaneously. Explanation Real world example Alice and Bob are working on the book, which stored in the database. Our heroes are making changes simultaneously, and we need some mechanism to prevent them from overwriting each other. In plain words Version Number pattern grants protection against concurrent updates to same entity.
Acyclic Visitor
Intent Allow new functions to be added to existing class hierarchies without affecting those hierarchies, and without creating the troublesome dependency cycles that are inherent to the GoF Visitor Pattern. Explanation Real world example 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 plain words Acyclic Visitor allows functions to be added to existing class hierarchies without modifying the hierarchies.
Ambassador
Intent Provide a helper service instance on a client and offload common functionality away from a shared resource. Explanation Real world example 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. In plain words
Bytecode
Intent Allows encoding behavior as instructions for a virtual machine. Explanation Real world example 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.
Caching
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. Explanation Real world example 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.
Chain of responsibility
Intent 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. Explanation Real-world example 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.
Circuit Breaker
Intent Handle costly remote service calls in such a way that the failure of a single service/component cannot bring the whole application down, and we can reconnect to the service as soon as possible. Explanation Real world example Imagine a web application that has both local files/images and remote services that are used for fetching data. These remote services may be either healthy and responsive at times, or may become slow and unresponsive at some point of time due to variety of reasons.
Command
Also known as Action, Transaction Intent Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. Explanation Real-world example 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.
Commander
Intent Used to handle all problems that can be encountered when doing distributed transactions. Class diagram Applicability This pattern can be used when we need to make commits into 2 (or more) databases to complete transaction, which cannot be done atomically and can thereby create problems. Explanation Handling distributed transactions can be tricky, but if we choose to not handle it carefully, there could be unwanted consequences. Say, we have an e-commerce website which has a Payment microservice and a Shipping microservice.