gpt4 book ai didi

c++ - 实现 'semi-virtual' 方法的最佳实践是什么?

转载 作者:行者123 更新时间:2023-11-30 02:31:32 25 4
gpt4 key购买 nike

我知道不存在“半虚拟”方法,但是,我遇到了与设计相关的问题。

假设我有一个名为 WebPage 的基类。此类有一个名为 UpdatePage() 的方法。但是因为此方法存在于抽象 WebPage 对象中,所以 UpdatePage() 方法是虚拟的,应该由从 WebPage 派生具体类的用户实现。

但是假设在调用 UpdatePage() 方法时,理想的做法是为某个类数据成员添加上次更新时间的时间戳。

我现在的处境是,我希望从一个方法中获得一些默认实现(即做一个时间戳),但我也希望该实现是针对从基类 WebPage 派生的具体类自定义的。

我知道我可以想出一些技术来解决这个问题。例如,我可以使 UpdatePage() 成为非虚拟的,并让它包含两个方法:非虚拟的 timeStamp() 方法和纯虚拟的 updateImplementation() 方法。这样,当用户调用 UpdatePage() 时,将存在默认和自定义行为。

但是,如果存在一些设计模式/规则,我不想重新发明轮子。

谢谢!

最佳答案

您在问题中提到的是 Template Method适合解决您的问题的模式。

简而言之,您的UpdatePage() 将提供流程的"template",并让派生类提供模板缺失的部分:

class WebPage {
public:
virtual UpdatePage() { // optional for the virtual
// Update the timestamp

// Call the logic provided by derived class
DoUpdatePage();

// Some other logic afterwards if you need
};

protected:
virtual DoUpdatePage() = 0; // you may also provide a default impl too
};

(希望语法正确,已经有一段时间没有接触C++了。但是思路应该很清楚)


根据您的设计,另一种可能的模式是 Decorator。

简而言之,不是直接使用派生类,而是通过提供时间戳逻辑的装饰器对其进行装饰

例如

class WebPage {
public:
virtual void UpdatePage() = 0;
};

class TimeStampWebPageDecorator : public WebPage {
public:
TimeStampWebPageDecorator(WebPage* webpage) : impl(webpage) {
}

virtual void UpdatePage() {
// logic for the timestamp stuff

impl->UpdatePage();

// some other logic after calling impl
}

private:
WebPage * impl;
}

因此,如果您有一个要调用的 WebPage 实现,您可以使用 TimeStampWebPageDecorator 对其进行装饰。例如

FooWebPage fooWebPage{};

// Instead of invoking fooWebPage directly like this.
// WebPage& webpage = fooWebPage;
// webpage.UpdatePage()

// Decorate it first
WebPage& webpage = TimeStampWebPageDecorator{&fooWebPage};
webpage.UpdatePage()

关于c++ - 实现 'semi-virtual' 方法的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37516026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com