I'm building an object pool and am find it really tedious to regularly reference a factory or and object pools to handle objects. Instead I'm considering building the pool directly into the object's class.
Abstract Object Class:
class Object(ABC):
_pool = []
_max_pool_size = 10
def __new__(cls, *args, **kwargs):
if cls._pool:
instance = cls._pool.pop()
instance.__init__(*args, **kwargs)
return instance
else:
return super().__new__(cls)
@classmethod
def release(cls, instance):
if len(cls._pool) < cls._max_pool_size:
cls._pool.append(instance)
Implementation:
@dataclass
class FooObject(Object):
n: int
foo_1 = FooObject(1)
FooObject.release(foo_1)
But when researching the ObjectPool design pattern it seems more common to separate the Pool, Objects, and use a Factory. Why is that and what problem would I run into with this method?
You can answer your question from different perspectives.
Object.Object. We must be able to access the pool without having to deal with theObject.Objectclass. Pool andObjectuse completely independent logics. For example,Objectcould deal with user credentials. Why would such an object also contain the logic to manage the pool? Separating the two responsibilities also enables that aPooland anObjectclass are in different logical locations (source files, DLL etc.) or physical locations (e.g. client-server).If you understand some OO deign principles you feel that it is semantically the wrong design decision to have the
Objectto implement its own pool.Unless you are a tortoise, a house and its inhabitant are two completely separate objects that share nothing. One uses the other. Both must exist individually. Both have different individual lifetimes. Both work and behave differently.
Although it is possible to have the object pool implemented by the
Objectitself it will produce ugly and overly complicated code and relationships between types.If you can answer the following question, you can also answer your own question:
"Why don't we have a single big class that contains the application?"