The Artima Developer Community
Sponsored Link

Java Answers Forum
Using only 1 instance of an object

1 reply on 1 page. Most recent reply: Dec 13, 2006 3:14 AM by Matthias Neumair

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Dale Rosenbaum

Posts: 1
Nickname: nmebehind
Registered: Dec, 2006

Using only 1 instance of an object Posted: Dec 12, 2006 8:08 AM
Reply to this message Reply
Advertisement
Hey everyone, I'm currently trying to build a little simulation with java and I need a bit of help. My simple simulation consists of a map, tanks and obstacles. My question is this....

I have a map class but classes are just basically blueprints for multiple instantiations. I only ever need 1 instance of a map in my program. Should I just keep the map class and instantiate it once? Or is there a better way (static class?) to only use one instance of an object that you need.

I hope that was clear. Any help would be useful. Thanks.


Matthias Neumair

Posts: 660
Nickname: neumi
Registered: Sep, 2003

Re: Using only 1 instance of an object Posted: Dec 13, 2006 3:14 AM
Reply to this message Reply
Keeping all constructors private and adding some static methods and variables would be onen asty way to do it:

 public class Map {
 
    private Map(...) {
    }
 
    public static Map createMap(...) {
        if (staticMap == null)
            staticMap = new Map(...);
        return staticMap;
    }
 
    private static staticMap = null;
 
}


So everytime someone wants to create the map, he calls.
Map myMap = Map.createMap(...);

instead of
Map myMap = new Map(...);



You could of course keep your reference to the map of course and pass it to everyone who needs it, like you mentioned first.

For all the Icons i use in my softwares, I implemented a provider which works basically like the method above. I pass the icon id to the provider. That provider looks if the icon was allready loaded and loads it if needed. If not it returns the icon which was loaded earlier.

Flat View: This topic has 1 reply on 1 page
Topic: Using only 1 instance of an object Previous Topic   Next Topic Topic: Please help, urgent issue

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use