首页 > 其他 > 详细

设计模式-单例模式(Singleton)

时间:2015-01-04 10:12:52      阅读:252      评论:0      收藏:0      [点我收藏+]

恶汉式

package cn.foxeye.design.singleton;
 
public class Singleton {
 
    private static Singleton instance = new Singleton();
 
    public Singleton() {
    }
 
    public static Singleton getInstance() {
        return instance;
    }
 
}

懒汉式

package cn.foxeye.design.singleton;
 
public class Singleton2 {
 
    private static Singleton2 instance = null;
 
    private Singleton2() {
    }
 
    public static synchronized Singleton2 getInstance() {
        if (instance == null) {
            instance = new Singleton2();
        }
        return instance;
    }
}

双重检查加锁

package cn.foxeye.design.singleton;
 
public class Singleton3 {
     
    private static Singleton3 instance = null;
     
    private Singleton3() {
    }
     
    public static Singleton3 getInstance() {
        if(instance == null) {
            synchronized (Singleton3.class) {
                if(instance == null) {
                    instance = new Singleton3();
                }
            }
        }
        return instance;
    }
 
}

Lazy initialization holder class模式

package cn.foxeye.design.singleton;
 
public class Singleton4 {
 
    private Singleton4() {
    }
 
    private static class SingletonHolder {
        private static Singleton4 instance = new Singleton4();
    }
 
    public static Singleton4 getInstance() {
        return SingletonHolder.instance;
    }
 
}

枚举式

package cn.foxeye.design.singleton;
 
public enum Singleton5 {
    uniqueInstance;
 
    private String name;
    private String sex;
    private String address;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getSex() {
        return sex;
    }
 
    public void setSex(String sex) {
        this.sex = sex;
    }
 
    public String getAddress() {
        return address;
    }
 
    public void setAddress(String address) {
        this.address = address;
    }
 
}


设计模式-单例模式(Singleton)

原文:http://my.oschina.net/u/1995545/blog/363378

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!