Apply Design Patterns In Java (Part 3)

Apply Design Patterns In Java (Part 3)

1. Overview

Continuing from my previous article, we delve into three key design patterns: Facade, Mediator, and Observer. The Facade Pattern simplifies complex systems with a unified interface, making them easier for clients to use. The Mediator Pattern manages interactions between objects, promoting loose coupling and modularity. The Observer Pattern allows objects to respond to changes dynamically, fostering a responsive architecture. Understanding and applying these patterns enhances the maintainability, scalability, and flexibility of software projects, providing structured solutions to common design challenges.

2. Facade

2.1 Definition

Facade is a structural design pattern that provides a simplified interface to a library, a framework, or any other complex set of?classes.

2.2 Problem

Consider a scenario with multiple classes managing products and accounts in an inventory system. The existing implementation involves multiple steps and classes, leading to potential confusion and errors when performing tasks like purchasing products or managing account balances.

Issues

  • Tight Coupling: The code tightly couples the Inventory and AccountStorage operations, requiring developers to manually manage the product and account lookups and withdrawals.
  • Complexity: The buying process involves multiple steps that must be coordinated correctly, increasing the chance of errors.
  • Scalability: Adding new steps to the buying process or changing existing logic requires modifying multiple parts of the code.

2.3 Solution

Using the Facade Pattern, we create a FacadeService class that provides simplified methods for common operations such as purchasing products, depositing money, and fetching account balances. This approach encapsulates the complex interactions within a single class, improving usability and reducing the potential for errors.

Benefits of the Facade Pattern:

  • Simplified Interface: The Facade provides a clean and simple interface for clients to interact with complex subsystems.
  • Improved Maintainability: Changes to the underlying system can be made without affecting the client code.
  • Enhanced Usability: The pattern reduces the learning curve for new developers by abstracting the complexities of the system.

Incorporating the Facade Pattern into your design can lead to more maintainable and user-friendly applications, particularly when dealing with complex systems that require coordinated operations across multiple classes.

3. Mediator

3.1 Definition

Mediator is a behavioral design pattern that lets you reduce chaotic dependencies between objects. The pattern restricts direct communications between the objects and forces them to collaborate only via a mediator?object.

3.2 Problem

Consider a chat room application where multiple users can send messages to each other. In this setup, every user must maintain direct references to other users to send and receive messages. This creates a tightly coupled system, where users are heavily dependent on each other for communication. As the number of users grows, the complexity of maintaining these references increases, making the system harder to scale and manage.

Issues

  • Tight Coupling: Each User has to manage its own list of contacts, making it tightly coupled with other users.
  • Scalability: Adding new users or changing communication logic requires modifications to each user.

3.3 Solution

We will introduce a ChatRoomMediator to manage communication between users. This decouples the users from each other, allowing them to communicate through the mediator.

Explanation

  • ChatMediator Interface: Defines the contract for the mediator (showMessage) which is responsible for communication between users.
  • ChatRoom Class: Implements the ChatMediator interface. It maintains a list of users and facilitates communication by implementing the showMessage method. The chat room handles message broadcasting to all users except the sender.
  • User Class: Represents a user in the chat room. Each user knows the ChatMediator and uses it to send messages. Users don't need to know other users directly, reducing coupling.

Benefits of the Mediator Pattern

  • Loose Coupling: The Mediator pattern reduces dependencies between components, making the system more flexible and maintainable.
  • Scalability: Adding or removing users becomes easier, as changes do not affect the users directly.
  • Centralized Control: The mediator centralizes control over the communication logic, simplifying the management of interactions between components.

The Mediator pattern is ideal for scenarios where multiple objects interact in complex ways, and you want to simplify their communication.

4. Observer

4.1 Definition

Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re?observing.

4.2 Problem

Suppose we have a WeatherStation class that tracks the temperature. We want multiple display elements (like a phone app, a web page, and a desktop widget) to update automatically whenever the temperature changes.

4.3 Solution

We will implement the Observer pattern to allow multiple display elements to register with the WeatherStation and be notified whenever the temperature changes.

Explanation

  • Subject Interface: Defines the methods for registering, removing, and notifying observers.
  • Observer Interface: Defines the update() method that observers must implement.
  • WeatherStation Class: Implements the Subject interface. It keeps a list of observers and notifies them when the temperature changes.
  • DisplayElement Class: Implements the Observer interface. It receives updates from the WeatherStation and prints the temperature change.

Benefits of the Observer pattern

  • Decoupling: The WeatherStation can notify any number of display elements without knowing their details.
  • Flexibility: New display elements (such as a tablet display or a smart speaker display) can be added easily.
  • Dynamic Updates: Display elements are updated automatically whenever the temperature changes, ensuring they always show the latest data.

Stanislav Sorokin

Founder @Bles Software | Driving Success as Top Seller AI Solutions | 152+ Projects Delivered | 120+ Five-Star Ratings on Fiverr

5 个月

Awesome breakdown, have you considered combining the Mediator Pattern with event-driven systems? It's like magic for decoupling complex interactions!

回复
D??ng Xuan ?à

??Java Software Engineer | Oracle Certified Professional

7 个月

Nice!!

回复

要查看或添加评论,请登录

Nguyen Hai Dang (Eric)的更多文章

社区洞察

其他会员也浏览了