- //懒汉式和饿汉式的案例
- //单例设计时建议使用饿汉式
- class Single
- {
- private int num;
- public void setNum(int num){
- this.num=num;
- }
- public int getNum(){
- return this.num;
- }
- /* Single(){}
- private static Single s =new Single();
- public static Single getInstance(){
- return s;
- }*/// 饿汉式: Single类进内存时,对象已经创建好
- private Single(){}
- private static Single s=null;
- public static Single getInstance(){
- //if(s==null){
- // synchronized(Single.class)//给对象上锁
- if(s==null)
- s=new Single();
- return s ;
- }
- // }懒汉式:对象是方法被调用时才初始化,
- // 也叫做对象的延时加载,Single类进内存时对象还没有存在,只有调用了getInstance方法时才建立对象
- }
- class SingleDemo
- {
- public static void main(String[] args) {
- Single s1=Single.getInstance();
- Single s2=Single.getInstance();
- // Single s1=new Single();
- // Single s2=new Single();
- s1.setNum(30);
- System.out.println(s2.getNum());
- }
- }
复制代码 |
|