Something About Singleton

1: Differences between Static Method and Singleton

         Static:has little or no state, can’t extend types and can’t be typed

Singleton: mayhave a state, cant extend types and be typed.

 

  So,when you need an unique object, if the object is stateless, you can use staticmethod; otherwise using singleton will be better.

 

2: what’s the bad of Singleton?

     Thereare at least two disadvantages:

     First:

Look at the below code that use a singletonobject:

 

     Public class SomeClass {

                   PrivateSingleton singleton = Singleton.getInstance();

       … use singleton to do something in methods.

          }

 

 theSomeClass are tight coupled with singleton, the SomeClass must also test thesingleton object when doing testing. But in fact the SomeClass do not need totest the singleton object.

         Sowe can pass the Singleton to the SomeClass de constructor, so the SomeClassneedn’t to test the singleton object.

 

     Second: the Singleton classbreaks the Single ResponsibilityPrinciple.  Singleton class holds the business logic aswell as it’s own creation logic.

posted on 2010-11-24 11:14  NanguoCoffee  阅读(175)  评论(0编辑  收藏  举报

导航