Can I implement the Factory Method pattern in C++

2019-01-23 19:31发布

I'm working in an embedded environment (Arduino/AVR ATMega328) and want to implement the Factory Method pattern in C++. However, the compiler I'm using (avr-gcc) doesn't support the new keyword. Is there a way of implementing this pattern without using new?

7条回答
成全新的幸福
2楼-- · 2019-01-23 20:37

A way I've solved this problem in an embedded system with strict coding standards (where we were not allowed to use "new" or "delete") was to create a static array of the desired object. And then use static pointers to the already-allocated objects, storing these returned values (using static variables and/or member variables) for later execution of the various objects.

// Class File ---------------------------------------------------
class MyObject {
    public:
        MyObject* getObject();

    private:
        const int MAX_POSSIBLE_COUNT_OF_OBJECTS = 10;
        static MyObject allocatedObjects[MAX_POSSIBLE_COUNT_OF_OBJECTS];

        static allocatedObjectIndex = 0;
};

// Implementation File ------------------------------------------

// Instantiate a static array of your objects.
static MyObject::allocatedObject[MAX_POSSIBLE_COUNT_OF_OBJECTS];

// Your method to return already created objects.
MyObject* MyObject::getObject() {

    if (allocatedObjectIndex < (MAX_POSSIBLE_COUNT_OF_OBJECTS - 1)) {
        return allocatedObjects[allocatedObjectIndex++];
    } else {
        // Log error if possible
        return NULL;
    }
}

Please be forewarned. This is all from memory as I haven't written any C++ in over 8 months.

Also Note: This has a serious drawback in that you are allocating a bunch of RAM at compile time.

查看更多
登录 后发表回答