Java Design Pattern Single example mode (reprint)

Source: Internet
Author: User

Concept:
   In Java, the singleton pattern is a common design pattern, and the singleton pattern is divided into three kinds: lazy type single case, a hungry man type single case, registration type single case three kinds.
There are a few features of the Singleton model:
   1, the Singleton class can have only one instance.
2, the Singleton class must create its own unique instance on its own.
3, the Singleton class must provide this instance to all other objects.
< Span style= "line-height:1.8; margin:0px; Font-family: Song body; Color:black; padding:0px; " >

First, we look at a classic single-instance implementation.

[Java]View Plaincopyprint?
  1. Public class Singleton {
  2. private static Singleton uniqueinstance = null;
  3. Private Singleton () {
  4. //Exists only to defeat instantiation.
  5. }
  6. public static Singleton getinstance () {
  7. if (uniqueinstance = = null) {
  8. Uniqueinstance = new Singleton ();
  9. }
  10. return uniqueinstance;
  11. }
  12. //Other methods ...
  13. }


Singleton by restricting the construction method to private to prevent the class from being instantiated externally, the unique instance of Singleton can only be accessed through the getinstance () method within the same virtual machine scope. (In fact, the Java reflection mechanism is the ability to instantiate a class constructed as private, which basically invalidates all Java Singleton implementations.) This issue is not discussed here, and it is deceiving to assume that the reflection mechanism does not exist. )

However, the above implementations do not take into account thread safety issues. Thread safety refers to the idea that if your code is in a process where multiple threads are running concurrently, these threads may run the code at the same time. If the result of each run is the same as the single-threaded run, and the value of the other variable is the same as expected, it is thread-safe. Or, the interface provided by a class or program for a thread is an atomic operation or a switchover between multiple threads does not result in ambiguity in the execution of the interface, that is, we do not have to consider the problem of synchronization. Obviously the above implementations do not meet the requirements of thread safety, and many singleton instances are likely to occur in concurrent environments.

[Java]View Plaincopyprint?
  1. Package jason.single;
  2. Public class Teststream {
  3. String name = null;
  4. Public String GetName () {
  5. return name;
  6. }
  7. public void SetName (String name) {
  8. this.name = name;
  9. }
  10. Private Teststream () {
  11. }
  12. private static Teststream ts1 = null;
  13. public static Teststream gettest () {
  14. if (ts1 = = null) {
  15. Ts1 = new Teststream ();
  16. }
  17. return ts1;
  18. }
  19. public void Printinfo () {
  20. System.out.println ("The name is" + name);
  21. }
  22. }


[Java]View Plaincopyprint?
  1. Package jason.single;
  2. Public class Tmain {
  3. public static void Main (string[] args) {
  4. Teststream ts1 = Teststream.gettest ();
  5. Ts1.setname ("Jason");
  6. Teststream ts2 = Teststream.gettest ();
  7. Ts2.setname ("0539");
  8. Ts1.printinfo ();
  9. Ts2.printinfo ();
  10. if (ts1 = = ts2) {
  11. System.out.println ("created is the same instance");
  12. }else{
  13. System.out.println ("Not the same instance created");
  14. }
  15. }
  16. }

Operation Result:


Conclusion: The result shows that the singleton pattern provides an object-only access point for an object-oriented application, and the entire application can enjoy an instance object regardless of the function it implements.

1. A hungry man type single case class

[Java]View Plaincopyprint?
  1. A hungry man Singleton class. When class is initialized, it is self-instantiated
  2. Public class Singleton1 {
  3. //Private default constructor
  4. Private Singleton1 () {}
  5. //already self-instantiated
  6. private static final Singleton1 single = new Singleton1 ();
  7. //Static Factory method
  8. public static Singleton1 getinstance () {
  9. return single;
  10. }
  11. }


2. Lazy single-case class

[Java]View Plaincopyprint?
  1. Lazy Singleton class. Instantiated at the first call
  2. Public class Singleton2 {
  3. //Private default constructor
  4. Private Singleton2 () {}
  5. //Note that there is no final
  6. private static Singleton2 single=null;
  7. //Static Factory method
  8. public synchronized static Singleton2 getinstance () {
  9. if (single = null) {
  10. Single = new Singleton2 ();
  11. }
  12. return single;
  13. }
  14. }


[Java]View Plaincopyprint?
    1. Import Java.util.HashMap;
    2. Import Java.util.Map;
    3. Registered Singleton class.
    4. Similar to the method in spring, the class name is registered, the next time from the inside to get directly.
    5. Public class Singleton3 {
    6. private static map<string,singleton3> Map = new hashmap<string,singleton3> ();
    7. static{
    8. Singleton3 single = new Singleton3 ();
    9. Map.put (Single.getclass (). GetName (), single);
    10. }
    11. //Protect the default construction child
    12. protected Singleton3 () {}
    13. //Static factory method to return such unique instances
    14. public static Singleton3 getinstance (String name) {
    15. if (name = = null) {
    16. Name = Singleton3.  Class.getname ();
    17. System.out.println ("name = = NULL" +"--->name=" +name);
    18. }
    19. if (map.get (name) = = null) {
    20. try {
    21. Map.put (name, (Singleton3) class.forname (name). newinstance ());
    22. } catch (Instantiationexception e) {
    23. E.printstacktrace ();
    24. } catch (Illegalaccessexception e) {
    25. E.printstacktrace ();
    26. } catch (ClassNotFoundException e) {
    27. E.printstacktrace ();
    28. }
    29. }
    30. return Map.get (name);
    31. }
    32. //A schematic business approach
    33. Public String About () {
    34. return "Hello, I am Regsingleton.";
    35. }
    36. public static void Main (string[] args) {
    37. Singleton3 single3 = singleton3.getinstance (null);
    38. System.out.println (Single3.about ());
    39. }
    40. }

Java Design Pattern Single example mode (reprint)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.