---
title: "java利用class的load机制实现单例模式"
author: "haiker"
date: "2012-10-23T16:43:50Z"
tags: ["Java", "singleton"]
categories: ["编程语言"]
slug: "java-class-load"
draft: false
lastmod: "2012-10-23T16:43:50Z"
id: 1703825
url: "https://haiker.iteye.com/blog/1703825"
---

先上代码

```
public class Singleton {

    private static Singleton instance = null;

    public static Singleton getInstance() {
        if(instance == null) {
            instance = SingletonLazy.lazy;
        }
        return instance;
    }

    private static class SingletonLazy {
        public static Singleton lazy = new Singleton();
    }

}
```

 

classloader首先会加载Singleton.class文件，运行到if(instance==null)这句的时候，如果为空，回去加载SingletoneLazy.class。如此便实现了lazy初始化。