我应该在这里使用全局变量吗? [英] Should I use global variables here?

查看:80
本文介绍了我应该在这里使用全局变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么使用全局变量是一个坏主意?



我想为所有要使用的类创建一个变量数组。它会存储关键状态,所以它不能被设置为const(final)。

你能告诉我一些其他(适当的)如何做到这一点的方法吗?

解决方案


为什么使用全局变量不好?


因为它破坏了封装。所有代码都可以访问它们并修改它们。

lockquote

我想让所有类都可以使用的变量数组$ <$> b $ b

如果您的所有代码只有一个实例可用,则可以使用单例:

  public class MyGlobalKeys {
private static final MyGlobalKeys globals = new MyGlobalKeys();

//在此类以外禁用构建
private MyGlobalKeys(){}
$ b $ public void getInstance(){
return globals;

$ b $ public void addKey(String key,bool state){...}
public bool hasKey(String key){...}
//等等...
}

请注意,此示例特别不是线程安全的 - 为了改进实现方法,请参阅 Java Singleton设计模式


Why is it a bad idea to use global variables?

I want to make an array of variables available for all of the classes to use. It will store key states, so it can't be set as const (final).

Could you show me some other (proper) way of how to do this?

解决方案

Why is it bad idea to use global variables?

Because it breaks encapsulation. All code can access them and modify them.

I want to make array of variables avaiable for all the classes to use

If there is only one instance to be used by all your code, you can use a singleton:

public class MyGlobalKeys {
    private static final MyGlobalKeys globals = new MyGlobalKeys();

    // disable construction outside of this class
    private MyGlobalKeys() {}

    public void getInstance() {
       return globals;
    }

    public void addKey(String key, bool state) { ... }
    public bool hasKey(String key) { ... }
    // and so on ...
}

Note that this sample is particularly not thread-safe - for improved implementation approaches, see Java Singleton Design Pattern

这篇关于我应该在这里使用全局变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆