| Author |
Composition
|
Jawad Kakar
Ranch Hand
Joined: Oct 06, 2002
Posts: 82
|
|
Dear friends, I want to have a single instance of "Data class" in my application, Can I use composition in the following way to achieve my goal, or there is a better way to do this. public class DatabaseAccess{ private static Data instance = null ; private DatabaseAccess(){} public static Data getDbInstance() throws IOException{ if(instance == null){ return new Data("db.db"); } else{ return instance; } } }// end of Class and this is the way I call it. Data data = DataBaseAccess.getDbInstance(); Thank you in advance
|
 |
Juan Katabasis
Ranch Hand
Joined: Jun 20, 2001
Posts: 46
|
|
|
it will work ok the way you want it but that's a typical implementation of a singleton, not a composition
|
Regards<br />J.
|
 |
Pete Lyons
Ranch Hand
Joined: Aug 18, 2002
Posts: 109
|
|
Originally posted by Jawad Kakar: public class DatabaseAccess{ private static Data instance = null ; private DatabaseAccess(){} public static Data getDbInstance() throws IOException{ if(instance == null){ return new Data("db.db"); } else{ return instance; } } }
Jawad, This code is flawed. You should change the first part of the if clause to be: if(instance == null) { instance = new Data("db.db"); return instance; } otherwise, you will ALWAYS be getting a new instance, when you want only 1 instance. Depending on what kind of exception handling you want to do, you could also just initialize the instance iVar when you declare it like: private static Data instance = new Data("db.db"); or use the elusive "static initializer block". Either of these would eliminate the need for the null check, but might complicate your handling of errors reading/loading the file. Pete
|
 |
Jawad Kakar
Ranch Hand
Joined: Oct 06, 2002
Posts: 82
|
|
Thank you Pete, when I wrote it I guess I did not look at it carefully. Thank you Jawad
|
 |
 |
|
|
subject: Composition
|
|
|