Singleton mode (Singleton)

Source: Internet
Author: User

conditions of Use: You can use this mode when you only need a unique object for a class in your system .

Why is this pattern used? : Because sometimes the creation of some objects requires a lot of resources, using a single (unique) object instance to maintain some shared data, and so on, in these scenarios can be designed in a single-case mode, it is appropriate to reduce the memory overhead, because the unique object is not (limited) to create frequently.


The first type: full-han mode

public class singleton{

Private SingleTon () {};

private static SingleTon instance = new SingleTon ();

public static SingleTon getinstance ()

{

return instance;

}

}


The second type: Hunger and Han Mode

public class singleton{

Private SingleTon () {};

private static SingleTon instance = Null;//new singletonight ();

public static synchronized SingleTon getinstance ()

{

if (instance==null) instance = new SingleTon ();

return instance;

}

}

This method is better than the above method, not every time the generation of objects, but the first use of the build instance, improve efficiency.

Noting the second form of synchronized, this synchronized is important, if not synchronizedThere can be confusion when a thread accesses it at the same time, so we can add it before the methodsynchronizedkeyword to ensure that it is accessed synchronously.

in a comprehensive sense,
is to not give the outside world the chance to call their own construction method,
You can only get instances of this class by means such as getinstance (),
and this instance has already been generated,
can only be called,
cannot be created,
This ensures that only one instance of a class exists in a Java application.


Singleton mode (Singleton)

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.