Original link: blog.csdn.net/weixin\_495…

The singleton design pattern in Java

In terms of design patterns, this is a separate thing. It doesn’t belong in Java, but it’s used a lot in Java, so today I’m going to introduce you to the hungry guy and the lazy guy in the single-example design pattern. First, let me explain what the singleton design pattern is (if you don’t want to know, you can go straight to hungry and lazy) : The singleton design pattern for classes is a way to ensure that only one object instance of a class can exist in the entire software system. (Don’t understand it doesn’t matter, can use it)

Hungry

Hungry han style: can be understood as hungry not, on the advance to eat tools ready (new object), and then “eat” operation. To speak in code:

class Family{ private int number; private String name; Private static Family Instance=new Family(); Public static Family getInstance(){return Instance; } // provide public static methods that return objects. } public class Test3 { public static void main(String[] args) { Family family1=Family.getInstance(); Family family2=Family.getInstance(); }}Copy the code

Two. Slacker style

Slacker: This person is understandably lazy, he just washes the dishes but doesn’t prepare them, and he will use his new object whenever he wants to eat. To speak in code:

class lazy { private lazy(){ } private static lazy Instance = null; Public static lazy getInstance(){if (Instance==null){Instance=new lazy(); } return Instance; } } public class Test32 { public static void main(String[] args) { lazy lazy1=lazy.getInstance(); }}Copy the code

What’s the difference between a hungry man and a lazy man

For hungry: Advantage: thread thief safety Disadvantage: long object loading time For lazy: Advantage: delayed object creation, faster disadvantage: low multithreaded security, but can be optimized to make it usable.

Original link: blog.csdn.net/weixin\_495…