装饰模式与授权模式之间的区别 [英] Difference between Decorator pattern and Delegation pattern

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

问题描述

装饰模式与授权模式有什么区别(如果有的话)?我不想知道实现细节,还要了解使用情况的差异和主观观点如何使用它们。

What is the difference between Decorator pattern and Delegation pattern (if there is any) ? I don't want to know just about implementation details but also about use case differencies and subjective point of view how to use them.


  • < a href =http://en.wikipedia.org/wiki/Decorator_pattern>装饰图案

  • 委托模式

  • Decorator pattern
  • Delegation pattern

编辑:您可以指向使用这些模式(特别是委托,因为装饰在Java IO类中使用)的源代码(在OS项目中)。我正在寻找一些真正的用法,而不仅仅是虚拟的例子。也许这些模式只是在标题上有所不同。随意写这个意见。

EDIT : Can you point to source code (in OS project) where these pattern (especially Delegation, because Decoration is used in Java IO classes) are used. I'm looking for some real usage not just dummy example. Maybe these patterns are the same differs only in title. Feel free to write this opinion.


推荐答案

装饰者使用委托,但是以一种非常具体的方式。

Decorator uses Delegation, but in a very specific way.

委派(或组合)不像通过协调使用其他几个对象来构建复杂行为的一般方式一样多。它通常以一组或静态方式使用。通过set或static我的意思是这样的:

Delegation (or composition) is not as much a pattern as a general way to build complex behavior by coordinating use of several other objects. It's often used in a set or static way. By "set or static" I mean something like this:

class Delegator {
  private final ClassA a = new ClassA();
  private final ClassB b = new ClassB();

  public void doWork() {
     a.setup();
     final ResFromA resa = a.getRes();
     b.setup();
     b.consume(resa);
  }

}

请注意,代理商不共享任何类型或接口与ClassA或ClassB,并且知道a和b的确切类型。

Note that Delegator does not share any type or interface with either ClassA or ClassB, and knows the exact type of both a and b.

装饰器是使用委托来向逻辑实体添加行为的动态方式在运行时。在装饰器中,所有实体共享一个通用接口,并使用委托来连接他们的工作。

Decorator is a dynamic way to use delegation to add behavior to a logical entity at runtime. In Decorator all entities share a common interface, and use delegation to concatenate their work.

public interface Item {
  public void drawAt(final int x, final int y);
}

public class CircleAround implements Item {
  private final Item wrapped;
  private final int radius;

  public CircleAround(public final Item wrapped, public final int radius) {
    this.wrapped = wrapped;
    this.radius = radius;
  }

  public void drawAt(final int x, final int y) {
    // First handle whatever we are wrapping
    wrapped.drawAt(x,y);
    // Then add our circle
    Graphics.drawCircle(x, y, radius);
  }

}

请注意,与第一个例子不同, CircleAround不知道它所包含的项目的确切类型,并与它共享一个公共接口。

Note that unlike the first example, CircleAround does not know the exact type of the item that it wraps, and shares a common interface with it.

这篇关于装饰模式与授权模式之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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