[code]package Singleton;
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;
}
}
[code]package Singleton;
public class SingletonT {
/**测试方法
* @param args
*/
public static void main(String[] args) {
// 饿汉式单例
Persion1 p1=Persion1.getInstance();
Persion1 p2=Persion1.getInstance();
p1.setAge(12);
p2.setAge(14);
System.out.println("p1 :"+p1.getAge()+",p2 :"+p2.getAge());
// 懒汉式单例类
Persion2 p3=Persion2.getInstance();
Persion2 p4=Persion2.getInstance();
p3.setAge(15);
p4.setAge(17);
System.out.println("p3 :"+p3.getAge()+",p4 :"+p4.getAge());
// 双重检查单例
Persion3 p5=Persion3.getInstance();
Persion3 p6=Persion3.getInstance();
p5.setAge(18);
p6.setAge(20);
System.out.println("p5 :"+p5.getAge()+",p6 :"+p6.getAge());
}
}
运行结果:
p1 :14,p2 :14
p3 :17,p4 :17
p5 :20,p6 :20 |
|