难以理解如何使用Singleton模式?

时间:2014-09-20 23:32:20

标签: java design-patterns singleton

我一直在努力编写代码以便:

Class 1创建了Class 2的实例(Class t = new Class())。该实例可用于1,2和3类。 我一直在四处寻找并发现了“Singleton Pattern”。我不明白我是如何在我的代码中实现这一点的,而且很少有消息来源都说不同的东西......

感谢您的帮助,非常感谢:)

2 个答案:

答案 0 :(得分:2)

Singleton示例:如果您有类电话簿,并且您希望程序的每个类都引用同一个电话簿。您可以将Class Phonebook变为Singleton-Class。

换句话说:使用Singleton模式,以确保每个其他代码都引用Singleton-Class的相同Object。

class Phonebook {
    //Make the constructor private so no one can create objects, but this class
    private Phonebook() {
    }
    // to static members to hold (m_Instance) and get (getInstacnce) the Singleton Instance of the class
    private static Phonebook m_Instance;
    public static Phonebook getInstance() {
        if (m_Instance == null) {
            // first call to getInstance, creates the Singelton Instance, only we (Phonebook) can call the constructor;
            m_Instance = new Phonebook(); 
        }
        return m_Instance; //always the same Instance of Phonebook
    }
    ... // Members of the Phonebook (add/getPhoneNumber)
}

该软件的每个部分都将获得与电话簿相同的实例。所以我们可以注册phonenumbers,其他所有类都可以阅读。

...
Phonebook l_Phonebook = Phonebook.getInstance();
l_Phonebook.addPhoneNumber("Yoschi", "01774448882")
... 
// somewhere else
Phonebook l_Phonebook = Phonebook.getInstance();
Phone.getInstance().call(l_Phonebook.getPhoneNumber("Yoschi"));

答案 1 :(得分:1)

以下是说明的链接:

http://en.wikipedia.org/wiki/Singleton_pattern

示例代码将是

public class singleton
   {
       public static singleton _obj;
       private singleton()
       {
           // prevents instantiation from external entities
       }
       public static singleton GetObject() // instead of creating new operator, declare a method and that will create object and return it.
       {
           if (_obj == null) //Checking if the instance is null, then it will create new one and return it 
           //otherwise it will return previous one.
           {
               _obj = new singleton();
           }
           return _obj;
       }
       public void printing(string s)
       {
           Console.WriteLine(s);
       }
   }

这是一个c#代码,但概念与java相同。