• 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
  • 相关阅读:
    simple-LDAP-auth
    User Attributes
    webpack 模块标识符(Module Identifiers)
    详解webpack中的hash、chunkhash、contenthash区别
    [转] 插件兼容CommonJS, AMD, CMD 和 原生 JS
    Exif.js 读取图像的元数据
    [转] 跨域
    [转] 理解Web路由
    [转] React 是什么
    [转] Web MVC简介
  • 原文地址:https://www.cnblogs.com/lxw0109/p/SingletonThisInstance.html
Copyright © 2020-2023  润新知