单例设计模式是一种创建对象的方式。在单例模式中,构造方法被私有化,不可以通过new来创建对象,这样做可以使得类的安全性得到提高和资源利用率提高。并且在对象的生命周期中,始终在堆内存中保持一个对象实例,而不断新创建的对象指向唯一一个堆内存空间。
以下有6种创建单例的方式,每个方法均有其特点。
public class Singleton1 {
private Singleton1(){}
public static Singleton1 getInstance(){
return new Singleton1();
}
public void print(){
System.out.println("i am Singleton1");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Singleton1.getInstance().print();
}
}
线程不安全,并且没有判断实例是否存在。
public class Singleton2 {
private static Singleton2 instance;
private Singleton2(){}
public static Singleton2 getInstance(){
instance = new Singleton2();
return instance;
}
public void print(){
System.out.println("i am Singleton2");
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Singleton2.getInstance().print();
}
}
线程不安全
public class Singleton3 {
private static Singleton3 instance;
private Singleton3(){}
public static Singleton3 getInstance(){
if(instance == null){
instance = new Singleton3();
}
return instance;
}
public void print(){
System.out.println("i am Singleton3");
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Singleton3.getInstance().print();
}
}
线程安全,但是高并发时候性能不好。
public class Singleton4 {
private static Singleton4 instance;
private Singleton4(){}
public static synchronized Singleton4 getInstance(){
if(instance == null){
instance = new Singleton4();
}
return instance;
}
public void print(){
System.out.println("i am Singleton4");
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Singleton4.getInstance().print();
}
}
线程安全,性能又好。
public class Singleton5 {
private static Singleton5 instance;
private static byte[] lock = new byte[0];
private Singleton5(){}
public static Singleton5 getInstance(){
if(instance == null){
synchronized(lock){
if(instance == null){
instance = new Singleton5();
}
}
}
return instance;
}
public void print(){
System.out.println("i am Singleton5");
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Singleton5.getInstance().print();
}
}
线程安全,性能又好。
public class Singleton6 {
private static Singleton6 instance;
private static ReentrantLock lock = new ReentrantLock();
private Singleton6(){}
public static Singleton6 getInstance(){
if(instance == null){
lock.lock();
if(instance == null){
instance = new Singleton6();
}
lock.unlock();
}
return instance;
}
public void print(){
System.out.println("i am Singleton6");
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Singleton6.getInstance().print();
}
}
在windows操作系统中,回收站本身也是一个单例对象。在每个盘中,均有回收站对象引用,并且指向同一个回收站。只不过均隐藏起来了。
原文地址:http://thinklili.blog.51cto.com/10867130/1753225