About
The maxon::Factory template is used to create factory functions for a given interface. Such factory functions allow to safely create new, initialized instances of that interface.
Declaration
Based on the maxon::Factory template, a factory is typically declared as a published object using MAXON_DECLARATION.
using StringHashFactoryType = maxon::Factory<StringHashRef(
maxon::String)>;
MAXON_DECLARATION(StringHashFactoryType, StringHashFromStringFactory,
"net.maxonexample.factory.stringhashfromstring");
Implementation
The published object containing the new factory must be defined in a source code file using MAXON_DECLARATION_REGISTER. The behaviour of the factory depends on a referenced function that is invoked by the factory:
- maxon::Factory::CreateFactory(): References a static function for creation of the desired object.
- maxon::Factory::CreateObjectFactory(): References a member function of a specific implementation. This function will create an instance and will call that member function.
Examples
This example shows a simple interface that just provides read-only access to its data.
The implementation can look like this:
class SecretStringHashImplementation :
public maxon::Component<SecretStringHashImplementation, StringHashInterface>
{
public:
{
}
{
if (_hash.IsPopulated())
if (hash.GetLength() != 64)
_hash = hash;
}
{
return InitFromHash(hash);
}
{
}
private:
};
Since it should not be possible to change the internal data of an existing instance, the internal data must be set when the object is created. Within a header file a factory can be defined as a published object.
using StringHashFactoryType = maxon::Factory<StringHashRef(
maxon::String)>;
MAXON_DECLARATION(StringHashFactoryType, StringHashFromStringFactory,
"net.maxonexample.factory.stringhashfromstring");
A factory can call a static function that in return will create a new instance with the given arguments:
{
StringHashRef res = SecretStringHashImplementation::GetClass().Create()
iferr_return;
return res;
}
{
return StringHashFactoryType::CreateFactory(&MakeSecretStringFromHash);
}
A different factory can invoke a member function of the implementation class. Then it will create an instance of that specific implementation automatically:
{
return StringHashFactoryType::CreateObjectFactory(&SecretStringHashImplementation::FactoryInit);
}
The factory is then used as any other published object:
const StringHashRef stringHash = StringHashFromStringFactory().Create(secretText)
iferr_return;
if (equal)
Further Reading