问题
I have 2 projects: A and B that should interactwith each other.
Project A introduce interface names ISpecialTask and Project B should implement it.
Projet B has an entity named TaskWithListOfProperties that cannot implement ISpecialTask because it has different structure of properties (in addition, all the system knows how to work with TaskWithListOfProperties and I don't want to change its structure).
So I decided to create a class named SpecialTaskFromListOfProperties that implements ISpecialTask and uses TaskWithListOfProperties instance in order to use it for the interaction between the 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 SpecialTaskFromListOfProperties actually the Adapter pattern?
What is the difference between the adapter pattern and decorator pattern?
回答1:
Depends on what you're actually trying to achieve. Adapter and Decorator are pretty much similar, however when you implement an Adapter you bring no new logic besides conversion. When implementing a Decorator you actually bring in some brand new functionality that never existed before in the object you're decorating.
So, long story short, if interface properties Id
, WorkerId
etc are naturally coming from TaskWithListOfProperties
- then you should consider it as an Adapter. Otherwise it's a Decorator.
回答2:
From the original GoF book, the intent of the Adapter pattern [Black Wasp] [Wikipedia] is to...
convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
While the intent of the Decorator pattern [Black Wasp] [Wikipedia] is to...
attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending funtionality.
Though the patterns are similar, from the definition it's clear that this is the adapter pattern. You've got a square peg (TaskFromListOfProperties
) that needs to fit into a round hole (ISpecialTask
), so you've adapted it using SpecialTaskFromListOfProperties
.
A decorator would augment/extend the existing functionality of TaskFromListOfProperties
, i.e. it wouldn't change its existing interface. That's not what SpecialTaskFromListOfProperties
is doing.
来源:https://stackoverflow.com/questions/6999834/is-this-called-adapter-adapter-vs-decorator