Single column mode [Hungry Man Style and Lazy Man Style]

Single column mode [Hungry Man Style and Lazy Man Style]

The singleton pattern is a class that only provides one object and a method to obtain this object.

There are two types of singleton patterns:

  • Hungry Chinese style
  • lazy man style

1. Hungry Chinese style

  1. private constructor
  2. Create object inside class
  3. Provides a static method to access objects of this class.
package com.linghu.single;

/**
 * 饿汉式
 * @author 令狐荣豪
 * @version 1.0
 */
public class SingleTon01 {
    
    
    public static void main(String[] args) {
    
    
//        Girlfriend instance = Girlfriend.getInstance();
//        System.out.println(instance);
        //饿汉式
        System.out.println(Girlfriend.n);//访问静态属性时,类的对象还是会被初始化创建,这就浪费了!
    }
}

class Girlfriend{
    
    
    private String name;
    public static int n=100;
    private static Girlfriend gf=new Girlfriend("小红");

    private Girlfriend(String name) {
    
    
        System.out.println("构造器。。。");
        this.name = name;
    }

    public static Girlfriend getInstance(){
    
    
        return gf;
    }

    @Override
    public String toString() {
    
    
        return "Girlfriend{" +
                "name='" + name + '\'' +
                '}';
    }
}

2. Lazy man style

package com.linghu.single;

/**
 * 懒汉式
 * @author 令狐荣豪
 * @version 1.0
 */
public class SingleTon02 {
    
    
    public static void main(String[] args) {
    
    
        //访问静态属性的时候,对象不会被创建,不会浪费,需要的时候才会初始化创建对象
        System.out.println(Cat.n);
//        Cat instance = Cat.getInstance();
//        System.out.println(instance);
    }
}

class Cat{
    
    
    private String name;
   public static int n=100;
    private static Cat cat;


    private Cat(String name) {
    
    
        System.out.println("构造器调用...");
        this.name = name;
    }

    public static Cat getInstance(){
    
    
        if (cat==null){
    
    
            cat=new Cat("喵喵");
        }
        return cat;
    }

    @Override
    public String toString() {
    
    
        return "Cat{" +
                "name='" + name + '\'' +
                '}';
    }
}

3. Summary

The timing of creating objects in Hungry style and Lazy style is different. Hungry style is created when the class is loaded, while Lazy style is created when it is used.

Guess you like

Origin blog.csdn.net/weixin_43891901/article/details/131206430