How can I prevent construction with Object Pool

166 views Asked by At

I want to use the Object Pool design pattern for my library, so that the user cannot create more than a predefined number of objects.
How can I force the user to use the Pool class for acquiring an instance, instead of constructor of the resource?

I can't declare the resource constructor private because then the pool class won't be able to create the instance either...

Thanks

2

There are 2 answers

0
justin On

use composition and a class which holds the collection. IOW, you give them a wrapper type around the collection which adjusts the visibility and handles object creation.

If you really want to restrict resource creation even further, you can bind without friendship using this approach (having seen the c++/friend comments):

class t_resource {
private:
    t_resource();
public:
    ~t_resource();

    static void AddToResourcePool(t_resource_pool& resourcePool) {
        if (resourcePool.isFull()) {
            /* error */
        }
        else {
            resourcePool.addResource(new t_resource);
        }
    }
};
0
Dave Newton On

The pool doesn't need to be separate from the class itself, or the class could composite in a pool, etc.

Instances would be retrieved from the object's (self-contained) pool, like a singleton, but a how-ever-many-you-want-eton.

You could also play games with visibility, but how to do so depends on the language, and IMO, probably not worth the effort--use a singleton-like pattern, but with n objects, instead of one.