简体   繁体   English

在代理模式中使用 inheritance 过度组合

[英]Using inheritance over composition in a proxy-pattern

I'm just curious why all examples of proxy-pattern written in Python are using composition over inheritance?我只是好奇为什么所有用 Python 编写的代理模式示例都使用 inheritance 上的组合? If proxy class should implement all of the methods of original class, isn't it easier to inherit proxy from original and just overwrite methods we want to perform additional logic (caching, logging, etc.), using super().method() ?如果代理 class 应该实现原始 class 的所有方法,使用super().method()从原始继承代理并覆盖我们想要执行附加逻辑(缓存、日志记录等)的方法不是更容易吗?

The relationship between classes is also respected: the proxy class is some kind of an original class.类之间的关系也受到尊重:代理 class 是某种原始 class。

Example:例子:

class Original:
    def some_method(self):
        return "some"

    def another_method(self):
        return "another"

class Proxy(Original):
    def another_method(self):
        res = super().another_method()
        logger.log(res)

        return res

Lets take a look at one of the "classical" diagrams for proxy pattern (from wiki ):让我们看一下代理模式的“经典”图表之一(来自wiki ):

在此处输入图像描述

I would argue that "If proxy class should implement all of the methods of original class" statement is not true - the proxy class should implement all of the "contract" methods ( Subject interface) and it hides the implementation detail ie RealSubject from the user (also RealSubject potentially can have some other public methods not defined by the interface).我认为“如果代理 class 应该实现原始类的所有方法”声明不正确 - 代理 class 应该实现所有“合同”方法( Subject接口)并且它隐藏了实现细节,即对用户的RealSubjectRealSubject也可能具有接口未定义的其他一些公共方法)。

One more thing to consider - composition can give the proxy ability to control the lifetime of the proxied class instance, while with inheritance (if we skip the fact that there is no more "proxying" happening) it is not possible for the "proxy" itself.要考虑的另一件事-组合可以使代理能够控制代理 class 实例的生命周期,而使用 inheritance (如果我们跳过没有更多“代理”发生的事实)“代理”是不可能的本身。

Also note that there are benefits (and drawbacks) in choosing composition over inheritance in general.另请注意,与inheritance 相比,选择组合通常有好处(和缺点)。

Some more useful reading:一些更有用的阅读:

  1. Prefer composition over inheritance?比 inheritance 更喜欢组合? SO answer所以回答
  2. Differences between Proxy and Decorator Pattern代理模式和装饰器模式的区别

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM