Designing a Multiton: Singleton that returns 5 objects in cycle

Let’s Design a Multiton class i.e. a modified Singleton to return 5 objects in cycle.

Logic to Create Multiton

  • Instead of keeping a static pointer as member variable keep a vector of pointers as member variable.
  • Now also keep track of how many times getInstance() function is called. To do that use static member variable current and increment current index every time getInstance() is called.
  • Also keep current index in 0 to 4 always i.e. keep it modulus from LIMIT i.e. 5
  • Then whenever getInstance() is called just return the current index pointer from internal vector.

[showads ad=inside_post]

Let’s see the Code,

Advertisements

#include <iostream>
#include <vector>

#define LIMIT 5

class Multiton
{
private:
	static std::vector<Multiton *> listOfInstancePtrs;
	// Limit of Objects this class will return in cycle
	static int limit;
	// Current index of getInstance() function call
	static int currentIndex;
	// ID of each object
	int mId;
	Multiton()
	{
		mId = currentIndex + 1;
	}

public:
	int getId()
	{
		return mId;
	}
	// Reserver initial size
	static int reserverSize()
	{
		Multiton::listOfInstancePtrs.reserve(LIMIT);
		for(int i = 0; i < LIMIT; i++)
		{
			Multiton::listOfInstancePtrs[i] = NULL;
		}
		return LIMIT;
	}
	static Multiton *getInstance()
	{

		currentIndex = currentIndex % LIMIT;

		if(!Multiton::listOfInstancePtrs[currentIndex % limit])
		{
			Multiton::listOfInstancePtrs[currentIndex % limit] = new Multiton();
		}
		return Multiton::listOfInstancePtrs[currentIndex++ % limit];
	}

};

std::vector<Multiton *> Multiton::listOfInstancePtrs;
int Multiton::limit = Multiton::reserverSize();
int Multiton::currentIndex =  0;

int main()
{
	std::cout<<Multiton::getInstance()->getId()<<std::endl;
	std::cout<<Multiton::getInstance()->getId()<<std::endl;
	std::cout<<Multiton::getInstance()->getId()<<std::endl;
	std::cout<<Multiton::getInstance()->getId()<<std::endl;
	std::cout<<Multiton::getInstance()->getId()<<std::endl;
	std::cout<<Multiton::getInstance()->getId()<<std::endl;
	std::cout<<Multiton::getInstance()->getId()<<std::endl;
	return 0;
}

Output

1
2
3
4
5
1
2

Do you want to Learn Modern C++ from best?

We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.

Check Detailed Reviews of Best Modern C++ Courses

Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top