JAVA basic singleton mode

Singleton mode

What is Singleton?

Insert picture description here

Singleton: refers to the singleton design pattern in JAVA. It is one of the most commonly used design patterns in software development.
This pattern involves a single class that is responsible for creating its own objects while ensuring that only a single object is created. This class provides a way to access its unique object, which can be accessed directly without instantiating objects of this class. Single: only case: instance


Basic knowledge:

Class: Refers to the definition of a kind of thing, which is an abstract concept.
Instance: Refers to the actual example, a concrete individual of the thing, or a concrete thing.
For example: "person" is a class. "Zhang San" is a concrete example of human beings, namely instantiation.
The same is true in programming. You first define a "class" yourself. When you need to use it, use the definition of "class" to create a concrete example.
Using the definition of a class to create an instance is called instantiation of the class.


Singleton design pattern, that is, a code pattern in which only one instance object of a certain class can be obtained and used in the entire system

note:

1. A singleton class can only have one instance.
How to call it? Constructor privatization

2. The singleton class must create its own unique instance.
Contains a static variable of the reclass to save this unique instance

3. The singleton class must provide this instance to all other objects.
Provide external methods to obtain the instance object:
(1) directly exposed
(2) use static variable get method to obtain


Examples:

1. There is only one head teacher in a class.
2. Windows is multi-process and multi-threaded. When operating a file, it is inevitable that multiple processes or threads operate a file at the same time. Therefore, the processing of all files must be carried out through a single instance.
3. Some device managers are often designed as a singleton mode. For example, a computer has two printers, and when outputting, it is necessary to deal with that the two printers cannot print the same file.


advantage:

1. There is only one instance in the memory, which reduces the memory overhead, especially the frequent creation and destruction of instances (such as the home page cache of the School of Management).
2. Avoid multiple occupation of resources (such as file writing operations).

Disadvantages:

There is no interface, no inheritance, and conflicts with the single responsibility principle. A class should only care about the internal logic, not how to instantiate it outside.


Several common forms:

Hungry Chinese style: Create objects directly, without thread safety issues
-Direct instantiation Hungry Chinese style (concise and intuitive)
-Enumeration (the most concise)
-Static code block Hungry style (suitable for complex instantiation)

Lazy style: Delayed creation of objects
-unsafe thread (suitable for single thread)
-thread safe (suitable for multithreading)
-static internal class form (suitable for multithreading)



Hungry Chinese Style:

package com.tedu.single;

/**
 * 饿汉式:
 * 直接创建实例对象,不管你是否需要这个对象,都会创建
 *
 * 1.构造器私有化 private
 * 2.自行创建,并且静态变量保存 static
 * 3.向外提供这个实例 public
 * 4.强调这是一个单例,我们可以final修饰
 *
 * 常量我们习惯性的写为大写 INSTANCE
 */
public class Singleton1 {
    
    
    public static final Singleton1 INSTANCE = new Singleton1();
    private Singleton1(){
    
    

    }
}

Acquisition method test:

package com.tedu.test;

import com.tedu.single.Singleton1;

public class TestSingleton1 {
    
    
    public static void main(String[] args) {
    
    
        Singleton1 s = Singleton1.INSTANCE;
        System.out.println(s);
    }
}

operation result:
Insert picture description here

enumerate:

package com.tedu.single;
/**
 * 枚举类型:表示该类型的对象是有限的几个
 * 我们可以限定为一个,就成了单例
 */
public enum Singleton2 {
    
    
    INSTANCE;
}

Acquisition method test:

package com.tedu.test;

import com.tedu.single.Singleton2;

public class TestSingleton1 {
    
    
    public static void main(String[] args) {
    
    
        Singleton2 s = Singleton2.INSTANCE;
        System.out.println(s);
    }
}

operation result:
Insert picture description here

We can find that there is no difference between the two modes, basically the same, the difference between before JDK1.5 and after JDK1.5.

Static code block:

package com.tedu.single;

import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader;

import java.io.IOException;
import java.util.Properties;
//静态代码块
public class Singleton3 {
    
    
    public static final Singleton3 INSTANCE;
    //什么时候可能会用到这种方法呢?属性需要初始化
    private String info;
    static {
    
    
        try {
    
    
            Properties pro=new Properties();
            pro.load(Singleton3.class.getClassLoader().getResourceAsStream("single.properties"));
            INSTANCE = new Singleton3(pro.getProperty("info"));
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
    private Singleton3(String info){
    
    
        this.info=info;
    }
    public static Singleton3 getINSTANCE() {
    
    
        return INSTANCE;
    }
    public String getInfo() {
    
    
        return info;
    }
    public void setInfo(String info) {
    
    
        this.info = info;
    }
}

The above are three ways of writing in hungry Chinese style


Lazy man:

package com.tedu.test;

import com.tedu.single.Singleton4;

public class TsetSingleton4 {
    
    
    public static void main(String[] args) {
    
    
        Singleton4 s1= Singleton4.getInstance();
        Singleton4 s2= Singleton4.getInstance();

        System.out.println(s1==s2);
        System.out.println(s1);
        System.out.println(s2);
    }
}

test:

package com.tedu.test;

import com.tedu.single.Singleton4;

public class TsetSingleton4 {
    
    
    public static void main(String[] args) {
    
    
        Singleton4 s1= Singleton4.getInstance();
        Singleton4 s2= Singleton4.getInstance();

        System.out.println(s1==s2);
        System.out.println(s1);
        System.out.println(s2);
    }
}

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/QQ1043051018/article/details/112911713