public class Persion1 {
public static Persion1 persion=new Persion1();
/**
* 饿汉式单例
*/
public static Persion1 getInstance()
{
return persion;
}
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
[code]package Singleton;
public class Persion2 {
public static Persion2 persion;
/**
* 懒汉式单例
*/
public synchronized static Persion2 getInstance()
{
if(persion==null)
{
persion=new Persion2();
}
return persion;
}
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
[code]package Singleton;
public class Persion3 {
public static Persion3 persion;
/**
* 双重检查单例
*/
public static Persion3 getInstance()
{
if(persion==null)
{
synchronized (Persion3.class) {
if(persion==null)
{
persion=new Persion3();
}
}
}
return persion;
}
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}