---
title: "黑马程序员-编程基础03-单例设计模式"
author: "Mrng"
date: "2012-07-27T17:47:51Z"
tags: []
categories: ["编程语言"]
slug: "03"
draft: false
lastmod: "2012-07-27T18:01:17Z"
id: 1609817
url: "https://mrng.iteye.com/blog/1609817"
---

------- [android培训](http://edu.csdn.net/heima)、[java培训](http://edu.csdn.net/heima)、期待与您交流！ ---------- 　

设计模式：解决一类问题最行之有效的方法。Java中有23种设计模式。

单例设计模式：解决一个类的实例在内存中只存在一个

1.为了避免其他程序过多创建该类实例，先禁止其他程序创建该类实例，将构造器初始化

2.还为了让其他程序可以访问到该类实例，只好在该类中自己创建一个实例

3.为了方便其他程序对该类实例的访问，还要对外提供一些访问方式，就是提供一个方法返回该类的实例

\* 饿汉式

public class Single {

    //1.将构造器私有化

    private Single() { }

    //2.自己创建实例

    private static final Single instance = new Single();

    //3.将实例提供给外部使用

    public static Single getInstance() { return instance; }

}

 

\* 懒汉式

public class Single {

    //1.将构造器私有化

    private Single() { }

    //2.自己创建实例

    private static Single instance = null;

    //3.将实例提供给外部使用

    public static synchronized Single getInstance() {

          if (instance == null) {

                synchronized(Single.class) {

                      instance = new Single();

                }

          }

          return instance; 

    }

}

\* 枚举

public enum Single {

    //1.枚举类的构造器默认私有化

    //2.自己创建实例

    instance;

    //3.将实例提供给外部使用

    public static Single getInstance() { return instance; }

}　　

------- [android培训](http://edu.csdn.net/heima)、[java培训](http://edu.csdn.net/heima)、期待与您交流！ ---------- 　　

详细请查看：[http://edu.csdn.net/heima/](http://edu.csdn.net/heima)