Two Singleton design modes

Source: Internet
Author: User

Java code
// Static methods and static members can be called by all objects.
// Is the referenced Variable Also a member variable?
 
/*
Requirements:
Define a class to ensure that the class only has one object in the memory.
 
Ideas:
1. Do not allow other classes to create such objects.
2. Define a class object.
3. Provide the custom object.
 
 
Design Mode: it is an effective solution to a certain type of problems.
 
Singleton design mode: Ensure the uniqueness of the class objects in the memory.
Steps:
1. Define private and static objects of this class.
2. private constructor.
3. Provide a static method to return this object.
*/
 
Class Single
{
Private static/* final */Single s = new Single ();
Private Single (){}
Public static Single getSingle ()
{
Return s;
}
 
}
 
Class Single2
{
Private static Single2 s = null;
 
Private Single2 (){}
 
Public static/* synchronized */Single2 getSingle2 ()
{
If (s = null)
S = new Single2 ();
Return s;
}
}
 
Class SingleDemo
{
Public static void main (String [] args)
{
 
Single s1 = Single. getSingle ();
Single s2 = Single. getSingle ();
 
S1.setAge (10 );
S2.setAge (30 );
 
System. out. println (s1.getAge ());
System. out. println (s2.getAge ());
}
}
 

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.