Home >Java >javaTutorial >Completely master the Java singleton pattern

Completely master the Java singleton pattern

WBOY
WBOYforward
2022-04-13 19:04:081877browse

This article brings you relevant knowledge about java, which mainly introduces related issues about the singleton mode, which means that a class has only one instance, and the class can create this instance by itself A model, let's take a look at it together, I hope it will be helpful to everyone.

Completely master the Java singleton pattern

## Recommended study: "

java video tutorial"

Single case mode:

First of all, there are 23 design patterns in Java:

  • Creative pattern: Factory method pattern, abstract factory pattern, Singleton mode, builder mode, prototype mode
  • Structural mode: Adapter mode, decorator mode, proxy mode, appearance mode, bridge mode, combination mode, flyweight mode
  • Behavioral patterns: : Strategy pattern, template method pattern, observer pattern, iterative sub pattern, chain of responsibility pattern, command pattern, memo pattern, state pattern, visitor pattern, mediator pattern , interpreter mode.

1. What is the singleton pattern:

Definition: means that a class has only one instance, and the class A pattern that creates this instance on its own. This can avoid the waste of memory resources caused by opening multiple task manager windows, or errors such as inconsistent display content in each window. For example, can our computer only have one task manager open? Right, this is to prevent wasted resources and other errors.

In projects, you can generally obtain the same object through singleton mode to call tool methods. The advantage of this is to save memory resources. I don’t need to create multiple different objects because this consumes memory resources

In short: A singleton is a program that has only one instance. This class is responsible for creating its own object. At the same time, it is necessary to ensure that only one object is created

Characteristics of singleton mode:

    Constructor private
  1. Holding properties of its own type
  2. Provides static methods to obtain instances to the outside world

Structure diagram of singleton mode:
Completely master the Java singleton pattern

2. Advantages and disadvantages of singleton mode:

Advantages:

    Reduces memory overhead
  1. Avoiding multiple occupation of resources
  2. Setting global access points can be optimized and access to shared resources

Disadvantages (referenced from the Internet):

    Generally there is no interface and expansion is difficult. If you want to expand, there is no other way except modifying the original code, which violates the opening and closing principle
  1. In concurrent testing, the singleton mode is not conducive to code debugging. During the debugging process, if the code in the singleton has not been executed, it cannot simulate the generation of a new object.
  2. The functional code of the singleton mode is usually written in a class. If the functional design is unreasonable, it is easy to It is easy to violate the single responsibility principle

Look at a mind map of the singleton mode:

3. Lazy mode (more commonly used)

The characteristic of lazy mode is delayed initialization. The object will not be instantiated until the method is called to obtain the instance.

It is not thread-safe. Strictly speaking, it is not a singleton mode. The advantage is that it will not be created until the instance is obtained. The object therefore saves memory overhead

Demo:

public class SingLeton {

    //1、有自己类型的属性
    private static SingLeton instance;

    //2、构造器私有化
    private SingLeton(){}

    //3、对外提供获取实例的静态方法
    public static SingLeton getInstance(){
        if (instance == null){
            instance = new SingLeton();
        }
        return instance;
    }}

Test class:

public class Test {
    public static void main(String[] args) {

        //判断是否产生的是同一个对象
        SingLeton s1 = SingLeton.getInstance();
        SingLeton s2 = SingLeton.getInstance();
        System.out.println(s1 == s2);
    }}

Output:

true

Note:

About lazy mode threads are not safe

Now we know that lazy mode threads are not safe, Then you need to use a lock (synchronized) to synchronize:

/**
 *   保证 instance 在所有线程中同步
 */public class SingLeton2 {

        //1、有自己类型的属性
        private static volatile SingLeton2 instance ;    
        
        //2、构造器私有化
        private SingLeton2() {
        }

        public static synchronized SingLeton2 getInstance() {
            //getInstance 方法前加同步
            if (instance == null) {
                instance = new SingLeton2();
            }
            return instance;
        }
    }
If you are writing multi-threading, do not delete the keywords volatile and synchronized in the above example code, otherwise there will be thread non-safety issues. If you don't delete these two keywords, you can

ensure thread safety, but synchronization is required every time you access it, which will affect performance and consume more resources. This is the shortcoming of the lazy singleton.

4. Hungry Man Mode [Recommended]

Hungry Man Mode is thread-safe and commonly used, but it is easy to generate garbage objects because Hungry Man Mode loads classes at the beginning The instance is initialized


##Demo:

/**
 *
 * 饿汉模式
 */public class SingLeton {

    //持有自己类型的属性   (和懒汉一样)
    //由于static修饰,只在类加载的时候执行一次,类加载的时候就实例化对象
    private static SingLeton instance = new SingLeton();

    //构造器私有化,不能通过它创建对象
    private SingLeton(){};

    //对外提供获取实例的静态方法
    public static SingLeton getInstance(){
        return instance;
    }}
Test class:

public class Test {
    public static void main(String[] args) {

        //判断是否产生的是同一个对象
        SingLeton s1 = SingLeton.getInstance();
        SingLeton s2 = SingLeton.getInstance();
        System.out.println(s1 == s2);
    }}
Output:

true
Comparison between lazy man mode and hungry man mode:

  1. 懒汉模式延迟加载,非线程安全,饿汉模式线程安全
  2. 懒汉模式刚运行不实例化对象,需要的时候才实例化对象,相当于来讲更节省内存开销
  3. 饿汉模式只要运行都会加载类的时候就给你初始化了,就需要使用更大的内存

图解:
Completely master the Java singleton pattern

5、单例模式的应用场景:

  1. 需要经常创建的一些类,使用单例可以降低系统的内存压力
  2. 这个类只要求生成一个对象的时候,比如每个人的名字
  3. 类创建实例时占用资源较多,或实例化耗时较长,且经常使用
  4. 频繁访问数据库或文件的对象
  5. 类需要频繁实例化,而创建的对象又频繁被销毁的时候,如多线程的线程池

6、单例模式的应用实例

这里使用懒汉式单例模式模拟产生班级的班长
分析: 在每一个学期内,班级的班长只有一人,所以适合用单例模式实现

Person类:

/**
 * 使用懒汉模式
 */public class Person {

    //保证instance在所有线程中同步
    private static volatile Person instance;

    private Person(){
        System.out.println("产生一个班长");
    }

    //加上synchronized锁
    public static synchronized Person getInstance(){
        if(instance == null){
            instance = new Person();
        }else {
            System.out.println("错误信息:已经有一个班长,不能再产生");
        }
        return instance;
    }

    public void getName(){
        System.out.println("我是班长:小强");
    }}

测试类:

public class Test {
    public static void main(String[] args) {

        Person p1 = Person.getInstance();
        p1.getName(); //输出班长名字

        Person p2 = Person.getInstance();
        p2.getName();

        if(p1 == p2){
            System.out.println("两个班长是同一个人");
        }else {
            System.out.println("两个班长是同一个人");

        }
    }}

运行结果:

产生一个班长
我是班长:小强
错误信息:已经有一个班长,不能再产生
我是班长:小强
两个班长是同一个人

小结:

这个就是单例模式,当程序已经产生一个对象后,就不会产生一个新的对象,即使有多个对象也是同一个对象而已,在使用懒汉模式的时候需要注意线程安全问题,在平时更加推荐使用饿汉模式,也需要注意资源的占用。

推荐学习:《java教程

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

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete