Android单例模式

看到一段单例模式的代码,觉得挺有意思,如下:

public abstract class Singleton {    private T mInstance;    protected abstract T create();    public final T get() {        synchronized (this) {            if (mInstance == null) {                mInstance = create();            }            return mInstance;        }    }}

这是单例模式的抽象类,所有单例都需要写这么一坨东西,所以干脆就将其抽象并泛型化,当需要使用单例的时候这么做,先在一个单例管理类中声明单例:

public class SingletonManager {    public static final Singleton STUDENT_INSTANCE = new Singleton() {        @Override        protected Student create() {            // TODO Auto-generated method stub            return new Student("hello student");        }    };    public static final Singleton TEACHER_INSTANCE = new Singleton() {        @Override        protected Teacher create() {            // TODO Auto-generated method stub            return new Teacher("hello teacher");        }    };}

使用单例的时候如下:

public class Main {    public static void main(String[] args) {        // TODO Auto-generated method stub        Student student = SingletonManager.STUDENT_INSTANCE.get();        System.out.println(student.name);        Teacher teacher = SingletonManager.TEACHER_INSTANCE.get();        System.out.println(teacher.name);    }}