- Joined
- Aug 27, 2017
- Messages
- 110
Hello,
I had an idea how pools could be enhanced. Here is my concept:
My pool class is still compatible with the current brl pools. The difference is that if a class implements the IOnPoolAllocate interface an initialization method will automatically be called when Pool.Allocate() will be called (same goes for IOnPoolFree when Pool.Free() will be called).
So like constructors/destructors this can be used to initialize and clean up objects automatically.
Here is how it can be used:
I had an idea how pools could be enhanced. Here is my concept:
Code:
Class Pool<T>
Private
Field _pool := New Stack<T>
Global _HasOnPoolAllocate:Int = Pool<T>.UNKNOWN
Global _HasOnPoolFree:Int = Pool<T>.UNKNOWN
Const UNKNOWN:Int = 0
Const YES:Int = 1
Const NO:Int = 2
Public
Method New(initialCapacity:Int = 10)
For Local i:Int = 0 Until initialCapacity
_pool.Push New T
Next
End
Method Allocate:T()
Local o:T
If _pool.IsEmpty() Then
o = New T
Else
o = _pool.Pop()
End
Select _HasOnPoolAllocate
Case YES
IOnPoolAllocate(o).OnPoolAllocate()
Case UNKNOWN
_HasOnPoolAllocate = NO
If IOnPoolAllocate(o) Then
_HasOnPoolAllocate = YES
IOnPoolAllocate(o).OnPoolAllocate()
End
End
Return o
End
Method Free:Void(o:T)
Select _HasOnPoolFree
Case YES
IOnPoolFree(o).OnPoolFree()
Case UNKNOWN
_HasOnPoolFree = NO
If IOnPoolFree(o) Then
_HasOnPoolFree = YES
IOnPoolFree(o).OnPoolFree()
End
End
_pool.Push(o)
End
End
Interface IOnPoolAllocate
Method OnPoolAllocate:Void()
End
Interface IOnPoolFree
Method OnPoolFree:Void()
End
So like constructors/destructors this can be used to initialize and clean up objects automatically.
Here is how it can be used:
Code:
Class Foo Implements IOnPoolAllocate, IOnPoolFree
Method OnPoolAllocate:Void()
Print "init stuff"
End
Method OnPoolFree:Void()
Print "clean up stuff"
End
End
Function Main:Int()
Local FooPool := New Pool<Foo>
Local bar := FooPool.Allocate() ' => prints "init stuff"
FooPool.Free(bar) ' => prints "clean up stuff"
Return 0
End