java - Having Trouble Understanding How To Use Singleton Pattern? -


i've been trying code that:

class 1 creates instance of class 2 (class t = new class() ). instance can used in class 1,2 , 3. i've been looking around bit , found "singleton pattern". don't understand how implement code though , fair few of sources saying different things...

thanks help, appreciated :)

singleton example: if have class phonebook , want every class of programm refer same phonebook. make class phonebook singleton-class.

in other words: singleton pattern used, asure every other code refering same object of singleton-class.

class phonebook {     //make constructor private no 1 can create objects, class     private phonebook() {     }     // static members hold (m_instance) , (getinstacnce) singleton instance of class     private static phonebook m_instance;     public static phonebook getinstance() {         if (m_instance == null) {             // first call getinstance, creates singelton instance, (phonebook) can call constructor;             m_instance = new phonebook();          }         return m_instance; //always same instance of phonebook     }     ... // members of phonebook (add/getphonenumber) } 

every part of software, same instance of phonebook. can register phonenumbers, every other class can read.

... phonebook l_phonebook = phonebook.getinstance(); l_phonebook.addphonenumber("yoschi", "01774448882") ...  // somewhere else phonebook l_phonebook = phonebook.getinstance(); phone.getinstance().call(l_phonebook.getphonenumber("yoschi")); 

Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -