File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Composition

 
Jawad Kakar
Ranch Hand
Posts: 82
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 Ec
Ranch Hand
Posts: 46
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it will work ok the way you want it but that's a typical implementation of a singleton, not a composition
 
Pete Lyons
Ranch Hand
Posts: 109
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 82
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Pete, when I wrote it I guess I did not look at it carefully.
Thank you
Jawad
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic