Singleton Design

table of Contents

Singleton Design

Singleton design is the core essence of being a JVM process has allowed only one instance of an object .

In the design of a single embodiment, a total of two types of ** "starving single embodiment," and "lazy single embodiment" **.

Example of two single difference:

1, starving single embodiment is instantiated when the final class is defined directly loaded class, it is to define the lazy formula will need to be instantiated instance operation.

2, due to the two different Singleton design pattern, style hungry man in control of resources on the less lazy type, lazy man will need to be instantiated instance, while a hungry man style in the open class loader will take up memory space.

3, hungry Chinese-style thread-safe, lazy style thread is unsafe, need to use synchronization locks to complete a single case.

4, hungry efficiency in execution of Han dominant, lazy formula needs to be locked, so the performance is better performed formula hungry man.

Example starving single design

As the hungry man, single cases of direct use of the final created a sample return is an instance of the object, so inherently thread-safe.

Example:

public class TestOne {
    public static void main(String[] args) {
        /*饿汉式单例*/
        Ball ball = Ball.getInstance();
        ball.print();
    }
}

class Ball {
    /**
     * 直接对类进行实例化
     */
    private static final Ball BALL = new Ball();

    private Ball() {
    }

    /**
     * 由于调用全部返回BALL,只生成BALL一个对象。
     * @return  返回实例化对象
     */
    public static Ball getInstance() {
        return BALL;
    }

    public void print(){
        System.out.println("饿汉式单例!!!");
    }
}


result:

饿汉式单例!!!

Design Example lazy single

Since the single idler embodiment not directly instantiated final, when the single idler embodiment a plurality of threads is instantiated design, will be a problem, it is necessary to use the reflection and synchronized method for processing .

public class TestOne {
    public static void main(String[] args) {
        /*懒汉式单例*/
        Ball ball = Ball.getInstance();
        ball.print();
    }
}

class Ball {
    /**
     * 先不直接实例化类,只定义
     */
    private static Ball ball;

    private Ball() {
    }

    /**
     * 当需要使用此类时,进行实例化操作
     * 节省资源
     *
     * @return 返回Ball实例化对象
     */
    public synchronized static Ball getInstance() {
        /*判断是不是第一次调用*/
        if (ball == null) {
            //进行实例化
            ball = new Ball();
        }
        return ball;
    }

    public void print() {
        System.out.println("懒汉式单例!!!");
    }
}

result:

懒汉式单例!!!
Published 61 original articles · won praise 0 · Views 2175

Guess you like

Origin blog.csdn.net/sabstarb/article/details/104701919