Java_Singleton Mode Hungry Man Style and Lazy Man Style

Tip: To get started with the singleton design pattern, it is best for students to assign my code here to their own development environment, and then follow my instructions to practice step by step.


1. What is the singleton design pattern?

In the entire system, there can only be one object instance for a certain class, and this class only provides one method to obtain its object instance

Two, two singleton design patterns

1. Hungry Chinese style

The code is as follows (example):

public class SingleTon01 {
    public static void main(String[] args) {
        //System.out.println(Animal.n1);
        System.out.println(Animal.getInstance());
    }
}
class Animal{
    private String name;
    public static int n1 = 888;
    private static Animal dog = new Animal("dog");//2,在类的内部new一个对象

    //分析:这里为什么要用static,因为我们的构造器私有化了,我们在main中new不出对象,又因为
    //我们创建的该对象用了private,所以,我们即使用类名来调用也无济于事,我们需要写一个公共
    // 方法getInstance()来获得该对象。所以此getInstance()方法也要用static,又因为静态方法
    //必须调用静态成员,所以我们这里的static必须加上
    private Animal(String name) {//1,构造器私有化
        System.out.println("构造器被调用");
        this.name = name;
    }
    public static Animal getInstance(){//3,提供一个static方法,返回dog
        return dog;
    }

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

 The running results are as follows (example):

The constructor is called
Animal{name='dog'}

The constructor is called // put System.out.println(Animal.n1); open
888
Animal{name='dog'}

 analyze:

No matter whether we use the Animal.n1() statement or not, our constructor is always called because we have created new objects in the Animal class. So our dog, no matter whether we adjust the getInstance() method or not, we can get the object. Of course, we can getInstance() again to return their addresses. Everyone can debug it by themselves, it is definitely the same address.

 2. Lazy style

The code is as follows (example):

public class SingleTon02 {
    public static void main(String[] args) {
        System.out.println(Cat.n2);
        System.out.println(Cat.getInstance());
        System.out.println(Cat.getInstance());
        System.out.println(new Dog("大黄"));
        System.out.println(new Dog("大黄"));
    }
}
class Cat{
    private String name;
    public static int n2 = 999;
    private static Cat cat; //2,给一个static静态属性对象

    private Cat(String name) {//1,构造器私有化
        //这条语句在单独使用Cat,n2方法时是不会被调用的
        //System.out.println("构造器被调用");
        this.name = name;
    }
    public static Cat getInstance(){//3,提供一个public的static的方法来返回我们的Cat对象
        if (cat == null){
            cat = new Cat("小白");
        }
        return cat;
    }
}
class Dog{
    private String name;

    public Dog(String name) {
        this.name = name;
    }
}

  The running results are as follows (example):

The first case: it is the result of running the above code

999
review.SingTon.Cat@4b67cf4d 
review.SingTon.Cat@4b67cf4d
review.SingTon.Dog@7ea987ac
review.SingTon.Dog@12a3a380

The second case: this is to run only System.out.println(Cat.n2); turn off all System.out.println() at the bottom of main. And turn on the shield System.out.println ("constructor was called").

999

 Analysis: You can execute the Cat.n2 statement separately (shield the bottom statement). After execution, you can find that the constructor is not called. The reason is that we only defined cat in the Cat class, and there is no new object, so the constructor does not will be executed. But we open the prompt statement in the constructor and call the getInstance() method to get two objects with the same address, indicating that these two are one object. Finally, we wrote an ordinary Dog() class, and new objects, and found that the addresses of the two are different. This verifies that the singleton mode we mentioned has only unique objects.

Summarize

Hungry Chinese style : 1. Privateize the constructor; 2. Create an object directly inside the class (the object is static); 3. Provide a public static method and return the corresponding object. Why is it called Hungry Chinese style? It is possible that this object has already been created, but we haven’t come to use it yet. This mode will cause waste of resources.

Lazy style : 1. Privateize the constructor; 2. Define a static static attribute object; 3. Provide a public static method that can return a cat object. The reason why it is called Hungry Chinese style is that we do not call this method, we do not actually create objects in memory, we can verify this through the above example

Guess you like

Origin blog.csdn.net/ming2060/article/details/127802557