装饰器,包装器和适配器模式之间有什么区别? [英] What are the differences between Decorator, Wrapper and Adapter patterns?

查看:420
本文介绍了装饰器,包装器和适配器模式之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我已经使用这些模式系列很多次了,但是,对我来说,很难看到它们的区别,因为它们的定义非常相似。基本上,似乎所有这些对象都是关于包装一个或多个其他对象以扩展或包裹其行为的方法。

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.

对于这种快速示例,似乎是在存储库模式上实现缓存机制。这是我可能会从下面开始的快速示例 C#代码。

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

您指定的示例我将归类为装饰器:CacheRepository decorates 一个 IRepository 来添加缓存功能。

The example you specify I would categorize as a decorator: The CacheRepository decorates an IRepository to add caching capabilities.

这篇关于装饰器,包装器和适配器模式之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆