以下问题解决了我经常遇到的问题。基本上,有适配器模式等解决方案,但我发现它有点不满意。
假设我有一个类Polygon
,它实现了一个具有相当多功能的-uhm-polygon。其中许多Polygon
生活在我的程序中,有些是孤立的变量,有些是收集结构。
现在,有一个函数需要一个基本上是Polygon的参数类型,但有一些额外的功能。让我们说一个Polygon
可以返回一些指标:他的音量,重心和角质量。此外,该功能还需要原始Polygon
的方法。
第一个想法是:
class Polygon:
# defines my polygon
class PolygonWithMetrics(Polygon):
# - extends polygon with the metrics
# - takes Polygon as argument upon construction
# - would need to delegate many functions to Polygon
def functionUsingPolygonWithMetrics(p):
# use functions of Polygon and PolygonWithMetrics
# driving code:
p = Polygon(some args here)
... more code ...
p_with_metrics = PolygonWithMetrics(p) # Bummer - problem here...
functionUsingPolygonWithMetrics(p_with_metrics)
问题:需要将PolygonWithMetrics
中的许多功能委托给原始Polygon
。
第二个想法是:
class Polygon:
# defines my polygon
class PolygonMetrics:
# takes a polygon and provides metrics methods on it
def functionUsingPolygonWithMetrics(p):
# use functions of Polygon and PolygonMetrics
# driving code:
p = Polygon(some args here)
... more code ...
p_with_metrics = PolygonMetrics(p)
functionUsingPolygonWithMetrics(p, p_with_metrics) # Bummer - problem here...
这个想法将原始Polygon
作为参数,再加上提供度量函数的第二个对象。问题是我需要更改functionUsingPolygonWithMetrics
的签名。
我真正需要的是如何使用更多功能扩展现有对象ad-hoc,而不会出现想法1和2中给出的问题。
我可以想象一个大致相同的想法,其中的工作主要由PolygonWithMetrics
完成:
class Polygon:
# defines my polygon
class PolygonWithMetrics(maybe inherits something):
# - takes a Polygon and provides metrics methods on it
# - upon construction, it will take a polygon
# - will expose the full functionality of Polygon automatically
def functionUsingPolygonWithMetrics(p):
# use functions of Polygon and PolygonWithMetrics
# driving code:
p = Polygon(some args here)
... more code ...
p_with_metrics = PolygonWithMetrics(p)
functionUsingPolygonWithMetrics(p)
出现了三个问题: