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,

Output

1
2
3
4
5
1
2

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,