Singleton Class using a constructor not a get Instance method ?

Hi,
I have a class with a couple of contructors, the class is instantiated many times in the application.
Is there any way by which I can return a single instance of the class when the contructor is called ?.
I dont want to declare a get instance method to return a single instance is it somehow possible to do this in the contructor itself.
This is done so I dont have to refactor the whole application and change all the places where this class is instantiated.
Example
XXXClass xxx = new XXXClass();
every time new XXXClass() is called the single instance of the class must be returned.
I dont want to implement
XXXClass xxx = XXXClass.getInstance();
Thanks in advance
Rgds
Pradeep Thomas

Pradeep ,
You see a constructor does not return anything
when you tell java
String str = new String();
It is into the reference str that a Object of the type String is assigned and used ..
If you want a single instance to exist in your application ..the best way is to use the singelton approach.
Alternatively you could create one static instance of the object in a parent class and all the classes that inherit from it will then share access .

Similar Messages

  • Singleton Class using a constructor not a getInstance method

    Hi,
    I have a class with a couple of contructors, the class is instantiated many times in the application.
    Is there any way by which I can return a single instance of the class when the contructor is called ?.
    I dont want to declare a get instance method to return a single instance is it somehow possible to do this in the contructor itself.
    This is done so I dont have to refactor the whole application and change all the places where this class is instantiated.
    Example
    XXXClass xxx = new XXXClass();
    every time new XXXClass() is called the single instance of the class must be returned.
    I dont want to implement
    XXXClass xxx = XXXClass.getInstance();
    Thanks in advance
    Rgds
    Pradeep Thomas

    The short answer to your question is No. If your class has accessible constructors and your code calls "new" then there will be multiple instances of the corresponding objects.
    Possible ways round your problem are to use static variables in place of instance variables or to use your existing class as a wrapper for another class that is instantiated only once. This second class should include all the variables and methods and the wrapper class would delegate all calls to it. This is not quite a singleton because there would still be multiple instances of the wrapper, but each instance would share the same variables and methods. You could also add a getInstance() method to the wrapper class so that new code could start to use it as a singleton.
    Other than that, it's time to refactor! Good Luck.

  • Class "adressverwaltung.AdressverwaltungView" does not have a main method

    Hello
    I'm new to Java and also to Netbeans.
    In Netbeans I created a new project as a Java Desktop application. If I will run this application (Run > Run file) I'll get the following error message: Class "adressverwaltung.AdressverwaltungView" does not have a main method.
    What do I have to do to get a main method?
    Thanks in advance.
    Peter

    linux_desktop wrote:
    2: You're right: I have to learn the basics. But the first answer of db didn't help. If I have a site with a lot of chapters, I'm interested in to know which chapter will explain the solution of my problem. Because I'm not interested in to spend a lot of time for nothing.If you're not interested in investing time to learn the basics, then that's your choice.
    However it means that you are highly unlikely to get any good help around here.
    This is not a homework service and we don't usually condone people taking shortcuts, because there aren't any shortcuts that result in actual learning here.
    If you want to do an address management application, then you will need the information contained in the tutorials, there's no way around it.
    And presenting you with "this is how you write a main method" will not help you, because you'll still be missing tons of other stuff.
    3: Only to read is not enough. I have to create an example, learning by doing is it called.As you've been told, you should have looked into the tutorials before discarding them. They do include examples where you should program.

  • Error: 1026: Constructor functions must be instance methods.

    I am follwoing a tutorial on linda.com about creating a website in Flash
    everything was going well until i started trying to copy the action script in the online examples
    now I keep getting this error message and can't figure out how to get rid of it:
    1026: Constructor functions must be instance methods.
    any assistance wouold be much appreciated, thank you
    here is the action script I am using for my buttons:
    stop();
    tv.addEventListener(MouseEvent.CLICK, clickSection);
    function clickSection(evtObj:MouseEvent){
    gotoAndStop("tv");

    I'm sorry, I am still not following what you are saying
    here is what I have in the actions layer, frame 1
    stop();
    tv.addEventListener(MouseEvent.CLICK, clickSection);
    anim.addEventListener(MouseEvent.CLICK, clickSection);
    ads.addEventListener(MouseEvent.CLICK, clickSection);
    photo.addEventListener(MouseEvent.CLICK, clickSection);
    film.addEventListener(MouseEvent.CLICK, clickSection);
    home.addEventListener(MouseEvent.CLICK, clickSection);
    function clickSection(evtObj:MouseEvent){
    trace ("The "+evtObj.target.name+" button was clicked!")
    gotoAndStop(evtObj.target.name);
    I am trying to link markers on the actions time line: tv, anim, ads, photo, film and home
    with layers (web pages) on the time line below...

  • Constructor functions must be instance methods?

    Hi,
    I have this code as in the following:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
        <mx:Script>
            <![CDATA[
                import mx.controls.*;           
                import mx.events.*;
                import mx.containers.*;       
                import thematicMap.*;  
                 public var Region:Region = new Region();
                 public var Scale:Scale = new Scale();
                 public var ThematicMap:ThematicMap = new ThematicMap(); //1026:Constructor functions must be instance methods
                 public var ReadXML:ReadXML = new ReadXML();       
                 private var savedIndex:int= 99999;        
                  public function addNavigation():void{
                      var buttonTools:Array = ["Driving Distance","Education Level--College",
                                               "Education Level--High School","Median Income","Population"];
                      var navigationBar:ToggleButtonBar = new ToggleButtonBar();
                          navigationBar.dataProvider = buttonTools;
                          navigationBar.toggleOnClick = true;
                          navigationBar.selectedIndex = -1;
                          navigationBar.addEventListener(ItemClickEvent.ITEM_CLICK,clickHandler);                      
                          //pass the variables?
                          addSlider(); //add the slider control  
                          vbox.addChild(navigationBar);
                  public function addSlider():void{
                       var text_entry:HBox = new HBox();                 
                       var numColors:TextInput = new TextInput();
                           numColors.length == 3;
                           numColors.text = "5";
                           numColors.restrict = "0-9";
                       var direction:Text= new Text();
                           direction.text = "Number of Colors";
                        //recalculate the map if the listener is called
                       text_entry.addChild(direction);
                       text_entry.addChild(numColors);
                       vbox.addChild(text_entry);                    
                 public function clickHandler(event:ItemClickEvent):void{
                     if(event.index == savedIndex) {
                         //don't do a thing
                     else savedIndex = event.index;           
                     //add the thematic map                
                     ThematicMap.addRegions(OK); //This part never worked
                     //mapGrid.addChild(thematicmap);
            ]]>
        </mx:Script>
       <mx:Canvas id="map" creationComplete="addNavigation()">
               <mx:VBox id="vbox" x="20" y="10">           
               <mx:Canvas id="mapGrid"/>      
        </mx:VBox>     
       </mx:Canvas>
    </mx:Application>
    Here is what I have in my ThematicMap.as:
    package thematicMap
        import mx.core.*;
        import mx.events.*;
        public class ThematicMap {       
            public var region:Region = new Region();  
            public var readXML:ReadXML = new ReadXML();     
            public function addRegions(name:String):void {   
                 trace(name);      
    Have I done something wrong here? How come it keeps telling me that the constructor functions must be instance methods?
    Thanks for your help.
    Alice

    Yes, I put in the quotes, and that took care of that error.
    However, it still tells me I have an error that I am calling a possibly undefined method addRegions through a reference with static type ThematicMap
    Here is the complete code of my main app:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
        <mx:Script>
            <![CDATA[
                import mx.controls.*;           
                import mx.events.*;
                import mx.containers.*;       
                import thematicMap.*;   //I had imported all the classes
                 public var region:Region = new Region();
                 public var scale:Scale = new Scale();
                 public var thematicMaps:ThematicMap = new ThematicMap();
                 public var readXML:ReadXML = new ReadXML();       
                 private var savedIndex:int= 99999;        
                  public function addNavigation():void{
                      var buttonTools:Array = ["Driving Distance","Education Level--College",  "Education Level--High School","Median Income","Population"];
                      var navigationBar:ToggleButtonBar = new ToggleButtonBar();
                          navigationBar.dataProvider = buttonTools;
                          navigationBar.toggleOnClick = true;
                          navigationBar.selectedIndex = -1;
                          navigationBar.addEventListener(ItemClickEvent.ITEM_CLICK,clickHandler);                      
                          //pass the variables?
                          addSlider(); //add the slider control  
                          vbox.addChild(navigationBar);
                  public function addSlider():void{
                       var text_entry:HBox = new HBox();                 
                       var numColors:TextInput = new TextInput();
                           numColors.length == 3;
                           numColors.text = "5";
                           numColors.restrict = "0-9";
                       var direction:Text= new Text();
                           direction.text = "Number of Colors";
                        //recalculate the map if the listener is called
                       text_entry.addChild(direction);
                       text_entry.addChild(numColors);
                       vbox.addChild(text_entry);                    
                 public function clickHandler(event:ItemClickEvent):void{
                     if(event.index == savedIndex) {
                         //don't do a thing
                     else savedIndex = event.index;           
                     //add the thematic map                
                     thematicMaps.addRegions("OK");
                     //mapGrid.addChild(thematicmap);
            ]]>
        </mx:Script>
       <mx:Canvas id="map" creationComplete="addNavigation()">
               <mx:VBox id="vbox" x="20" y="10">           
               <mx:Canvas id="mapGrid"/>      
        </mx:VBox>     
       </mx:Canvas>
    </mx:Application>
    As a matter of fact, when I write import thematicMap. it looks like thematicMap.ThematicMap does show up, so that is imported, right?
    I am getting confused.
    Alice

  • Get instance method and design pattern

    Hi All,
    1. I New to abap objects and i read the help and some stuff from the forum,
    l like to now more about design pattern in abap objects,
    2. I saw in some abap class the use of method of GET_INSTANCE i think it's from factory pattern , what is the pros. and cons to use this method ,when i should consider to use it ?
    Thanks in Advance
    Nina

    Hello Nina
    A very good introduction into design patterns is the book "Head First: Design Patterns". Here you will find many good reasons why and when to use the factory pattern.
    You should use the factory pattern when
    - you want to prevent "direct" instantiation (i.e. using a public CONSTRUCTOR method) by the developer
    - you want to hide the complexity of instantiation from the user of the class
    - the instantiation creates an implementation of an interface and you want to keep control of which implementing class is returned
    Regards
      Uwe

  • Constructor function must be instance method Error

    Hi I m got puzzled that How this error happen, Last time I finish the project all modules was working properly, but today I open file and render then I wounder the all base classes of Linkage object is missing and if i give them(flash.dispaly.MovieClip) manually then it dosen't show any error and it dosen't accept. When I delete the class of any linkage object then It accept base class of linkage object. How can I solve the Problem.???

    Hi,
    I clicked that option under the "Flash" tab and the same curt error message appeared.
    I'll try to answer your question on how I put together the file.
    The file contains static art, static text and a movie clip that runs through twice.  All that functions fine.
    **Perhaps I need to change the name in various locations relate to the button and the actions.  Here's what I did next:
    I then added a layer and called it "invisibleBtn"
    Drew a rectangle and converted it to a symbol and called it "invisibleBtn" - I also labeled it "invisibleBtn" in the window under the "Properties" tab when you click the rectangle in Scene 1 (can't remember what that box is called)
    I added another layer and called it "ActionScript"
    I called up the Actions-Frame window and added this code:
    invsibleBtn.addEventListener(MouseEvent.CLICK,onClick);
    function onClick(event:MouseEvent):void {
    navigateToURL(new URLRequest ("http://www.fcnmarketingsolutions.com"));
    I hope this is what you were asking for in your message.
    Thanks.

  • Class with private constructor can be extended or not

    Hi All,
    I have a doubt.
    if a class has private constructor and there are some methods in this class.Can this class be extended and if yes how can we call its method in subclass?
    Thanks
    Sumit

    Karanjit wrote:
    If a class contains only private constructors, then it cannot be extended.Err... not the whole story!
    public class Sabre20090603a
        static class Fred extends Sabre20090603a
            Fred()
                super();
        private Sabre20090603a()
    }

  • Why are Constructor not inherited?

    Hello,
    how come Java Constructors are not inherited by subclasses? Consider:
    ClassA
    ClassA(someParameters)
    ClassB extends ClassA
    How come do I need to declare a Constructor in ClassB that will accept "someParameters"? Why don't my ClassB simply inherites its parent Constructor?
    Thanks for any insights :-)
    PA.

    Hi,
    Straight from the Java Language Specs:
    2.12 Constructors
    A constructor is used in the creation of an object that is an instance of a class. The constructor declaration looks like a method declaration that has no result type. Constructors are invoked by class instance creation expressions, by the conversions and concatenations caused by the string concatenation operator +, and by explicit constructor invocations from other constructors; they are never invoked by method invocation expressions.
    Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.
    If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body is implicitly assumed by the compiler to begin with a superclass constructor invocation "super();", an invocation of the constructor of the direct superclass that takes no arguments.
    If a class declares no constructors then a default constructor, which takes no arguments, is automatically provided. If the class being declared is Object, then the default constructor has an empty body. Otherwise, the default constructor takes no arguments and simply invokes the superclass constructor with no arguments. If the class is declared public, then the default constructor is implicitly given the access modifier public. Otherwise, the default constructor has the default access implied by no access modifier.
    A class can be designed to prevent code outside the class declaration from creating instances of the class by declaring at least one constructor, in order to prevent the creation of an implicit constructor, and declaring all constructors to be private.
    This should answer your question and then some.
    Try reading the JLS yourself to get answers as to why ... then come back here and get help with how.
    http://java.sun.com/docs/books/vmspec/2nd-edition/html/VMSpecTOC.doc.html
    Regards,
    Manfred.

  • Singleton class within Container

    Let me extend my apologies now if this is to simple of a question for the forum.
    Here is my design issue. We are within a session bean (Stateless) and each session bean will need access to a Singleton class which possesses reference data (has a find method). This Singleton class must be static as we do not wish to replicate the amount of data involved.
    Here is my concern. Based on the fact the EJB container has created 10 session beans which must access this Singleton class and the methods within it, I "think" there will be a concurrency issue with this design.
    Can a EJB guru shade some light on this issue for me?
    Thanks in advance!

    If the the singleton class is used for multiple read and only one specific bean does a write, I dont think there should be a problem.
    However, if there are multiple read and write scenarios, then offcourse concurrency is an issue.
    What kind of data are using inside the single ton class. If you are using a hashtable or Vector inside, they take care of concurreny , as they are synchronized.
    Or else another way I could think of is
    Create a statefull session bean, instead of a java object for your singleton. Make the maximum and minimum cache size to 1.
    This will take care of the object to be singleton. And the bean would take care of the concurreny.
    Just my thoughts, am not an expert,

  • Class methods vs. Instance methods

    When shall we use class methods instead of instance methods , and vice versa?
    By going through the Java Tutorial, it only says the following.
    A common use for static methods is to access static fields....
    I am definitely sure that class methods aren't just exist for accessing static fields of a class.
    PS. I understand that instance methods belong to the object that is instantiated and class methods belong to the class itself.

    Jay-K wrote:
    JoachimSauer wrote:
    P.S.: I wouldn't call them "class methods". They are called static methods in Java. It helps to stay with the common, widely-used terminology.Thanks, its good to know what the norms are.
    but i wonder why the Java Tutorial states it clearly "Class Methods" over here [http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html|http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html]
    Because strictly speaking that's what they are. They belong to classes, rather than instances of classes. The world-at-large, though, has found that term to be a bit ambiguous, especially when discussing fields - it's not uncommon to see instance variables referred to as "class variables" by newbies - so it's kind-of self-corrected.

  • Junit : How can I get the method name (say testMyAddress) that failed

    My code is below
              TestSuite masterSuite = new TestSuite(testClass);
              TestResult result = new TestResult();
              masterSuite.run(result);
                   Enumeration errors = result.errors();
                   while (errors.hasMoreElements())
                        TestFailure error = (TestFailure)errors.nextElement();
                        Test test = error.failedTest();
    /*will give me the class name but how can I get the method that threw the exception.
    I can get fName (that contains the method name) field to get the method,but being private I cannot hold of the field.
    Wondering if there is any easy way to get the method name that threw exception,without writing unneccessary code
                        Class c1 = test.getClass();
    thx
    m

    getting all methods is no good!
    My test class looks like this
    MyTestClass{
    testGoodData(){
    asserttrue(.....);
    testBadData(){
    asserttrue(.....);
    testNullData(){
    asserttrue(.....);
    someHelperMethod(){
    thx
    m

  • Can not access the Instance Data of a Singleton class from MBean

    I am working against the deadline and i am sweating now. From past few days i have been working on a problem and now its the time to shout out.
    I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecysle, i will be adding data to the SDATA instance.So, this SDATA instance always has the data.
    Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if i check the data structures when i am adding the data, all the structures contains data. But when i call this singleton instance from the MBean, am kind of having the empty data.
    Can anyone explain or have hints on what's happening ? Any help will be appreciated.
    I tried all sorts of DATA class being final and all methods being synchronized, static, ect.,, just to make sure. But no luck till now.
    Another unfortunate thing is that, i some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
    Please see the detailed problem at @ http://stackoverflow.com/questions/1151117/can-not-access-the-instance-data-of-a-singleton-class-from-mbean
    I see related problems but no real solutions. Appreciate if anyone can throw in ideas.
    http://www.velocityreviews.com/forums/t135852-rmi-singletons-and-multiple-classloaders-in-weblogic.html
    http://www.theserverside.com/discussions/thread.tss?thread_id=12194
    http://www.jguru.com/faq/view.jsp?EID=1051835
    Thanks,
    Krishna

    I am working against the deadline and i am sweating now. From past few days i have been working on a problem and now its the time to shout out.
    I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecysle, i will be adding data to the SDATA instance.So, this SDATA instance always has the data.
    Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if i check the data structures when i am adding the data, all the structures contains data. But when i call this singleton instance from the MBean, am kind of having the empty data.
    Can anyone explain or have hints on what's happening ? Any help will be appreciated.
    I tried all sorts of DATA class being final and all methods being synchronized, static, ect.,, just to make sure. But no luck till now.
    Another unfortunate thing is that, i some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
    Please see the detailed problem at @ http://stackoverflow.com/questions/1151117/can-not-access-the-instance-data-of-a-singleton-class-from-mbean
    I see related problems but no real solutions. Appreciate if anyone can throw in ideas.
    http://www.velocityreviews.com/forums/t135852-rmi-singletons-and-multiple-classloaders-in-weblogic.html
    http://www.theserverside.com/discussions/thread.tss?thread_id=12194
    http://www.jguru.com/faq/view.jsp?EID=1051835
    Thanks,
    Krishna

  • Reflection: get an instance of a internal class by default constructor

    Hi there
    first the structure (reduced):
    public class ConvertionFactors { //singelton
    private HashMap<String,Class> factors = new HashMap<String,Class>();
    private class M_TO_FT implements DataFilter{
    public double convert(double value) {
    return value*M_IN_FT;
    public DataFilter getFilter(String from, String to)
    String name = from.toUpperCase()+convertionMethodNameSeparator+to.toUpperCase();
    Class c = factors.get(name); //retrieve the class
    Object o = c.newInstance(); //generate a instance.... not working
    return (DataFilter)o;
    The problem i want an instance of the internal class without defining a construktor like
    public M_TO_FT(){} because there are many classes like this one :-(
    (that was already working with a constructor that wants an instance of the container class.... thats what i am missing in the call c.newInstance() which uses the default constructor (i gues))
    i want something like
    new M_TO_FT() ; just the reflection version of it which calls the default constructor
    thanks for help

    well i get a Exception like this:
    java.lang.InstantiationException: com.eads.jpinfinity.data.unit.ConvertionFactors$M_TO_FT
         at java.lang.Class.newInstance0(Class.java:335)
         at java.lang.Class.newInstance(Class.java:303)
         at com.eads.jpinfinity.data.unit.ConvertionFactors.getFilter(ConvertionFactors.java:315)
         at com.eads.jpinfinity.data.unit.junit.ConvertionFactorsTest.testGetFilter(ConvertionFactorsTest.java:50)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at junit.framework.TestCase.runTest(TestCase.java:154)
         at junit.framework.TestCase.runBare(TestCase.java:127)
         at junit.framework.TestResult$1.protect(TestResult.java:106)
         at junit.framework.TestResult.runProtected(TestResult.java:124)
         at junit.framework.TestResult.run(TestResult.java:109)
         at junit.framework.TestCase.run(TestCase.java:118)
         at junit.framework.TestSuite.runTest(TestSuite.java:208)
         at junit.framework.TestSuite.run(TestSuite.java:203)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:421)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:305)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:186)
    i think because i never told the method which is the containing class for this internal class. if i defina a constructor in the inner class it always needs a instance of the containter. by calling c.newInstance() there is no relation to the container class and because the inner class cant exist without the outer class it may not be constructed.
    It is possible to get an instance with "new FT_TO_M();" (the traditional way) with the default constructor but jet i have not found a way to get a instance of a inner class with reflection without defining a constructor.

  • Help: Factory Class using Inner Class and Private Constructor?

    The situation is as follows:
    I want a GamesCollection class that instantiates Game objects by looking up the information needed from a database. I would like to use Game outside of GamesCollection, but only have it instantiated by GamesCollection to ensure the game actually exist. Each Game object is linked to a database record. If a Game object exist, it must also exist in the database. Game objects can never be removed from the database.
    I thought about making the Game object an inner class of GamesCollection, but this means that Game class constructor is still visible outside. So what if I made Game constructor private? Well, now I can't create Game objects without a static method inside Game class (static Object factory).
    Basically what I need is a constructor for the inner Game class accessible to GamesCollection, but not to the rest of the world (including packages). Is there a way to do this?

    leesiulung wrote:
    As a second look, I was initially confused about your first implementation, but it now makes more sense.
    Let me make sure I understand this:
    - the interface is needed to make the class accessible outside the outer classBetter: it is necessary to have a type that is accessible outside of GameCollection -- what else could be the return type of instance?
    - the instance() method is the object factory
    - the private modifier for the inner class is to prevent outside classes to instantiate this objectRight.
    However, is a private inner class accessible in the outer class? Try it and see.
    How does this affect private/public modifiers on inner classes?Take about five minutes and write a few tests. That should answer any questions you may have.
    How do instantiate a GameImpl object? This basically goes back to the first question.Filling out the initial solution:
    public interface Game {
        String method();
    public class GameCollection {
        private static  class GameImpl implements Game {
            public String method() {
                return "GameImpl";
        public Game instance() {
            return new GameImpl();
        public static void main(String[] args) {
            GameCollection app = new GameCollection();
            Game game = app.instance();
            System.out.println(game.method());
    }Even if you were not interested in controlling game creation, defining interfaces for key concepts like Game is always going to be a good idea. Consider how you will write testing code, for example. How will you mock Game?

Maybe you are looking for