Query about simulating global variables in java

前端 未结 2 866
孤独总比滥情好
孤独总比滥情好 2021-01-07 15:45

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.

相关标签:
2条回答
  • 2021-01-07 16:11

    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 = ...
    }
    
    0 讨论(0)
  • 2021-01-07 16:24

    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.

    0 讨论(0)
提交回复
热议问题