Evgenii Legotckoi
Evgenii LegotckoiSept. 18, 2018, 4:01 a.m.

Generative Design Patterns - Object Pool

Goals

Object pooling can greatly improve performance; it is most effective in situations where the cost of initializing an instance of a class is high and the rate of instantiation of the class is high, while the number of instances in use at any given time is small.

Problems

Object pools (otherwise known as resource pools) are used to manage object caching. A client that has access to an object pool can avoid creating new objects by simply asking the pool for a new object that has already been created. Typically, a pool will be a growing pool, i.e. the pool itself will create new objects if the pool is empty. We can also have a pool that limits the number of objects created.

It is desirable to keep all reusable objects that are not currently in use in the same object pool so that they can be managed by one consistent policy. To achieve this, the reusable pool class must implement the Singleton design pattern.


Discussion

The object pool allows other objects to "check" objects from their pool, when those objects are no longer needed by their processes, they are returned to the pool for reuse.

However, we don't want the process to have to wait for a particular object to be allocated, so the object pool also creates new objects as needed, but also needs to use a facility to periodically clean up unused objects.

Structure

The general idea of the connection pool pattern is that if class instances can be reused, then you avoid creating class instances by reusing them.

  • Reusable . Instances of classes in this role interact with other objects for a limited period of time, after which they are no longer needed for this collaboration.
  • Client . Class instances in this role use reusable objects.
  • ReusablePool. Class instances in this role manage reusable objects for use by Client objects.

It is generally desirable to keep all reusable objects that are not currently in use in the same object pool so that they can be managed by one consistent policy. Therefore the ReusablePool class is for the Singleton class. Its constructor(s) are private, which forces other classes to call the getInstance method to get the same instance of the ReusablePool class.

The Client object calls the acquireReusable method of the ReusablePool object when it needs a reusable object. The ReusablePool object maintains a collection of reusable objects. It uses a collection of reusable objects to contain a pool of reusable objects that are not currently in use.

If there are any reusable objects in the pool, when the acquireReusable method is called, it removes the Reusable object from the pool and returns it. If the pool is empty, the acquireReusable method creates a reusable object if possible. If the acquireReusable method cannot create a new reusable object, it waits until the collection object is returned to the collection again.

Client objects pass a reusable object to the releaseReusable method on the ReusablePool when they have finished working with the object. The releaseReusable method returns a reusable object to a pool of reusable objects that are not being used.

In many applications, the object pool design pattern has reasons for limiting the total number of reusable objects that can exist. In such cases, the ReusablePool object that creates reusable objects is responsible for ensuring that it does not create more objects than the specified maximum number of reusable objects. If ReusablePool objects are responsible for limiting the number of objects that are created, then the ReusablePool class will have a method to specify the maximum number of objects that will be created. This method is listed in the diagram above as setMaxPoolSize.

Example

An object pool is similar to an office warehouse. When a new employee is hired, the office manager must prepare a workplace for him. It calculates whether there is spare equipment in the warehouse of the office. If so, then the office manager uses it. If not, it places an order to purchase new equipment from Amazon. In the event that an employee is fired, his equipment is moved to a warehouse where it can be taken when a new workplace is needed.

Control List

  1. Create an ObjectPool class with a private array of objects inside
  2. Create acquire and release methods
  3. Make sure the ObjectPool will work as a singleton

Rules of thumb

  • The Factory Method pattern can be used to encapsulate object creation logic. However, after they are created, it does not manage them, the object pool pattern keeps track of the objects it creates.
  • Pel objects are usually implemented as a singleton
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 2:56 p.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 2:45 p.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 2:35 p.m.

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 9, 2024, 5:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 9:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 7:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 8:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
BlinCT
BlinCTMay 5, 2024, 3:46 p.m.
Написать свой GraphsView Всем привет. В Qt есть давольно старый обьект дял работы с графиками ChartsView и есть в 6.7 новый но очень сырой и со слабым функционалом GraphsView. По этой причине я хочу написать х…
BlinCT
BlinCTMay 5, 2024, 3:44 p.m.
добавить qlineseries в функции Давно я не работал с виджетами и с формами, на мой взгляд уже пережитов, и в управлении не очень удобное это все. Н оя у вас не увидел в коде где вы QCharts растягиваете на область парента.…
PS
Peter SonMay 4, 2024, 3:57 a.m.
Best Indian Food Restaurant In Cincinnati OH Ready to embark on a gastronomic journey like no other? Join us at App india restaurant and discover why we're renowned as the Best Indian Food Restaurant In Cincinnati OH . Whether y…
Evgenii Legotckoi
Evgenii LegotckoiMay 3, 2024, 12:07 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Добрый день. По моему мнению - да, но то, что будет касаться вызовов к функционалу Андроида, может создать огромные трудности.
IscanderChe
IscanderCheApril 30, 2024, 2:22 p.m.
Во Flask рендер шаблона не передаётся в браузер Доброе утро! Имеется вот такой шаблон: <!doctype html><html> <head> <title>{{ title }}</title> <link rel="stylesheet" href="{{ url_…

Follow us in social networks