限制对接口的访问的正确方法
A proper way to restrict access to an interface?
假设我有一个表示打印作业的类:CPrintingJob
.它不知道正在打印的文档,只知道作业状态 - 作业是否排队、拒绝、继续等。
这个想法是,每当需要完成某些打印时,都会实例化此类的对象,然后与其他数据一起传递给打印模块,然后作业的创建者检查其状态以查看打印的进展情况。
假设CPrintingJob
继承了两个接口:
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
传递到的打印模块必须能够更改其状态,因此可以访问该接口。
我想这正是应该使用朋友的情况,但我一直避免使用它们,因为它们是一个固有的有缺陷的机制,因此不知道如何正确使用它们。
那么,我该如何正确地做到这一点呢?
使用工厂并让工厂返回 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::d ynamic_pointer_cast投射指针。
经过一番深思熟虑,我决定:
-
这整件事绝对比它的价值更麻烦;
-
MFH上面答案的(略微修改)版本是唯一的,因此是最好的方法。
感谢大家的投入,这当然很有启发性。
相关文章:
- 通过方法访问结构
- 模板方法访问正向声明的类仅在没有此指针的情况下无法编译
- 类变量无法从类方法访问
- 为什么从静态方法访问非静态方法是糟糕的设计
- 子类是否也在 c++ 中继承私有数据成员?但通过超类的公共方法访问
- 如何从回调方法访问自定义类成员
- 使初始化变量可供多个属性初始化方法访问
- 从c++中的方法访问指向对象的专用指针数组
- C++如何通过回调方法访问成员变量
- "undefined reference"从静态方法访问的模板类的静态成员
- 如何从方法访问类成员
- 类静态方法访问其静态数据成员
- 从静态方法访问非静态成员的工作示例
- 类方法访问其数据成员
- 通过公共方法访问私有成员变量
- 为什么无法从模板方法访问此类自己的受保护成员?
- 通过非静态方法访问静态成员
- JNI保留对对象的全局引用,并使用其他JNI方法访问它.在多个JNI调用中保持C++对象的活动状态
- 如何让一个方法访问其他模板类实例的私有成员
- 方法访问C++中的对象实例化