A single-instance pattern of Java design patterns

Source: Internet
Author: User

/**
Design pattern: GOF (Gang of Four) book: design mode


Singleton design pattern: Resolves a class that only has one object in memory.
*/
/**
A hungry man singleton mode: Initializes an object first. Commonly used in development.
*/
Class single{
private String name;
private int age;

Private single () {}; These three steps ensure that the class has only one object in memory.
private static Single S = new single ();
public static single getinstance () {//Developer but use getinstance method on Demand
return s;
}
public void Setage (int.) {
This.age = age;
}
public int getage () {
return age;
}
public void SetName (String name) {
THIS.name = name;
}
Public String GetName () {
return name;
}
}
/**
Lazy Singleton mode: An object is initialized when the program calls the method.
*/
Class single1{
private String name;
private int age;
Private Single1 () {}; These three steps ensure that the class has only one object in memory.
private static Single1 s = new Single1 ();
The difference between the public static Single1 getinstance () {//A hungry man type and the lazy type is here.
if (s = = null) {
Synchronized (Single1.class) {//prevents the program from running into a deadlock state.
if (s = = null)
s = new Single1 ();
}
}
return s;
}
public void Setage (int.) {
This.age = age;
}
public int getage () {
return age;
}
public void SetName (String name) {
THIS.name = name;
}
Public String GetName () {
return name;
}
}
Class singledemos{
public static void Main (String args[]) {
Single1 S1 = single1.getinstance ();
Single1 s2 = single1.getinstance ();
S1.setname ("Lzl");
System.out.println (S2.getname ());
}
}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.