A single-instance pattern of Java design patterns

Source: Internet
Author: User

A single-instance pattern of Java design patterns

Recently because want to understand the bottom of the source code, so looked at some design patterns, follow-up to read several kinds of writing

Single-Case Pattern English Original:

    • Ensure a class have only one instance,and provide a global point of access to it
    • That is: Throughout the application, make sure that there is only one instance of a class and provide this instance to the entire system
There are typically two representations in Java
    • A hungry man type Singleton: class is instantiated at load time
    • Lazy Singleton: Loading is only instantiated the first time

1. A hungry man type single case

Singleton
static Singleton m_instance = new Singleton ()
Static getinstance (): Singleton

Source:

publicclass Singleton{     privateSingleton() {}      privatestaticfinalnewSingleton();      //静态工厂方法       publicstaticgetInstance() {          return single;      }  }//成员变量是私有的,而且不能被外部访问

2, lazy-type single case

Singleton
static Singleton m_instance = null
syncchronized static getinstance (): Singleton

Source:
java public class Singleton { private Singleton() {} private static Singleton single=null; public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } } //双重校验锁

    • The first one is more resource-intensive, but the speed of reflection is relatively good.
    • The second is cool, but it consumes the performance of the runtime, but the impact is minimal.
    • In the end, the first is more suitable for user resource configuration, the second is more suitable for the business logic of the singleton mode

With the help of: Electronic industry Press "design principles" Thanks!

A single-instance pattern of Java design patterns

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.