Implementing C++ -to-lua observer pattern? - c++

I have an observer (or "listener") pattern implemented in my code as such:
struct EntityListener
{
public:
virtual void entityModified(Entity& e) = 0;
};
class Entity
{
public:
Entity();
void setListener(EntityListener* listener);
private:
EntityListener* m_listener;
};
Now, this works in C++; the Entity class calls the entityModified() method whenever it needs. Now, I'd like to transfer some of the functionality to Lua, and among those function points is this listener callback. The entities are now created from the Lua scripts. The question is, how do I achieve the listener functionality in Lua?
For example, the Lua script currently does something like this:
function initializeEntity()
-- The entity object is actually created in C++ by the helper
Entity = Helper.createEntity()
-- Here I'd like to hook a Lua function as the Entity's listener
end

One possible solution is to have a LuaListener class in your C++ code that contains a "pointer" to the Lua function, and a Lua-specific setListener function that is called from the Lua script that takes a Lua function as argument, and creates a LuaListener instance and passes that to the actual C++ setListener.
So the Lua code would look something like
function onModified(entity)
-- ...
end
function initializeEntity()
entity = Helper.createEntity()
entity.setListener(onModified)
end
And the C++ code would look something like (pseudoish-code only):
class LuaListener : public EntityListener
{
private:
lua_State* state;
std::string funcName;
public:
void entityModified(Entity& e)
{
// Call function `funcName` in `state`, passing `e` as argument
}
};
class LuaEntity : public Entity
{
public:
void setListenerLua(state, funcName, ...)
{
Entity::setListener(new LuaListener(state, funcName, ...));
}
};

Related

C++ how to have seperate versions of the same method?

I'm sorry if I don't know the right word for what I'm trying to accomplish.
Basically I have an event handler object which only has a single member. The member is a Stage object.
When the event handler receives an event, I want it to simply use the stage object to call the relevant method. For example:
Event event; //this event is not part of my code, but rather the library I'm using.
Stage s; // my custom class object
EventHandler event_handler; //also my custom class object
event_handler.stage = &s;
if(event == SHUTDOWN) {
event_handler.stage->handle_shutdown();
}
So what I'm trying to accomplish is that, there will be seperate scopes that my program goes into over time, and I want each scope to have access to the event_handler such that they can do something like:
void some_other_scope(EventHandler* eh) {
Stage* some_new_stage = new Stage(...);
eh->stage = some_new_stage;
}
This way, the original event code stays the same, and the event handler will be calling handle_shutdown on a different object than it was originally going to.
So what I want to do is to overload the handle_shutdown method so that there can be different implementations of it. I know how basic overloading works, it can be done by specifying different parameters, but is there any way to have different definitions of the same class method based on the file that the object was created in?
I was hoping to have several files, each with their own some_other_scope() function, and each file can redefine the handle_shutdown method to do different things based on what that file needs.
I'm sure there's a way to do what I want, I just don't know the right words to use.
It seems you want to use polymorphism:
class IStage
{
public:
virtual ~IStage() = default;
virtual void handle_shutdown() = 0;
// ...
};
class Stage1 : public IStage
{
public:
void handle_shutdown() override { /*Implementation1*/ }
// ...
};
class Stage2 : public IStage
{
public:
void handle_shutdown() override { /*Implementation1*/ }
// ...
};
And then
struct EventHandler
{
std::unique_ptr<IStage> stage;
// ...
};
EventHandler event_handler;
event_handler.stage = std::make_unique<Stage1>();
if (event == SHUTDOWN) {
event_handler.stage->handle_shutdown();
}
// Later
event_handler.stage = std::make_unique<Stage2>();
if (event == SHUTDOWN) {
event_handler.stage->handle_shutdown();
}

Builder pattern - configuration file reading

I'm facing a design problem. I want to separate building objects with a builder pattern, but the problem is that objects have to be built from configuration file.
So far I have decided that all objects, created from configuration, will be stored in DataContext class (container for all objects), because these objects states will be updated from a transmission (so it's easier to have them in one place).
I'm using external library for reading from XML file - and my question is how to hide it - is it better to inject it to concreteBuilder class? I have to notice that builder class will have to create lots of objects and at the end - connect them between each other.
Base class could look like that:
/*
* IDataContextBuilder
* base class for building data context object
* and sub obejcts
*/
class IDataContextBuilder {
public:
/*
* GetResult()
* returns result of building process
*/
virtual DataContext * GetResult () = 0;
/*
* Virtual destructor
*/
virtual ~IDataContextBuilder() { }
};
class ConcreteDataContextBuilder {
public:
ConcreteDataContextBuilder(pugi::xml_node & rootNode);
DataContext * GetResult ();
}
How to implement it correctly? What could be better pattern to build classes from configuration files?
I don't see a problem with that, but maybe you could inject another 'Director' class that receives a specific builder, loads the config files, and produces objects calling the respective builder-subclasses.
What I mean:
class DataContextDirector {
public:
void SetBuilder(IDataContextBuilder* builder);
void SetConfig(const std::string& configFilePath); // or whatever
DataContext* ProduceObject() {
// pseudo-code here:
// myBuilder->setup(xmlNodeOfConfig);
// return myBuilder->GetResult();
}
};

Best approach to extend this C++ factory implementation?

I would like to extend an existing piece of code, and I'm not sure about the cleanest design approach to do so. I'm wondering if the existing design really supports the kind of extension that I'm thinking of.
There is a factory which looks like this:
class XYZFactory
{
public:
static XYZFactory& getDefaultInstance() // so this is a singleton!
// ... some create methods
// std::unique_ptr<ABC> createABC();
private:
std::unique_ptr<XYZFactoryImpl> m_impl;
}
---
XYZFactory::XYZFactory() : m_impl(std::make_unique<XYZImpl>;
Now the problem is that I would like to extend the functionality of XYZImpl by deriving from it. I would like to avoid to expose that implementation detail however in the factory class, like adding a separate XYZFactory constructor with a ExtendedXYZImpl as an argument to inject that extension.
ADDED/EDITED for clarifaction: I should have called XYZImpl XYZFactoryImpl. It does the actual object creation. XYZFactory passes the createWhatever() calls to it. There is only one instance of XYZImpl which is held in m_Impl.
The thing that I actually want to be able to dynamically change is a member of XYZImpl m_ABC (instance of ABC) which is used for the object creation. I would like to derive from ABC.
Would killing the singleton design and subclassing from XYZFactory help?
Any ideas?
Thank you!
Mark
XYZFactory currently has a dependency on XYZFactoryImpl so clearly there is no way of injecting a dependency on ExtendedXYZImpl without exposing that functionality on XYZFactory. If that is unacceptable, the only alternative is to abandon the current design of XYZFactory.
There are not a great deal of constraints left in your question for us to use to form an answer but I suggest you start by making XYZFactory an abstract factory:
class XYZFactory {
public:
virtual ~XYZFactory(){}
virtual std::unique_ptr<ABC> createABC() const = 0;
}
With two implementations:
class XYZFactoryImpl : public XYZFactory {
public:
std::unique_ptr<ABC> createABC() const override {
return std::make_unique<ABC>();
}
};
class ExtendedXYZFactoryImpl : public XYZFactory {
public:
std::unique_ptr<ABC> createABC() const override {
return std::make_unique<DerivedABC>();
}
};
You can then provide a function to get a singleton instance and a way of reseating with a different singleton instance. e.g:
namespace details {
// Or this could be hidden in an anonymous namespace in a .cpp file
std::unique_ptr<XYZFactory>& getXYZFactoryInstanceMutable() {
static std::unique_ptr<XYZFactory> singleton = std::make_unique<XYZFactoryImpl>();
return singleton;
}
}
const XYZFactory& getXYZFactoryInstance() {
auto& singleton = details::getXYZFactoryInstanceMutable();
if (!singleton)
throw std::runtime_error("No XYZFactory registered");
return *singleton;
}
void setXYZFactoryInstance(std::unique_ptr<XYZFactory> new_factory) {
details::getXYZFactoryInstanceMutable() = std::move(new_factory);
}
Then to inject in your ExtendedXYZFactoryImpl you could do:
setXYZFactoryInstance(std::make_unique<ExtendedXYZFactoryImpl>());
auto abc = getXYZFactoryInstance().createABC();
Live demo.

How to make class addable to fabric via preprocessor defenitions?

Say we have a base fabric element interface:
class BaseFabricElenent {
public:
BaseFabricElenent(){}
virtual ~BaseFabricElenent(){}
virtual void action(){}
};
We have an enumeration:
enum TypeCode {
TypeCodeLive = 10,
TypeCodeDie = 100
};
And we have implementations for our TypeCodes.
We want to get a fabric that would return desired type by TypeCode as BaseFabricElenent* as normal fabric would do.
How to add types to fabric via preprocessor define?
say:
class LiveFabricElenent: pulic BaseFabricElenent {
public:
LiveFabricElenent() :
BaseFabricElenent(){}
virtual ~LiveFabricElenent(){}
virtual void action(){}
};
ADD_TO_FABRIC(LiveFabricElenent);
Update:
Found this helpfull article on registration of types into factory on global initialization phase
. Creating a Define that would generate stub classes for types registring is all that left.
I think you don't need a macro to achieve your purpose. If you must use the enum, do something like this:
class Fabric {
public:
BaseFabricElement* createElement(TypeCode typeCode) {
switch (typeCode) {
case TypeCodeLive: return new LiveFabricElement();
case TypeCodeDead: return new DeadFabricElement();
// ... other cases ...
default: return NULL;
}
}
};
If the creation process does not depend on Fabric state, then the createElement method can be static. I would also consider returning a smart pointer instead of a raw one, and renaming Fabric to Factory.

How to mole or moq e particular function which gets called in a static function

I want to test a particular function.
That function has call to static method of a different class which is protected thus cannot be access from outside.
As I am doing component level testing I don't want to hit the database.
So is it possible to mock a particular call to database if its inside a static function.
//I want to test this function
public void testing
{
Abc.instance.Add();
}
class Abc
{
public static readOnly instance = new Abc();
Abc()
{
createInstance();
}
public void createInstance()// I want to mock this function
{
//calls to the database
}
public void Add()
{
//...
}
}
But even if I use delegate to mock createInstance() , before even going to delegate line , static block is getting called, thus hitting the database and an exception is thrown.