Design Pattern
The design patterns come up to help us with best practices to solve common problems. The patterns can help in the maintenance of the system. However, you should have a code sense to decide when should NOT use them. Clean Code is better than a code that makes you look smart. The excess of patter use just because you wanna do that can cause productivity and maintenance troubles. The SIMPLE can be beautiful.
There are a lot of patterns that you can choose an also you will find many blogs to speak about them. Here, I’d like to put together some of them just with the summary. I believe it can facilitate understanding and help us to decide about the next step. I’ll list the GoF, Java EE and Microservice patterns.
GoF - Gang of Four
Four authors wrote a book with a set of patterns which can be used to reuse code. This work separate three categories of patterns. The Refactoring Guru explain in an intuitive way all these patterns. Some great implementations you can find in tutorialspoint, HowToDoInJava and StackAbuse.
Creational |
---|
Singleton - One instance per JVM Builder - Different types of immutable objects Factory - Centralized creation objects Abstract Factory - Abstraction over a group of factories Prototype: create objects with similar states using clone. |
Structural |
Adapter: map an interface to another interface Bridge: decouple a class into two parts Composite: compose the objects into tree structures to represent whole-part hierarchies Decorator: facilitate to add new features or behaviours Facade: unified interface to a set of interfaces in a subsystem Flyweight: a shared object that can be used in multiple contexts simultaneously Proxy: a proxy object provide a surrogate or placeholder for another object to control access to it |
Behavioural |
Chain of Responsibility: request handled by more than one object Command: abstract the business logic into discrete actions which we call commands Iterator: access the elements of an aggregate object sequentially without exposing its underlying representation Visitor: when we want a hierarchy of objects to modify their behaviour but without modifying their source code. Strategy: choose a specific implementation of algorithm or task in run time Template Method: defines the sequential steps to execute a multi-step algorithm Mediator: an object that encapsulates how a set of objects interact Observer: when one object changes state, all its dependents are notified and updated automatically State: allows an object to alter its behaviour when its internal state changes Memento: restore state of an object to a previous state Interpreter: specifies how to evaluate sentences in a language, programmatically |
Java EE Design Pattern
The coreJ2EE Pattern book describes all pattern that you can find to develop using an enterprise application. Some of them we use in our development project and others are not usual on day-by-day because they are used in some frameworks and we don’t need to be worried about that. You will find great implementations in StackAbuse and tutorialspoint.
Presentation Tier |
---|
Intercepting Filter: pre-processing request. Context Object: used for maintaining state and for sharing/propagate information across the system layers. (i) View Helper separates the static view from the processing of the business model data (i) Dispatcher View initial access point for a request (Front Controller + View Helper + Service To Worker) (i) Front Controller: centralized request handling Application Controller: Centralize the flow of the application and screen navigation (i) Composite View Each subview can be included dynamically and the layout of the page can be managed independently of the content (i) Service To Worker: centralize control and request handling to retrieve a presentation model before turning control over to the view ( Dispatcher component + Front Controller + View Helper Patterns)(i) |
Business Tier |
Data Access Object (DAO): used to separate data accessing in a database from business logic. It can seems confuse with Repository pattern from DDD. You can see a comparison here. Web Service Broker expose and broker one or more services using XML and Web protocols (i) Service Activator facilitates asynchronous processing for EJB components (i) Domain Store separating persistence from object model (i) |
Integration Tier |
Business Delegate: decouple the presentation layer from the business layer Service Locator: locate various services using JNDI lookup. Decouple the Service Consumers and the concrete classes Session Facade Encapsulates business-tier components. It’s responsible for Locating, creating and modifying the business objects Providing a uniform coarse-grained service access (i) Business Object separate business data and logic using an object model. (i) Composite Entity: it represents a graph of objects. When updated all dependent objects are updated. EJB is the main use. Transfer Object: used when you want to send an object with attributes from different sources. T O Assembler: The Transfer Object Assembler aggregates multiple Transfer Objects from various business components and services and returns it to the client. (i) |
Architecture Pattern
Patterns |
---|
Multi-Tiered: Presentation Layer, Business Layer, Database Layer Client-Server: Client makes request to the server. It’s a centralized way to work. It is more security, easier to backup, recover, management and upgrade MVC: this pattern involves all the tiers and because of that also you will find MVC frameworks. It is an acronym to Model-View-Controller where Model represents the data, View represents the visualization of the data and the Controller is who handles the communication between View and Model. It promotes, for example, parallel developments and reuse. Service Oriented Architecture (SOA): The application components provide services to other components via a communications protocol. Principles: Standardized Service Contract, Loose Coupling, Service Abstraction, Service Reusability, Service Autonomy, Service Statelessness, Service Discoverability, Service Composability, Service Interoperability Microservice: Clear defined scope. It improve the modularity and promote the parallel development and scalability. Domain Driven Architecture[1][2]: Its about mapping business domain concepts into software artifacts. Use patterns as Factory, Repository and Service. Event Driven Architecture[3][4]: It was replaced by Saga Pattern and consists to maintain consistency using events. |
Microservice
It is a relatively new subject. I could find some patterns related to this theme but there are some patterns that are usual to find about Microservice, which I classified such Common Patterns. The Microsoft also define some others that I list below.
Common |
---|
Aggregator: a simple web page that invokes multiple services to achieve the functionality required by the application Proxy: used where each individual service need not be exposed to the consumer and should instead go through an interface Chained: produce a single consolidated response to the request. Branch: allows simultaneous response processing from two, likely mutually exclusive, chains of microservices Shared Data: This allows the service to be polyglot, and use the right tool for the right job Asynchronous Messaging: using message queues |
Microsoft |
Ambassador: used to offload common client connectivity tasks Anti-corruption layer: implements a façade between new and legacy applications Backends for Frontends: creates separate backend services for different types of clients Bulkhead: isolates critical resources |
Gateway Aggregation: aggregates requests to multiple individual microservices into a single request Gateway Offloading: enables each microservice to offload shared service functionality Gateway Routing: routes requests to multiple microservices using a single endpoint Sidecar: provide isolation and encapsulation of components Strangler: supports incremental migration |
The post Design Pattern for Microservice gives to us a list of classified patterns. Some of them were cited before.
Decomposition Patterns |
---|
Decompose by Business Capability: applying the single responsibility principle Decompose by Subdomain: use DDD (Domain-Driven Design) to classes which will not be easy to decompose Strangler Pattern: supports incremental migration - it creates two separate applications that live side by side until the refactored application “strangles” or replaces the original application. |
Integration Patterns |
API Gateway Pattern: helps to address many concerns raised by a microservice implementation, not limited to the ones above Aggregator Pattern: aggregate the data from different services and then send the final response to the consumer Client-Side UI Composition Pattern: the UI has to be designed as a skeleton with multiple sections/regions of the screen/page. Each section will make a call to an individual backend microservice to pull the data |
Database Patterns |
Database per Service: it must be private to that service only. It should be accessed by the microservice API only. It cannot be accessed by other services directly Shared Database per Service: In this pattern, one database can be used by 2 or 3 microservice. It is a pattern to be used when you start to break the application into smaller logical pieces. When this migration finish you should use a database per service. Command Query Responsibility Segregation (CQRS): it defines a solution to implement queries to retrieve data from different sources. It suggests splitting the application into command side (Create, Update, Delete) and the query side (materialized views) to handle the requests. Saga Pattern: it is used to ensure data consistency across services which can be implemented centralized or not centralized. |
Observability Patterns |
Log Aggregation: a centralized logging service that aggregates logs from each service instance Performance Metrics: aggregate the metrics of an application service. The metrics can be pushed to a metrics server or the server can pull the metrics from the services. Distributed Tracing: it helps to trace a request end-to-end to troubleshoot the problem Health Check: Each service needs to have an endpoint which can be used to check the health of the application |
Cross-Cutting Concern Patterns |
External Configuration: it avoids code modification for configuration changes Service Discovery Pattern: the idea is to publish the service where the consumers can find services. Circuit Breaker Pattern: it avoids cascading service failures and handles failures gracefully. It is based on invoke service via a proxy (electrical circuit breaker) and timeout. Blue-Green Deployment Pattern: implemented to reduce or remove downtime by running two identical production environments, Blue and Green, which one of them is the new version that will replace the other one. |