Query about simulating global variables in java

2019-02-16 03:47发布

问题:

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.

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

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();
        }
}

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.

回答1:

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 = ...
}


回答2:

You do no have to instantiate Global to access its static members. Static members are accessed by class name without object at all. So your approach is reasonable.

There are the following common practices to deal with "global" objects.

  1. Static members (almost your approach)
  2. Singleton pattern
  3. Thread local.

If I were you I'd make DBAccess singleton, so you will be able to access Database the anywere: DBAccess.getInstance().find("the query")

BTW, take a look in tools that already implemented DB access layer. For example iBatis, Hibernate, JPA.



标签: java global