Microsoft 信息保护 SDK - 策略 SDK 观察程序
策略 SDK 包含一个观察程序类。 观察者成员是虚拟的,应将其重写以处理对异步操作的回调。
当异步操作完成时,将会调用与结果对应的 OnXxx()
成员函数。 例如,对于 mip::Profile::Observer
为 OnLoadSuccess()
、OnLoadFailure()
和 OnAddEngineSuccess()
。
下面的示例演示了 SDK 示例也同样使用的承诺/未来模式,并且可以进行扩展以实现所需的回调行为。
配置文件观察者实现
在下面的示例中,我们创建了一个类 ProfileObserver
,它派生自 mip::Profile::Observer
。 成员函数已被重写,以便在整个示例中使用未来/承诺模式。
注意:以下示例仅部分实现,不包括对 mip::ProfileEngine
相关观察者的替代。
profile_observer.h
在标头中,我们定义了派生自 mip::Profile::Observer
的 ProfileObserver
,然后重写了每个成员函数。
class ProfileObserver final : public mip::Profile::Observer {
public:
ProfileObserver() { }
void OnLoadSuccess(const std::shared_ptr<mip::Profile>& profile, const std::shared_ptr<void>& context) override;
void OnLoadFailure(const std::exception_ptr& error, const std::shared_ptr<void>& context) override;
//TODO: Implement remaining members
};
profile_observer.cpp
在实现本身中,我们为每个观察者成员函数定义了一个要执行的操作。
每个成员可接受两个参数。 第一个是指向函数所处理类的共享指针。 ProfileObserver::OnLoadSuccess
预计会收到 mip::Profile
。 ProfileObserver::OnAddEngineSuccess
预计会收到 mip::ProfileEngine
。
第二个是指向“上下文”的共享指针。 在我们的实现中,上下文是对 std::promise
的引用,传递为 shared_ptr<void>
。 函数的第一行将此强制转换为 std::promise
,然后存储在一个名为 promise
的对象中。
最后,通过设置 promise->set_value()
并传入 mip::Profile
对象来准备未来。
#include "profile_observer.h"
#include <future>
//Called when Profile is successfully loaded
void ProfileObserver::OnLoadSuccess(const std::shared_ptr<mip::Profile>& profile, const std::shared_ptr<void>& context) {
//cast context to promise
auto promise = std::static_pointer_cast<std::promise<std::shared_ptr<mip::Profile>>>(context);
//set promise value to profile
promise->set_value(profile);
}
//Called when Profile fails to load
void ProfileObserver::OnLoadFailure(const std::exception_ptr& error, const std::shared_ptr<void>& context) {
auto promise = std::static_pointer_cast<std::promise<std::shared_ptr<mip::Profile>>>(context);
promise->set_exception(error);
}
//TODO: Implement remaining observer members
执行任何异步操作时,观察者实现将会传递给设置构造函数或异步函数本身。