gpt4 book ai didi

c++ - 类封装 : how to prepare code for adding new classes?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:17:09 25 4
gpt4 key购买 nike

我有以下代码:

class FooType1 : public FooInterface, public BarInterface1 {}
class FooType2 : public FooInterface, public BarInterface2 {}
class FooType3 : public FooInterface, public BarInterface3 {}

FooInterface service1 = boost::shared_ptr<FooType1>(new FooType1());
FooInterface service2 = boost::shared_ptr<FooType2>(new FooType2());
FooInterface service3 = boost::shared_ptr<FooType3>(new FooType3());

new Host(service1, service2, service3);

Host::Host(boost::shared_ptr<BarInterface1> service1,
boost::shared_ptr<BarInterface2> service2,
boost::shared_ptr<BarInterface3> service3) {
obj1 = service1;
obj2 = service2;
obj3 = service3;
}

我需要添加 FooType4FooType5 等,其方式类似于 FooType1FooType3。在 Host 构造函数中,我必须将适当的服务分配给适当的对象(1 到 1、2 到 2 等)。鉴于我知道将添加许多新服务,我该如何正确封装它?

我想到了 vector,因为在一些地方我必须对所有服务执行一些操作,所以“for each”循环会很有帮助。如何以合理的方式从 Host 构造函数的 vector 中获取对象?也许是某种设计模式?

最佳答案

你说,

I need to add FooType4,FooType5, etc. in a way analogoues toFooType1throughFooType3. In theHost` constructor I have to assign the proper service to the proper object (1 to 1, 2 to 2, etc.). Given that I know there will be many new services added, how can I properly encapsulate this?

鉴于此,您的方法不正确。如果您还没有阅读 Open/Closed Prinicple , 我强烈推荐阅读它。

更好的方法可能是允许客户端将服务添加到 Host。这就是我的想法。

class Host
{
public:
void addService(std::shared_ptr<FooInterface> service)
{
services_.push_back(service);
}

private:
std::vector<std::shared_ptr<FooInterface>> service_;
};

并将其用作:

Host* host = new Host(service1, service2, service3);
host->addService(std::shared_ptr<FooInterface>(new FooType1()));
host->addService(std::shared_ptr<FooInterface>(new FooType2()));
host->addService(std::shared_ptr<FooInterface>(new FooType3()));

关于c++ - 类封装 : how to prepare code for adding new classes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31948126/

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