标签:delegate void nat register 例子 rri boost 复用 err
组件的复用
组合
组合是一个组件复用的一种常用方式。一个外部的组件通过内部组件的复用来接入其接口。定义一个接口INameable,如下:
// i-nameable.h
#include "config.h"
#include <string>
class INameable :
virtual public IObject
{
public:
virtual ~INameable(void) BOOST_NOEXCEPT {}
virtual void SetName(const std::string& name) = 0;
virtual std::string GetName(void) = 0;
};
NSFX_DEFINE_CLASS_UID(INameable, "edu.uestc.nsfx.tutorial.INameable");
然后我们写一个提供该接口的组件Nameable。
// nameable.h
#include "config.h"
#include "i-nameable.h"
class Nameable :
public INameable
{
public:
Nameable(void);
virtual ~Nameable(void);
// INameable
virtual void SetName(const std::string& name) NSFX_OVERRIDE;
virtual std::string GetName(void) NSFX_OVERRIDE;
public:
// A public function.
// However, this function is not exposed by an interface.
void SetDefault(void);
private:
NSFX_INTERFACE_MAP_BEGIN(Nameable)
NSFX_INTERFACE_ENTRY(INameable)
NSFX_INTERFACE_MAP_END()
private:
std::string name_;
};
NSFX_REGISTER_CLASS(Nameable, "edu.uestc.nsfx.tutorial.Nameable");
下面的例子对Nameable进行了应用。
// nameable.cpp
#include "config.h"
#include "nameable.h"
Nameable::Nameable(void)
{
}
Nameable::~Nameable(void)
{
}
void Nameable::SetName(const std::string& name)
{
name_ = name;
}
std::string Nameable::GetName(void)
{
return name_;
}
void Nameable::SetDefault(void)
{
name_ = "A default name";
}
假设另外一个组件想要提供INameable。可以制造出Nameable来持有这个名字(这里有待修正)。例如:
// combination.h
#include "config.h"
#include "nameable/i-nameable.h"
class Combination :
public INameable
{
public:
Combination(void);
virtual ~Combination(void);
// INameable
virtual void SetName(const std::string& name) NSFX_OVERRIDE;
virtual std::string GetName(void) NSFX_OVERRIDE;
private:
NSFX_INTERFACE_MAP_BEGIN(Combination)
NSFX_INTERFACE_ENTRY(INameable)
NSFX_INTERFACE_MAP_END()
private:
// The INameable interface of the inner component is stored.
Ptr<INameable> nameable_;
};
NSFX_REGISTER_CLASS(Combination, "edu.uestc.nsfx.tutorial.Combination");
在Combination的构造器里,一个具有CID为"edu.uestc.nsfx.tutorial.Nameable"的组件被创造出来,而它的接口IN
ameable被存在nameable_中。例如:
// combination.cpp
#include "config.h"
#include "combination.h"
Combination::Combination(void) :
// Black-box reuse.
// The underlying type of "edu.uestc.nsfx.Nameable" is unknown, and
// the component is accessed via its interfaces.
nameable_(CreateObject<INameable>("edu.uestc.nsfx.tutorial.Nameable"))
{
}
为了使用INameale接口,Combination可以将调用委托给内部组件。例如:
void Combination::SetName(const std::string& name)
{
// Delegate to the inner component.
nameable_->SetName(name);
}
std::string Combination::GetName(void)
{
// Delegate to the inner component.
return nameable_->GetName();
}
标签:delegate void nat register 例子 rri boost 复用 err
原文地址:https://www.cnblogs.com/lx61/p/12188807.html