BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Design Patterns
.NET 2.0+

Object Pool Design Pattern

The object pool pattern is a creational design pattern that can improve performance when working with classes that are slow to instantiate. Rather than constructing new objects, reusable objects are retrieved from, and released to, a pool as required.

Testing the Object Pool

Let's try out the example code using the Main method of a console application as the client. In the code below, two pickers are requested from the pool. Each is identified and then sent to a location to pick up an item. The two items are then dropped at the "Build Room" location before the pickers are released back to the pool.

After this operation, six new pickers are requested. The first five requests are successful, picking the three unused robots and the two that were recently returned to the charging station. The sixth request fails because the pool is exhausted.

Try stepping through the code and watching the results that are outputted to the console.

AutomatedPicker pickerA = PickerPool.GetPicker();
AutomatedPicker pickerB = PickerPool.GetPicker();

pickerA.Identify("PA");
pickerB.Identify("PB");

pickerA.GoToLocation("Bay 1");
pickerB.GoToLocation("Bay 3");

pickerA.Pick("Processor");
pickerB.Pick("RAM");

pickerA.GoToLocation("Build Room");
pickerB.GoToLocation("Build Room");

pickerA.Drop();
pickerB.Drop();

PickerPool.ReleasePicker(pickerA);
PickerPool.ReleasePicker(pickerB);

AutomatedPicker pickerC = PickerPool.GetPicker();
AutomatedPicker pickerD = PickerPool.GetPicker();
AutomatedPicker pickerE = PickerPool.GetPicker();
AutomatedPicker pickerF = PickerPool.GetPicker();
AutomatedPicker pickerG = PickerPool.GetPicker();
AutomatedPicker pickerH = PickerPool.GetPicker();

/* OUTPUT

Picker 1 : Identified as PA
Picker 2 : Identified as PB
Picker 1 : At Bay 1
Picker 2 : At Bay 3
Picker 1 : Picked Up Processor
Picker 2 : Picked Up RAM
Picker 1 : At Build Room
Picker 2 : At Build Room
Picker 1 : Dropped Processor
Picker 2 : Dropped RAM
Picker 1 : At Recharging Station
Picker 2 : At Recharging Station

*/
30 June 2013