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.

Let’s see the Code,

#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

Join a list of 2000+ Programmers for latest Tips & Tutorials