Suppose i’m writing a software that it has about 50 classes.
We can divide classes into 2 part:
1. classes we forced to create instance for more that of once instance.
2. classes we just create a one instance until end of program.
So, suppose i have MainProgram class and everything do here, then just
make an instance in main.cpp and run my program.
Now, I need to pass instances created just once (option 2) to other classes, Do you
have any idea to implement to this?
Because i can’t new again. i just work with old instance.For example:
I wrote a SocketNetwork Class that its constructor get port number and bind to it.
So i can’t rebind again and i forced to access to resoures of the given port number.
Seems like you’re looking for the singleton pattern.
It goes something like:
Because the constructor is private, you can only get the single instance of
Athat is created through thegetInstance()method, which you can call anywhere.will always return the same instance of
A.