Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (491)
Games in Android Showcase (112)
games submitted by our members
Games in WIP (556)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Singleton vs. class with only static methods  (Read 11943 times)
0 Members and 2 Guests are viewing this topic.
Offline erikd

JGO Ninja


Medals: 16
Projects: 4
Exp: 14 years


Maximumisness


« Posted 2003-10-22 06:52:56 »

Hi there,

Having read about the Singleton, I'm wondering: Why a Singleton with the private constructor stuff and all? Isn't it easier to create a class with static methods and a static initializer, something for example like:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
public class Test {
  private static String value;

  static {
    value = "test";
  }
 
  public static String getValue() {
    return value;
  }
}


Isn't that easier than the java singleton stuff?
What great advantage about the singleton am I missing?

Greetings,
Erik

Offline Markus_Persson

JGO Wizard


Medals: 14
Projects: 19


Mojang Specifications


« Reply #1 - Posted 2003-10-22 07:13:15 »

singletons are just "prettier", as it's basically just a class with no public constructor and a public factory method.
You can even hide the fact it is a singleton from the user of the class.. only the class itself needs to know how it works. That means you can refactor it into a non-singleton class in the future without having to break other code.


/ Markus "Wishing all constructors were private" Persson
Wink

Play Minecraft!
Offline erikd

JGO Ninja


Medals: 16
Projects: 4
Exp: 14 years


Maximumisness


« Reply #2 - Posted 2003-10-22 07:29:45 »

I don't think a private constructor is that pretty  :-/
Creating a static class instead of forced single instance  seems more natural to me.

When you have to refactor the singleton to a non-singleton, you probably made a design error, but hey everybody makes them (I should know  Wink)
However, I suspect when you do refactor your singleton to a non-singleton, chances are than you break code that relies on the singleton being in fact a singleton. And why creating a singleton in the first place when you can't rely on the singleton being in fact a singleton?

Erik

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline cfmdobbie

Senior Member


Medals: 1


Who, me?


« Reply #3 - Posted 2003-10-22 08:15:09 »

One useful point about them is that they are still normal objects.  You can obtain a reference to a singleton and pass it to someone else, and they can use it as any other object.  If you changed it to an all-static interface this just wouldn't be possible.

Hellomynameis Charlie Dobbie.
Offline erikd

JGO Ninja


Medals: 16
Projects: 4
Exp: 14 years


Maximumisness


« Reply #4 - Posted 2003-10-22 10:05:27 »

With an all static class, you would never have to pass a reference to it to another object. I can't think of a reason why you would have to be able to in a singleton. I mean there's always just one and every object can get its reference using the method in the singleton class that is meant to provide that reference.
I suppose I'm still missing the clue Huh

Offline cfmdobbie

Senior Member


Medals: 1


Who, me?


« Reply #5 - Posted 2003-10-22 10:18:33 »

But how about if the specific object type isn't something that the target code needs to know?  You can still manipulate the object-type singleton via an interface, but with the static-type singleton the target code would have to refer directly to the particular implementation.

EDIT: This really needs an example to be perfectly clear!  How about storing a singleton object in a JNDI repository?  Or implementing a JDBC DataSource as a singleton (for whatever reason)?

Hellomynameis Charlie Dobbie.
Offline erikd

JGO Ninja


Medals: 16
Projects: 4
Exp: 14 years


Maximumisness


« Reply #6 - Posted 2003-10-22 10:48:43 »

Ah yes, I suppose you'll have a problem when you want the all static class to implement an interface which would be no problem for the singleton.

Offline tortoise

Junior Member




<3 Shmups


« Reply #7 - Posted 2003-10-22 13:44:28 »

Many things expect objects, not classes. If you just want one of those objects, a singleton's a good way to do it.

In my current program I have a toolbox window. I only want one. But it still has to be an instance of JInternalFrame. The static approach wouldn't work.
Offline Mojomonkey

Senior Member




ooh ooh eee eeee


« Reply #8 - Posted 2003-10-22 13:50:25 »

I try to follow this rule (whether or not it's a good rule is debatable).

If I have something that I'll only one a single instance of in a JVM:

1. If it maintains state, singleton. Otherwise, static.

Don't send a man to do a monkey's work.
Offline Markus_Persson

JGO Wizard


Medals: 14
Projects: 19


Mojang Specifications


« Reply #9 - Posted 2003-10-22 14:40:30 »

Good rule, imo. *wishing there was a thumbs-up emoticon*

Play Minecraft!
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline cfmdobbie

Senior Member


Medals: 1


Who, me?


« Reply #10 - Posted 2003-10-22 16:54:02 »

Quote
Good rule, imo. *wishing there was a thumbs-up emoticon*


/me hands Markus a
Click to Play


Grin

Hellomynameis Charlie Dobbie.
Offline Markus_Persson

JGO Wizard


Medals: 14
Projects: 19


Mojang Specifications


« Reply #11 - Posted 2003-10-22 17:20:14 »

Ooohh. How/where did you find that? =D

Play Minecraft!
Offline cfmdobbie

Senior Member


Medals: 1


Who, me?


« Reply #12 - Posted 2003-10-22 17:37:04 »

It's one of the options for a message logo (see above) so it's already on the JGO server.  I just copied the url and chucked it between a [ img ] [ / img ] pair.  This is also the only way of getting the animated laugh smiley:
Click to Play
.

I think I've been here too long...

Hellomynameis Charlie Dobbie.
Offline Preston

Senior Member


Medals: 4



« Reply #13 - Posted 2003-10-22 17:39:34 »

Quote

If I have something that I'll only one a single instance of in a JVM:

1. If it maintains state, singleton. Otherwise, static.

This is a good rule. I used singletons for a quite large C++ project some time ago and we used practically the same rule and it went well. :-)

Whenever a (single instanced) class has got some kind of states, so that the order of when it is beeing created could matter, a singleton is much safer than a static only class.

For a "function"-like class (like Math.sin() etc) pure static classes makes perfect sense. :-)
Offline singleton

Innocent Bystander





« Reply #14 - Posted 2013-03-27 06:25:24 »

Almost a decade has passed since the previous response and the use of dependency injection is common now. Often times the injected instance is a stateless Singleton. However, a class with static methods would not lend itself to injection. Note that this predicament is essentially the same as the one referred to by tortoise in an earlier response.
Offline HeroesGraveDev

JGO Kernel


Medals: 246
Projects: 11
Exp: 2 years


┬─┬ノ(ಠ_ಠノ)(╯°□°)╯︵ ┻━┻


« Reply #15 - Posted 2013-03-27 06:33:32 »

Just WHY did you necro an almost 10 year old thread?!

WHY????!!!!!!!

Offline princec

JGO Kernel


Medals: 369
Projects: 3
Exp: 16 years


Eh? Who? What? ... Me?


« Reply #16 - Posted 2013-03-27 08:51:20 »

He DANCES ON THE GRAVE!

Cas Smiley

Offline Roquen
« Reply #17 - Posted 2013-03-27 14:28:31 »

Since "singleton" is the username I was assuming this was a pro-wrestling match.  I feel so let down.
Offline matheus23

JGO Kernel


Medals: 106
Projects: 3


You think about my Avatar right now!


« Reply #18 - Posted 2013-03-27 15:59:04 »

Just WHY did you necro an almost 10 year old thread?!

WHY?Huh!!!!!!!

He only cam here to do EXACTLY THAT...

See my:
    My development Blog:     | Or look at my RPG | Or simply my coding
http://matheusdev.tumblr.comRuins of Revenge  |      On Github
Offline tyeeeee1
« Reply #19 - Posted 2013-03-27 17:23:32 »

Since this thread had already been necro'd and I read the OP...

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
public class Test {
  private static String value;

  static {
    value = "test";
  }
 
  public static String getValue() {
    return value;
  }
}


Wont this code give a compile error? I've never seen code that just says "static{}" and does stuff within that.
Offline princec

JGO Kernel


Medals: 369
Projects: 3
Exp: 16 years


Eh? Who? What? ... Me?


« Reply #20 - Posted 2013-03-27 17:40:36 »

No, it's fine.

Cas Smiley

Offline Cero
« Reply #21 - Posted 2013-03-27 17:47:52 »

Since this thread had already been necro'd and I read the OP...

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
public class Test {
  private static String value;

  static {
    value = "test";
  }
 
  public static String getValue() {
    return value;
  }
}


Wont this code give a compile error? I've never seen code that just says "static{}" and does stuff within that.

So what it does is, like variables, it just executes the code right away when the class is first loaded somewhere somehow. It's actually pretty cool. Its like an initialize without having to call it

Offline tyeeeee1
« Reply #22 - Posted 2013-03-27 17:52:58 »

O.o That's probably one of the most useful things I've learned yet. Necro posts are awesome.
Offline matheus23

JGO Kernel


Medals: 106
Projects: 3


You think about my Avatar right now!


« Reply #23 - Posted 2013-03-27 17:58:02 »

O.o That's probably one of the most useful things I've learned yet. Necro posts are awesome.

'aaahahhhhhH!!!!' STATIC *aaaahhh*

It's probably useful to do stuff, which is near the machine, but I really hate it actually... In my opinion nothing really needs to be static, unless it's close to the machine...

See my:
    My development Blog:     | Or look at my RPG | Or simply my coding
http://matheusdev.tumblr.comRuins of Revenge  |      On Github
Offline tyeeeee1
« Reply #24 - Posted 2013-03-27 17:59:24 »

'aaahahhhhhH!!!!' STATIC *aaaahhh*

It's probably useful to do stuff, which is near the machine, but I really hate it actually... In my opinion nothing really needs to be static, unless it's close to the machine...

I was actually just about to edit my post to ask if there was another way to do it without using static{}.
Offline sproingie

JGO Kernel


Medals: 202



« Reply #25 - Posted 2013-03-27 18:02:13 »

That particular static initializer is also completely pointless since it's exactly the same as saying:

1  
2  
3  
4  
5  
6  
7  
public class Test {
  private static String value = "test";

  public static String getValue() {
    return value;
  }
}


However, they do come in handy later: http://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom

Namely, you can have the holder execute more or less arbitrary initialization code in its static initializer. I use that trick here: https://bitbucket.org/chuck/jcod/src/c2e8ae6fd81bafc50bce94e2b2c9a0a26f3137d6/src/main/java/net/fishbulb/jcod/display/TileDisplay.java?at=default#cl-150



Offline Damocles
« Reply #26 - Posted 2013-04-04 12:12:48 »

Quote
Wont this code give a compile error? I've never seen code that just says "static{}" and does stuff within that.

This also works, can be run without a main method.

1  
2  
3  
4  
5  
6  
7  
8  
public class StartStatic
{
   static
   {
      System.out.println("Hello, main is overrated...");
   }

}


or even

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
public class StartStatic
{
   static
   {
      System.out.println("Dont like main");
      new Thread()
      {
         public void run()
         {
         for(int i=0;i<10;i++)
         {
            System.out.println("Im running! "+i);
            try
            {
               Thread.sleep(500);
            }
            catch (InterruptedException e)
            {
               e.printStackTrace();
            }
         }
         
         }
     
      }.start();
   }

}


Would be a good way to make your teacher mad in a programming class.

Offline Oskuro

JGO Knight


Medals: 39
Exp: 6 years


Coding in Style


« Reply #27 - Posted 2013-06-09 19:11:38 »


A good example of when to use the static initialization is Riven's implementation of sin/cos using lookup tables: here

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
private static final float   RAD,DEG;
private static final int     SIN_BITS,SIN_MASK,SIN_COUNT;
private static final float   radFull,radToIndex;
private static final float   degFull,degToIndex;
private static final float[] sin, cos;

static
{
    RAD = (float) Math.PI / 180.0f;
    DEG = 180.0f / (float) Math.PI;
   
    SIN_BITS  = 12;
    SIN_MASK  = ~(-1 << SIN_BITS);
    SIN_COUNT = SIN_MASK + 1;
   
    radFull    = (float) (Math.PI * 2.0);
    degFull    = (float) (360.0);
    radToIndex = SIN_COUNT / radFull;
    degToIndex = SIN_COUNT / degFull;
    sin = new float[SIN_COUNT];
    cos = new float[SIN_COUNT];

    for (int i = 0; i < SIN_COUNT; i++)
    {
        sin[i] = (float) Math.sin((i + 0.5f) / SIN_COUNT * radFull);
        cos[i] = (float) Math.cos((i + 0.5f) / SIN_COUNT * radFull);
    }
}


In other words, when you need complex static data structures that can be generated procedurally.


Just WHY did you necro an almost 10 year old thread?!

WHY?Huh!!!!!!!

Have you noticed who made the first reply to the thread?  Roll Eyes

Offline relminator
« Reply #28 - Posted 2013-06-10 02:10:14 »

No one is going to win this argument.  Some like to use singletons while others like to use statics.  I kind of like to mix it up depending on mostly my mood and not from a coding standpoint.

I have a friend at EA UK who told me that they don't care whether you use singletons or static globals (namespaced as this was in c++) as long as your sibgletons are not "lazy" (for memory efficiency obviously).
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Nickropheliac (15 views)
2014-08-31 22:59:12

TehJavaDev (23 views)
2014-08-28 18:26:30

CopyableCougar4 (29 views)
2014-08-22 19:31:30

atombrot (41 views)
2014-08-19 09:29:53

Tekkerue (38 views)
2014-08-16 06:45:27

Tekkerue (35 views)
2014-08-16 06:22:17

Tekkerue (25 views)
2014-08-16 06:20:21

Tekkerue (34 views)
2014-08-16 06:12:11

Rayexar (72 views)
2014-08-11 02:49:23

BurntPizza (48 views)
2014-08-09 21:09:32
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!