Java Singleton, Lazy & A Hungry man

Source: Internet
Author: User

 * 单例模式Singleton* Application: Some objects need only one is enough, such as the Emperor * 作用: 保证整个应用程序中某个实例有且只有一个 * 区别: 饿汉模式的特点是加载类时比较慢,但运行是比较快-线程安全          懒汉模式的特点是加载类时比较快,但运行时比较慢-线程不安全

1. A Hungry man

1 //

2 Public class Singleton1 {
3     //Private default Construction child4     PrivateSingleton1 () {}5     //already instantiated on its own6     Private StaticFinal Singleton1 single =NewSingleton1 ();7     //Static Factory Method8      Public StaticSingleton1 getinstance () {9         returnSingle ;Ten     } One}

2. Lazy

1 //lazy Singleton class. Instantiated at the first call2  Public classSingleton2 {3     //Private default Construction child4     PrivateSingleton2 () {}5     //Note that there is no final6     Private StaticSingleton2 single=NULL;7     //Static Factory Method8      PublicSynchronizedStaticSingleton2 getinstance () {9          if(single =NULL) {  TenSingle =NewSingleton2 (); One          }   A         returnSingle ; -     } -}

Java Singleton, Lazy & A Hungry man

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.