查询在java中模拟全局变量 [英] Query about simulating global variables in java

查看:126
本文介绍了查询在java中模拟全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我想这对大多数人来说都是微不足道的。但是,这里是 -
我有一个连接到数据库以读取特定信息的应用程序。现在,这个读取在每个请求的基础上在应用程序的许多类中发生。 所以我想将每个请求的数据库连接数限制为1 。所以这就是我所做的。

I have a question and i suppose this is trivial for most around here. However, here goes -- I have an application that connects to a database to read specific information. Now this read happens across many classes in the application on a per request basis. So i wanted to restrict the number of connections to the database to 1 per request. So this is what i did.

假设我有一个数据库访问类,DBAccess获取2个字符串,a& b。

Assuming that i had a database access class, DBAccess that fetches 2 strings, a & b.

我写了一个类Global,如下所示 -

I wrote a class Global that goes as follows --

    public class Global {
        static String a;
        static String b;

        public Global(DBAccessInput input) throws Exception {
            super();
            DBAccess dbtool= new DBAccess(input);
            a=dbtool.getA();
            b=dbtool.getB();
        }
}

所以现在我可以继续访问& b作为Global.a和Global.b在整个应用程序的其他类中。但这对我来说似乎是错误的,因为要填充一个& b我需要实例化Global的一个对象然后我会回到访问& b为Global.a,b为b。我可以把Global构造函数中的所有东西都放到一个静态块中但是仍然没有帮助,因为我仍然需要实例化Global的一个对象以将'input'传递给DBAccess。

So now i can go ahead and access a & b as Global.a and Global.b in other classes across the app. But this to me seems wrong because to populate a & b i would need to instantiate an object of Global and then i will fall back to accessing a & b as Global.a and likewise for b. I could put all of the stuff that is within the Global constructor into a static block but that still wouldnt help as i would still need to instantiate an object of Global to pass off 'input' to DBAccess.

任何正确方向的帮助或指示都会有很大的帮助。

Any help or pointers in the right direction would be of great help.

推荐答案

你可以实例化那些静态方法中的静态变量,而不是构造函数
但这不是一个好的样式:

You can instantiate those static variables in static method of global, instead of constructor But this is not a good style:

static initialize(DBAccessInput input) {
     a = ...
     b = ...
}

这篇关于查询在java中模拟全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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