The following fake example is a class that facilitates a polling process, stores the results, and saves it to a DB. My understanding is that this would be considered a Mediator pattern as it is facilitating the communication between objects that would otherwise be coupled without it. Is this accurate or would there be another pattern that explains this behavior better? Thank you!
public class StatusPoller
{
public void Poll()
{
foreach(User user in users)
{
string accessToken = oAuthClient.Authenticate(user); // Authenticate
List<status> statuses = pollingClient.PollStatus(accessToken); // Poll for status
Store(statuses); // Store statuses in DB
}
Message.Dispatch(5) // Dispatch a new message on a delay
}
}
CodePudding user response:
Kindof,
the problem that the Mediator pattern comes to solve is
We want to design reusable components, but dependencies between the potentially reusable pieces demonstrates the "spaghetti code" phenomenon (trying to scoop a single serving results in an "all or nothing clump").
so when StatusPoller
is injecting and handling all its dependencies such as
oAuthClient
pollingClient
and dbContext
(that is probably in the Store
method)
we are reducing the complexity of communicating between all these objects.
The mediator pattern is used to reduce communication complexity between multiple objects or classes. This pattern provides a mediator class which normally handles all the communications between different classes and supports easy maintenance of the code by loose coupling.
so basically your StatusPoller
is acting as a concrete Mediator
CodePudding user response:
This isn't any particular design pattern, which is perfectly fine. It's just a method. Not every method needs to be or should be a design pattern. More specifically, converting, A --> B
into, A --> C --> B
is not a Mediator. If it was, then the service layer of every web application would be a Mediator between the controllers and the DAOs. A Mediator converts a spiderweb like this,
A —→ C
↘ ↙↗ ↖↘
D ←—→ E
↖ B ↗
into a design like this,
A B C
↘ ↓ ↙↗
M e d i a t o r
↙↗ ↑↓
D E
where none of the objects talk to each other directly and all of the (two-way) communication happens through the Mediator.
This is actually a dangerous pattern to apply because, as you might guess from the picture, it's very easy for the Mediator to become a god object. Discipline is necessary to prevent business logic from creeping into the Mediator and restrict its responsibility solely to message passing.