1. 程式人生 > >2、單例模式(內部類的實現方式)

2、單例模式(內部類的實現方式)

package demo;
/**
 * Created by sunyifeng on 17/10/19.
 */
public class MyObject {
    // 內部類
private static class MyObjectHandler{
        private static MyObject myObject = new MyObject();
};
    public MyObject() {
        // do noting
}

    public static MyObject getInstance() {
        return MyObjectHandler.myObject
; } }
package demo;
/**
 * Created by sunyifeng on 17/10/19.
 */
public class MyThread extends Thread {
    @Override
public void run() {
        super.run();
System.out.println(MyObject.getInstance());
}
}
package demo;
/**
 * Created by sunyifeng on 17/10/19.
 */
public class Run {
    public static void 
main(String[] args) { MyThread thread1 = new MyThread(); MyThread thread2 = new MyThread(); MyThread thread3 = new MyThread(); thread1.start(); thread2.start(); thread3.start(); } }
執行結果:

[email protected]
[email protected]
[email protected]

程式分析:

1、定義一個靜態內部類,在裡面建立例項;通過靜態的getInstance()方法返回單例。

2、多個執行緒取到的是同一例項。