Right design pattern to deal with polymorphic collections of objects

后端 未结 5 1051
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-22 04:59

Suppose I have the following classes:

class BaseObject {
    public:
        virtual int getSomeCommonProperty();
};

class Object1: public BaseObject {
    publ         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-22 05:46

    Maybe this will do the trick here ?

    class CollectionManipulator {
    public:
        void someCommonTask(BaseCollection& coll) {
             for(unsigned int i = 0; i < coll.size(); i++)
                  someCommonTask(coll.getObj(i));
        }
    private:
        void someCommonTask(BaseObject*);  // Use baseObjects
    
    };
    
    class BaseCollection {
         friend class CollectionManipulator;
    private:
         virtual BaseObject* getObj(unsigned int) = 0;
         virtual unsigned int size() const = 0;
    };
    
    class Collection1 : public BaseCollection {
        vector objects;
    
    public:
        virtual void addObject() {
            Object1* obj = new Object1;
            objects.push_back(obj);
            baseObjects.push_back(obj);
        }
    
        void someSpecificTask(); // Use objects, no need of dynamic_cast<>
    
    private:
        BaseObject* getObj(unsigned int value) {
            return object[value];
        }
    
        unsigned int size() const {
            return objects.size();
        }
    }
    

    If you want abstract your container in Collection1 (like using list instead using vector), to use it in Manipulator, create an abstract iterator...

提交回复
热议问题