java设计模式总结之单例模式

来源:互联网 发布:淘宝拒收怎么申请退款 编辑:程序博客网 时间:2024/06/06 07:26

java设计模式之单例模式

单例模式有两种,一种饿汉式,一种懒汉式。

相同点
无论饿汉式还是懒汉式,都需要:
1.私有化构造
2.私有化的静态成员变量,变量名同类名
3.提供实例的静态方法

不同点

饿汉式:
直接返回一个已实例化的对象。
多线程下,有可能被实例化多次。

懒汉式:
如果未被实例化过,则实例化后返回。否则直接返回已实例化的对象。
需要加锁。只被实例化一次。

饿汉式

public class SingletonHungry {    private static SingletonHungry singletonHungry = new SingletonHungry();    private SingletonHungry() {}    public static SingletonHungry getInstance() {        return singletonHungry;    }     }

懒汉式

package com.singleton;public class SingletonLazy {    private static SingletonLazy singletonLazy;    private SingletonLazy() {}    public synchronized static SingletonLazy getInstance() {        if(singletonLazy == null) {            singletonLazy = new SingletonLazy();        }        return singletonLazy;    }}