• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why make a Globally shared instance of a Class ?

 
justin smythhe
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What are the benefits ? What are the disadvantages ?
 
Greg Brannon
Bartender
Posts: 563
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is this a homework essay question?

Either way, can you explain what "globally shared" means, give an example, and explain why you think having such a class might be useful?
 
justin smythhe
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greg Brannon wrote:Is this a homework essay question?
Either way, can you explain what "globally shared" means, give an example, and explain why you think having such a class might be useful?


Not a homework question. It came up when I was peeking at some non-java 1.6 api classes.
It can save memory if a lot of other objects use it. I can't think of any other reasons.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65216
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you mean a Singleton?
 
Greg Brannon
Bartender
Posts: 563
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which "non-java 1.6 api classes?"
 
justin smythhe
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bear Bibeault wrote:Do you mean a Singleton?

No, no the singleton pattern. I mean something like this :

private static final MyClass forEveryoneToUse = new MyClass();

....more code here.
 
justin smythhe
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greg Brannon wrote:Which "non-java 1.6 api classes?"


Why do you ask this question ?
 
Bill Gorder
Bartender
Posts: 1682
7
Android IntelliJ IDE Linux Mac OS X Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One well established idiom for this is Logger declaration



Globally shared is probably a poor description for this as your example you posted is actually private.

Consider the modifiers one at a time

private - only available to this class
final - can not be reassigned
static - Only one reference per class

Advantages?

1. less CPU overhead: loggers are retrieved and assigned only once, at hosting class initialization
2. less memory overhead: logger declaration will consume one reference per class

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic