zoukankan      html  css  js  c++  java
  • java的单例设计模式

    单例设计模式(就是一个类在内存只存在一个对象)
    思路:
    1.将构造函数私有化
    2.在类中自己创建一个对象
    3.提供一个方法可以获取该对象 
    例:
    public class Single {
        //单例设计模式(一个类在内存只存在一个对象)
        private Single(){     //设置为私有,使之不能new出对象
        }
        private static Single s=new Single(); //自定义一个对象
        public static Single getInstance(){   //使用(类名.静态函数) 返回自己定义的那一个对象s
            return s;
        }
        
        
        
        private int age;
        public void setAge(int age){
            this.age=age;
        }
        public int getAge(){
            return age;
        }

    }





    main方法的使用
            Single s6=Single.getInstance();//通过(类名.静态函数)返回自定义的对象
            Single s2=Single.getInstance();//通过(类名.静态函数)返回自定义的对象
            s6.setAge(36);
            
            System.out.println(s2.getAge());  //打印出36,说明内存只存在一个对象
            
            System.err.println(s6);//对象的地址值是一样的
            System.out.println(s2);//对象的地址值是一样的

  • 相关阅读:
    [Everyday Mathematics]20150226
    [Everyday Mathematics]20150225
    [Everyday Mathematics]20150224
    [Everyday Mathematics]20150223
    [Everyday Mathematics]20150222
    [Everyday Mathematics]20150221
    [Everyday Mathematics]20150220
    [Everyday Mathematics]20150219
    [Everyday Mathematics]20150218
    [Everyday Mathematic]20150217
  • 原文地址:https://www.cnblogs.com/taobd/p/7044112.html
Copyright © 2011-2022 走看看