2008年6月14日星期六

Singleton

  1. Intent - Ensure a class only has one instance, and provide a global point of access to it
  2. Motivation-
    Sometimes we want just a single instance of a class to exist in the systemé For example, we want just one window manager. Or just one factory for afamily of products.é We need to have that one instance easily accessible And
    we want to ensure that additional instances of the class can not be created

  3. Structure



  1. Implementation

There are two ways to implement Singleton. One is static Class and another is staticmethod.

  • The static class way
    declares the singleton class as final and all its methods are declared static, meaning that the class cannot be extended. One advantage of the final class approach is that you can use the class name directly to call the its method. However, you have to reprogram when you would like to drop the restrictions of Singleton status.
  • The static method way
    The key to creating a singleton is to prevent the client programmer from having any way to create an object except the ways you provide.
    You must make all constructors private, and you must create at least one constructor to prevent the compiler from synthesizing a default constructor for you (which it will create using package access).
    In Java , an object can be created cloning. The cloning is able to be prevented by making the class final. prevents cloning. However, if you’re inheriting from a class hierarchy that has already overridden clone( ) -a spublic and implemented Cloneable, you have to override clone( ) and throw a CloneNotSupportedException as described Actually, this isn’t precisely true, because even inthe above situation someone could still use reflection to invoke clone( ) [[is this true? clone( ) is still protected so I’m not so sure. If it is true, you’d have to throwCloneNotSupportedException as the only way to guarantee un-cloneability.

At this point , you can use the following template to create a singleton

1 define the final class Singleton

2 define a static Singleton Type member

3 private the default constructor to prevent initiate

4 create an static method allow client to get the static member.

5 override clone() to throw CloneNotSupportedException

There are two way in Singleton Class to initiate the static member. Eager way and lazy way.

Lazy way
can create the member on demand . However there could be more than one instance if two or more thread can instance() concurrently.

Eager way
can solve this problem to ensure there is only one instance in the program no matter how many threads call the instance().

Another method is sychronize the instance() but with much more cost

没有评论: