单例(一)

从最简单的单例开始:

package com.garinzhang.designpattern;

public class SimpleSingleton {
    private static SimpleSingleton instance = null;
    private SimpleSingleton() {}
    public static SimpleSingleton getInstance() {
        if(instance == null) {
            instance = new SimpleSingleton();
        }
        return instance;
    }
    public void printOut() {
        System.out.println("instance created!");
    }
}

以上例子有两个问题:

1. 通过JAVA里的反射可以产生构造函数为private的类的实例,看如下代码(这种方式可以让所有单例失效):

package com.garinzhang.designpattern;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class GetSimpleSingletonInstanceByReflection {
    static List<SimpleSingleton> list = new ArrayList<SimpleSingleton>();
    
    @SuppressWarnings("unchecked")
    public static SimpleSingleton getInstance() {
        Constructor<SimpleSingleton>[] constructors = null;
        try {
            constructors = (Constructor<SimpleSingleton>[]) Class.forName("com.garinzhang.designpattern.SimpleSingleton").getDeclaredConstructors();
        } catch(ClassNotFoundException e) {
            e.printStackTrace();
        }
        Constructor<SimpleSingleton> con = constructors[0];
        con.setAccessible(true);
        SimpleSingleton ss = null;
        try {
            ss = con.newInstance();
        } catch(IllegalArgumentException e) {
            e.printStackTrace();
        } catch(InvocationTargetException e) {
            e.printStackTrace();
        } catch(IllegalAccessException e) {
            e.printStackTrace();
        } catch(InstantiationException e) {
            e.printStackTrace();
        }
        return ss;
    }
    public static void main(String[] args) {
        SimpleSingleton ss = getInstance();
        System.out.println(ss instanceof SimpleSingleton);
        ss.printOut();
    }
}

 2. 不是线程安全的。线程安全的定义:如果你的代码所在的进程中有多个线程在同时运行,而这些线程可能会同时运行这段代码。如果每次运行结果和单线程运行的结果是一样的,而且其他的变量的值也和预期的是一样的,就是线程安全的;

package com.garinzhang.designpattern;

public class ThreadSafeSimpleSingleton {
    private static ThreadSafeSimpleSingleton instance = null;
    private ThreadSafeSimpleSingleton() {}
    public synchronized static ThreadSafeSimpleSingleton getInstance() {
        if(instance == null) {
            instance = new ThreadSafeSimpleSingleton();
        }
        return instance;
    }
}

GOF里的单例:

饿汉式单例类、懒汉式单例类、登记式单例类(http://www.cnblogs.com/whgw/archive/2011/10/05/2199535.html)

posted @ 2013-04-01 18:06  我是小菜鸟  阅读(196)  评论(0编辑  收藏  举报