I feel like I've been using these pattern families quite many times, however, for me it's hard to see the differences as their definitions are quite similar. Basicaly it seems like all of them is about wrapping another object or objects to extend or wrap their behavior with extra stuff.
For a quick example implementing a caching mechanism over a repository pattern seems to be this situation. Here is a quick sample C#
code I would probably start with.
public interface IRepository { IEnumerable<T> GetItems<T>(); } public class EntityFrameworkRepository : IRepository { ... } public class CachedRepository : IRepository { private IRepository _repository; private ICacheProvider _cache; public CachedRepository(IRepository repository, ICacheProvider cache) { this._repository = repository; this._cache = cache; } public IEnumerable<T> GetItems<T>() { ... } }
Which one of these patterns apply to this situation for example? Could anyone clarify briefly the differences in theory and in practice?
In theory they are the same, it's the intent
that differentiates one pattern from the other:
Allows objects to be composed/add capabilities by wrapping them with a class with the same interface
Allows you to wrap an object without a known interface implementation so it adheres to an interface. The point is to "translate" one interface into another.
Never heard of this as a design pattern, but I suppose it's just a common name for the above
The example you specify I would categorize as a decorator: The CacheRepository decorates
an IRepository
to add caching capabilities.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With