gpt4 book ai didi

c++ - 限制访问接口(interface)的正确方法?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:49:01 24 4
gpt4 key购买 nike

假设我有一个代表打印作业的类:CPrintingJob。它对正在打印的文档一无所知,只知道作业状态 - 作业是否排队、拒绝、继续等。

想法是在需要完成某些打印时实例化此类的对象,然后将其与其他数据一起传递给打印模块,然后作业的创建者检查其状态以查看打印的进行情况。

假设CPrintingJob继承了两个接口(interface):

class IPrintingJob // this one is to check the job state
{
virtual TState GetState() const = 0;
// ... some other state-inquiring methods

class ICallback // job's owner is notified of state changes via this one
{
virtual void OnStateChange( const IPrintingJob& Job ) = 0;
};
};

class IPrintingJobControl // this one is for printing module to update the state
{
virtual void SetState( const TState& NewState ) = 0;
// ... some other state-changing methods
};

问题是,创建 CPrintingJob 对象的类不应该访问 IPrintingJobControl,但是打印模块 CPrintingJob 正在传递给必须能够更改其状态,因此可以访问该接口(interface)。

我想这正是应该使用 friend 的情况,但我一直避免使用 friend ,因为他们是一种天生有缺陷的机制,因此不知道如何正确使用他们。

那么,我如何正确地做到这一点?

最佳答案

使用工厂并让工厂返回 IPrintingJob 的实例(最好包装在 smart_ptr 中)。例如:

 struct PrintingFactory {
static auto create() -> std::unique_ptr<IPrintingJob> {
return std::unique_ptr<IPrintingJob>(new CPrintingJob());//as there is currently no std::make_unique..
}
}

一旦您必须使用 JobControl,您可以简单地通过 std::dynamic_pointer_cast 转换指针。

关于c++ - 限制访问接口(interface)的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13680867/

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