Apply Design Patterns In Java (Part 2)
Nguyen Hai Dang (Eric)
? Software Engineer | Backend | Devops | Database Optimization | AWS Cloud | Azure Cloud | Java | Let's connect?
1. Overview
Previously, we explored the Strategy and Factory Method design patterns (Link), which enhance flexibility and reusability in our code. Now, we focus on the Decorator, Composite, and CoR patterns. These patterns dynamically add functionality to objects, structure complex hierarchies, and pass requests along a chain of handlers, respectively. Each pattern adheres to the Open/Closed Principle, promoting modular and maintainable software architectures. This article delves into their practical applications and benefits, showcasing how they can be used to create robust and scalable systems.
2. Decorator
2.1 Definition
Decorator is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the?behaviors.
2.2 Problem
We define multiple notifier classes (e.g., SMS, Email) and combine them to create composite notifiers.
Drawback of this design:
2.3 Solution
Using the Decorator pattern, we can dynamically add responsibilities to objects.
Benefits of this design:
2.4 Code Example
3. Composite
3.1 Definition
Composite is a structural design pattern that lets you compose objects into tree structures and then work with these structures as if they were individual?objects.
领英推荐
3.2 Problem
Consider a scenario where we have an Item class representing products, and each item can contain other items, forming a nested structure
Drawbacks of this design:
3.3 Solution
Using the Composite pattern, we can separate simple items from composite items, improving flexibility and scalability.
Benefits of this design:
4. CoR Pattern
4.1 Definition
Chain of Responsibility is a behavioral design pattern that lets you pass requests along a chain of handlers. Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the?chain.
4.2 Problem
Consider a scenario where we have a simple web crawler. The WebCrawler class performs multiple steps: checking the URL, fetching content, extracting information, and saving data to a database. The original implementation might look like this
Drawbacks of this design
4.3 Solution
Using the Chain of Responsibility pattern, we can refactor the web crawler to improve flexibility and scalability. Each step in the crawling process will be handled by a separate handler.
Benefits of this design:
??Java Software Engineer | Oracle Certified Professional
8 个月Good to know
Xin bí kíp ch?p màn hình x?n nh? trên v?i anh ?i ^^!