限制对接口的访问的正确方法

A proper way to restrict access to an interface?

本文关键字:方法 访问 接口      更新时间:2023-10-16

假设我有一个表示打印作业的类: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投射指针。

经过一番深思熟虑,我决定:

  1. 这整件事绝对比它的价值更麻烦;

  2. MFH上面答案的(略微修改)版本是唯一的,因此是最好的方法。

感谢大家的投入,这当然很有启发性。