Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between Decorator, Wrapper and Adapter patterns?

Tags:

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?

like image 768
Zoltán Tamási Avatar asked Dec 06 '16 13:12

Zoltán Tamási


1 Answers

In theory they are the same, it's the intent that differentiates one pattern from the other:

Decorator:

Allows objects to be composed/add capabilities by wrapping them with a class with the same interface

Adapter:

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.

Wrapper:

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.

like image 168
Kenneth Avatar answered Sep 24 '22 02:09

Kenneth