单例模式

package com.demo;

public class Demo01 {
    public static void main(String[] args) {
        /*
         * java设计模式:在处理某些情况下一种约定俗成,并且行之有效的方法
         *  23种设计模式  单例设计模式 装饰者设计模式  
         *   
         *   单例设计模式:主要是为了解决在计算机内存中某个类只存在一个对象的这种情况
         */
        
         //Single s1 = new Single();
         Single2 s1 = Single2.getInstances();
         s1.setAge(20);
        
        // Single s2 = new Single();
         Single2 s2 = Single2.getInstances();
         s2.setAge(20);
        
         if(s1==s2){
             System.out.println("是同一个对象");
         }else{
             System.out.println("不是同一个对象");
         }
        
    }
    
}
    //饿汉式单例模式
    class Single {
        
        private int age;

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        //1.将构造函数设为私有化    避免在外部调用实例化对象
        private  Single(int age) {
            super();
            
        }
        
        public Single() {
            // TODO Auto-generated constructor stub
        }

        //2.在本类里面提供一个对象
        private  static Single s = new Single();
        
        //3.对外提供公共的方法
        public static Single getInstances(){
            return s;
        }       
}
    
    //懒汉式单例模式
  class Single2{
       private int age;

            public int getAge() {
                return age;
            }

            public void setAge(int age) {
                this.age = age;
            }
            
            //1.将构造函数设为私有化    避免在外部调用实例化对象
            private  Single2(int age) {
                super();
                
            }
            
            public Single2() {
                // TODO Auto-generated constructor stub
            }

            //2在本类中提供一个对象
            private static Single2 s =null;
            
            //3.对外提供公共的方法  synchronized线程锁
            public synchronized static Single2 getInstances(){
                if(s == null){
                    s= new Single2();
                }
                return s;
            }  
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值