本文介绍了设计模式,将数据添加到类(第三方)而不修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我不得不扩展类的行为而不修改它时,我经常使用设计模式。

When I have to extend the behaviour of a class without modifying it, I often use the design pattern visitor. It adds member-like functions without modifying the core of the class it works with.

以相同的方式或多或少地增加了类成员函数,而无需修改其核心。我需要扩展第三方类,但是

More or less in the same way, I need to extend a third party class, but mostly with data, not behaviour.

在这种情况下,我经常使用与键 MyClass * 的值为 MyClassExtender 。 MyClassExtender包含所有附加信息。

In such cases, I often use a std::map matching the a key MyClass* with a value MyClassExtender. MyClassExtender contains all the additionnal information.

这样做的时候,我碰巧想知道是否还有其他方法可以这样做,也许更常见或更最佳实践。 Extender?
是否有这种模式的名称...

While doing that, I happened to wonder if there are other ways of doing that, maybe more common or more 'best-practice". Should I call this additive class an Extender ?Is there a name for such a pattern...

Nota Bene:我可以简单地将MyClass *和MyClassExtender聚合在一起,但是我确实经常需要访问给定MyClass *的MyClassExtender,所以st :: map确实很方便。

Nota Bene: I could have simply aggregated the MyClass* and MyClassExtender in a new class, but I need to access MyClassExtender given a MyClass* really often, so the st::map is really convinient.

推荐答案

为什么不要继承是扩展类的一种方式,无论是行为还是状态。除非您只想将类的实例与其他数据相关联(在这种情况下,它根本不会扩展)和std ::地图是正确的答案。

Why don't you just subclass the class? Inheritance is the way to extend classes, whether with behavior or state. Unless you just want to associate instances of the class with other data, in which case it's not extending at all, and a std::map is the right answer.

这篇关于设计模式,将数据添加到类(第三方)而不修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 21:41