package com.be.six;
/**
* 开发一般用饿汉式,因为安全,简单
* @author zjw
*
*/
public class Singlton {
public static void main(String args[]){
//饿汉式用法
Singleton s=Singleton.getInstance();
s.setName("ffffffffffff");
s.setName("fffffddddddddddd");
s.test();
//懒汉式用法
Singleton1 s1=Singleton1.getInstance();
s1.setAge(33);
s1.getAge();
Singleton1 s2=Singleton1.getInstance();
s1.setAge(66);
s1.getAge();
}
}
/**
* 饿汉式
* Singleton一进内存,就已经创建好了对象
* @author zjw
*
*/
class Singleton{
private String name;
private Singleton(){}
private static Singleton s=new Singleton();
public static Singleton getInstance(){
return s;
}
public void test(){
System.out.println("name:"+name);
}
public void setName(String name){
this.name=name;
this.test();
}
}
/**
* 懒汉式
* Singleton1进内存,对象还没存在,只有调用了getInstance方法时,才建立对象,这就是延迟加载
* 缺点:
* 容易出错,
* 解决方案1,加同步关键字:Synchronized,但是加完后,程序执行效率会降低的很多
* 最终解决方案
*/
class Singleton1{
private int age;
private Singleton1(){}
private static Singleton1 s=null;
public static Singleton1 getInstance(){
if(null==s){
synchronized(Singleton1.class){//加锁 这是最终解决方案,双重判断,提高效率
if(null==s){
s=new Singleton1();
}
}
}
return s;
}
public int getAge(){
System.out.println("age:"+age);
return age;
}
public void setAge(int age){
this.age=age;
}
}