Home > Java > javaTutorial > body text

What is the singleton design pattern?

PHP中文网
Release: 2017-06-20 10:26:10
Original
1480 people have browsed it

The problem solved by the singleton design pattern: ensuring the uniqueness of the objects of a class in memory.

#For example: when multiple programs read a configuration file, it is recommended that the configuration file be encapsulated into an object. It will be convenient to operate the data in it, and to ensure that multiple programs read the same configuration file object, the configuration file object needs to be unique in the memory.

The Runtime() method is a guaranteed object designed in the singleton design pattern

## The idea of ​​uniqueness:

1. Do not allow other programs to create objects of this type;

2. Create an object of this class in this class;

3. Provide external methods to let other programs obtain this object.

Steps to ensure object uniqueness:

1.Because creating objects requires constructor initialization, as long as the constructor in this class is privatized, other programs cannot Create an object of this class;

##2.Create an object of this class in the class Object of class;

##3.Define a method to return the object so that other programs can obtain this type of object through the method. (Function: controllable)

##Reflection of code:

1. Private constructor;

2. Create a private and static object of this class;

3. Define a public and static method to return the object.

---------------------------------- -----------------------------------------------

##/********* Hungry Chinese Style *************/

class Single(){

## private Single() {} //Private constructor

## private static Single sg = new Single() ;//Create a private and static object of this class

## public static Single getInstance() { //Define a public static method and return the object

## Return sg;

## }


}

##/*********** Lazy Man Style: Lazy Loading Method *********/##

class Single2(){

  private Single2(){}

  private static Single2 sg2 = null;

  public static Single2 getInstance(){

    if( null == sg2 ){

      sg2 = new Single2();

      return sg2;

    }  

  }

}

 

The above is the detailed content of What is the singleton design pattern?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template