zoukankan      html  css  js  c++  java
  • Singleton: this & instance

    public class Singleton{
        private static final Singleton instance = new Singleton();
        private String name;
        private int age;
        private Singleton(){}
        public static Singleton getInstance(){
            return instance;
        }
    
        public void instanceSetter(String name, int age){
            instance.name = name;
            instance.age = age;
        }
    
        public void thisSetter(String name, int age){
            this.name = name;
            this.age = age;
        }
    
        public void instanceGetter(){
            System.out.println("instance.name: " + instance.name);
            System.out.println("instance.age: " + instance.age);
        }
    
        public void thisGetter(){
            System.out.println("this.name: " + this.name);
            System.out.println("this.age: " + this.age);
        }
    
        public static void main(String[] args){
            Singleton s = Singleton.getInstance();
            System.out.println(s);
    
            System.out.println("Before setter()");
            s.instanceGetter();    //null, 0
            s.thisGetter();    //null, 0
            System.out.println();
    
            s.instanceSetter("lxw", 26);
    
            System.out.println("After intanceSetter()");
            s.instanceGetter();    //lxw, 26
            s.thisGetter();    //lxw, 26
            System.out.println();
    
            s.thisSetter("wxl", 29);
    
            System.out.println("After thisSetter()");
            s.instanceGetter();    //wxl, 29
            s.thisGetter();    //wxl, 29
        }
    }

    Output:

    lxw@lxw:14:26:52:~$ java Singleton 
    Singleton@15db9742
    Before setter()
    instance.name: null
    instance.age: 0
    this.name: null
    this.age: 0
    
    After intanceSetter()
    instance.name: lxw
    instance.age: 26
    this.name: lxw
    this.age: 26
    
    After thisSetter()
    instance.name: wxl
    instance.age: 29
    this.name: wxl
    this.age: 29
  • 相关阅读:
    docker常用命令
    docker安装注意事项
    DataGridView中实现自动编号
    Flask设置配置文件
    python路径找类并获取静态字段
    JavaScript数据类型
    php学习笔记6
    php学习笔记5
    php学习笔记4
    php学习笔记3
  • 原文地址:https://www.cnblogs.com/lxw0109/p/SingletonThisInstance.html
Copyright © 2011-2022 走看看