Is this called an adapter? + adapter against decorator

I have 2 projects: A and B, which should interact with each other.

  • Project A introduces interface names. ISpecialTask โ€‹โ€‹and Project B should implement it.

  • Projet B has an object called TaskWithListOfProperties that ISpecialTask โ€‹โ€‹cannot implement because it has a different property structure (in addition, the whole system knows how to work with TaskWithListOfProperties, and I do not want to change its structure).

So, I decided to create a class called SpecialTaskFromListOfProperties that implements ISpecialTask โ€‹โ€‹and uses an instance of TaskWithListOfProperties to use it to interact between projects.

interface ISpecialTask { long Id{get;} long WorkerId{get;} long VehicleId{get;} long CustomerId{get;} } class TaskWithListOfProperties { IDictionary<string, long> Properties {get; } class SpecialTaskFromListOfProperties : ISpecialTask { public SpecialTaskFromListOfProperties(TaskWithListOfProperties ins) { ... ... } public long Id { get{ ... } } public long WorkerId { get{ ... } } public long VehicleId { get{ ... } } public long CustomerId { get{ ... } } } 

Is SpecTaskFromListOfProperties an adapter template?
What is the difference between an adapter template and a decorator pattern?

+4
source share
2 answers

Depends on what you are actually trying to achieve. The Adapter and Decorator are very similar in many respects, however, when implementing the Adapter, you have no new logic, except for conversion. When implementing Decorator, you actually add some completely new functionality that never existed previously in the object you are decorating.

So, in short, if the properties are Id , WorkerId etc. Naturally come from TaskWithListOfProperties - then you should consider this as an adapter . Otherwise, it is a decorator .

+8
source

From the original GoF book , the purpose of the [Black Wasp] [Wikipedia] adapter template is ...

converts a class interface to another client interface. The adapter allows classes to work together, which otherwise could not be associated with incompatible interfaces.

While the intent of the Decorator [Black Wasp] [Wikipedia] template is ...

Adds additional responsibilities to the object dynamically. Decorators provide a flexible alternative to a subclass to extend functionality.

Although the templates are similar, it is clear from the definition that this is an adapter template. You have a square snap ( TaskFromListOfProperties ) that needs to be inserted into the round hole ( ISpecialTask ), so you adapted it with SpecialTaskFromListOfProperties .

The decorator will increase / extend the existing functionality of TaskFromListOfProperties , that is, it does not change the existing interface. This is not what SpecialTaskFromListOfProperties does.

+11
source

All Articles