Singleton mode--Single State mode

Source: Internet
Author: User

Single State mode:

To prevent a class of a single state pattern from being instantiated multiple times, you should set the constructor of the class to private, which guarantees that the class instance can only be obtained through a static method. And the static method guarantees

Each returned instance is the same, so that an instance of the class needs to be set as a class property, which can be set to static because it needs to be accessed by a static method

Property. Instances of a single State class are the same shared instance.

The sample code for a single state pattern is as follows:

public class Singletontest

{

int value;

private static Singletontest instance;

Private Singletontest ()

{

SYSTEM.OUT.PRINTLN ("Executing builder ...");

}

public static Singletontest getinstance ()

{

if (instance = null)

{

Instance = new Singletontest ();

}

return instance;

}

public int GetValue ()

{

return value;

}

public void SetValue (int value)

{

This.value = value;

}

public static void Main (string[] args)

{

singletontest T1 = singletontest.getinstance ();

Singletontest t2 = singletontest.getinstance ();

T2.setvalue (9);

System.out.println (T1==T2);

}

}

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.