Search Results

Search found 774 results on 31 pages for 'singleton'.

Page 8/31 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Segfaults with singletons

    - by Ockonal
    Hello, I have such code: // Non singleton class MyLogManager { void write(message) {Ogre::LogManager::getSingletonPtr()->logMessage(message);} } class Utils : public singleton<Utils> { MyLogManager *handle; MyLogManager& getHandle { return *handle; } }; namespace someNamespace { MyLogManager &Log() { return Utils::get_mutable_instance().getHandle(); } } int main() { someNamespace::Log().write("Starting game initializating..."); } In this code I'm using boost's singleton (from serialization) and calling Ogre's log manager (it's singleton-type too). The program fails at any trying to do something with Ogre::LogManager::getSingletonPtr() object with code User program stopped by signal (SIGSEGV) I checked that getSingletonPtr() returns address 0x000 But using code Utils::get_mutable_instance().getHandle().write("foo") works good in another part of program. What's wrong could be there with calling singletons?

    Read the article

  • Changing the context of a self-executing function

    - by TaylorMac
    This code is copied directly from: http://www.bennadel.com/blog/2264-Changing-The-Execution-Context-Of-Your-Self-Executing-Function-Blocks-In-JavaScript.htm // Set the singleton value to the return value of the self- // executing function block. var singleton = (function(){ // Declare a private variable. var message = "Stop playing with your context!"; this.getMessage = function(){ return( message ); }; // Return this object reference. return( this ); }).call( {} ); // alert the singleton message. alert( "Message:", singleton.getMessage()); ?My thought is that I can use this to better contain the variables and functions in my programs. However, when I try to run the code in a JSfiddle: http://jsfiddle.net/xSKHh/ It does not return the message. What am I missing?

    Read the article

  • DAO/Webservice Consumption in Web Application

    - by Gavin
    I am currently working on converting a "legacy" web-based (Coldfusion) application from single data source (MSSQL database) to multi-tier OOP. In my current system there is a read/write database with all the usual stuff and additional "read-only" databases that are exported daily/hourly from an Enterprise Resource Planning (ERP) system by SSIS jobs with business product/item and manufacturing/SCM planning data. The reason I have the opportunity and need to convert to multi-tier OOP is a newer more modern ERP system is being implemented business wide that will be a complete replacement. This newer ERP system offers several interfaces for third party applications like mine, from direct SQL access to either a dotNet web-service or a SOAP-like web-service. I have found several suitable frameworks I would be happy to use (Coldspring, FW/1) but I am not sure what design patterns apply to my data access object/component and how to manage the connection/session tokens, with this background, my question has the following three parts: Firstly I have concerns with moving from the relative safety of a SSIS job that protects me from downtime and speed of the ERP system to directly connecting with one of the web services which I note seem significantly slower than I expected (simple/small requests often take up to a whole second). Are there any design patterns I can investigate/use to cache/protect my data tier? It is my understanding data access objects (the component that connects directly with the web services and convert them into the data types I can then work with in my Domain Objects) should be singletons (and will act as an Adapter/Facade), am I correct? As part of the data access object I have to setup a connection by username/password (I could set up multiple users and/or connect multiple times with this) which responds with a session token that needs to be provided on every subsequent request. Do I do this once and share it across the whole application, do I setup a new "connection" for every user of my application and keep the token in their session scope (might quickly hit licensing limits), do I set the "connection" up per page request, or is there a design pattern I am missing that can manage multiple "connections" where a requests/access uses the first free "connection"? It is worth noting if the ERP system dies I will need to reset/invalidate all the connections and start from scratch, and depending on which web-service I use might need manually close the "connection/session"

    Read the article

  • How to save data from multiple views of an iPhone app?

    - by DownUnder
    Hi Everyone. I'm making an app where I need to save the text in multiple views in the app when the app quits. I also need to be able to remove all of the data from just one of those views and when the app quits, it's possible not all of those views will have been created yet. After reading this post I thought perhaps it would be good to use a singleton that manages my app data which loads in the data when it is first requested and saved it when the app quits. Then in each view where I need to save data I can just set it on the singleton. I gave it a go but have run into some issues. At first I didn't synthesize the properties (as in the post I was using as a guide) but the compiler told me I needed to make getters and setters, so I did. Now when my applicationWIllTerminate: gets call the app crashes and the console says "Program received signal: “EXC_BAD_ACCESS”. kill quit". Is anyone able to tell me what I'm doing wrong, or suggest a better approach to saving the data? //SavedData.h #import <Foundation/Foundation.h> #define kFileName @"appData.plist" @interface SavedData : NSObject { NSString *information; NSString *name; NSString *email; NSString *phone; NSString *mobile; } @property(assign) NSString *information; @property(assign) NSString *name; @property(assign) NSString *email; @property(assign) NSString *phone; @property(assign) NSString *mobile; + (SavedData *)singleton; + (NSString *)dataFilePath; + (void)applicationWillTerminate:(NSNotification *)notification; @end //SavedData.m #import "SavedData.h" @implementation SavedData @synthesize information; @synthesize name; @synthesize email; @synthesize phone; @synthesize mobile; static SavedData * SavedData_Singleton = nil; + (SavedData *)singleton{ if (nil == SavedData_Singleton){ SavedData_Singleton = [[SavedData_Singleton alloc] init]; NSString *filePath = [self dataFilePath]; if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){ NSMutableArray * array = [[NSMutableArray alloc] initWithContentsOfFile:filePath]; information = [array objectAtIndex:0]; name = [array objectAtIndex:1]; email = [array objectAtIndex:2]; phone = [array objectAtIndex:3]; mobile = [array objectAtIndex:4]; [array release]; } UIApplication *app = [UIApplication sharedApplication]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:app]; } return SavedData_Singleton; } + (NSString *)dataFilePath{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *DocumentsDirectory = [paths objectAtIndex:0]; return [DocumentsDirectory stringByAppendingPathComponent:kFileName]; } + (void)applicationWillTerminate:(NSNotification *)notification{ NSLog(@"Application will terminate received"); NSMutableArray *array = [[NSMutableArray alloc] init]; [array addObject:information]; [array addObject:name]; [array addObject:email]; [array addObject:phone]; [array addObject:mobile]; [array writeToFile:[self dataFilePath] atomically:YES]; [array release]; } @end Then when I want to use it I do myLabel.text = [SavedData singleton].information; And when I change the field [SavedData singleton].information = @"my string"; Any help will be very much appreciated!

    Read the article

  • Dependency Injection & Singleton Design pattern

    - by SysAdmin
    How do we identify when to use dependency injection or singleton pattern. I have read in lot of websites where they say "Use Dependency injection over singleton pattern". But I am not sure if I totally agree with them. For my small or medium scale projects I definitely see the use of singleton pattern straightforward. For example Logger. I could use Logger.GetInstance().Log(...) But, instead of this, why do I need to inject every class I create, with the logger's instance?.

    Read the article

  • Singleton wrapper for Context

    - by kpdvx
    I'm considering creating a singleton wrapper for a Context so my model objects, if necessary, can open and read from a database connection. My model objects do not have access to a Context, and I'd like to avoid needing to pass a reference to a Context from object to object. I was planning to place into this singleton a reference to the Context returned by Application.getApplicationContext(). This singleton object would be initialized in my custom Application instance before anything else would need to or have a chance to use it. Can anyone think of a reason to not do this?

    Read the article

  • Singletons, thread safety and structuremap

    - by Ben
    Hi, Currently I have the following class: public class PluginManager { private static bool s_initialized; private static object s_lock = new object(); public static void Initialize() { if (!s_initialized) { lock (s_lock) { if (!s_initialized) { // initialize s_initialized = true; } } } } } The important thing here is that Initialize() should only be executed once whilst the application is running. I thought that I would refactor this into a singleton class since this would be more thread safe?: public sealed class PluginService { static PluginService() { } private static PluginService _instance = new PluginService(); public static PluginService Instance { get { return _instance; } } private bool s_initialized; public void Initialize() { if (!s_initialized) { // initialize s_initialized = true; } } } Question one, is it still necessary to have the lock here (I have removed it) since we will only ever be working on the same instance? Finally, I want to use DI and structure map to initialize my servcices so I have refactored as below: public interface IPluginService { void Initialize(); } public class NewPluginService : IPluginService { private bool s_initialized; public void Initialize() { if (!s_initialized) { // initialize s_initialized = true; } } } And in my registry: ForRequestedType<IPluginService>() .TheDefaultIsConcreteType<NewPluginService>().AsSingletons(); This works as expected (singleton returning true in the following code): var instance1 = ObjectFactory.GetInstance<IPluginService>(); var instance2 = ObjectFactory.GetInstance<IPluginService>(); bool singleton = (instance1 == instance2); So my next question, is the structure map solution as thread safe as the singleton class (second example). The only downside is that this would still allow NewPluginService to be instantiated directly (if not using structure map). Many thanks, Ben

    Read the article

  • When should EntityManagerFactory instance be created/opened ?

    - by masato-san
    Ok, I read bunch of articles/examples how to write Entity Manager Factory in singleton. One of them easiest for me to understand a bit: http://javanotepad.blogspot.com/2007/05/jpa-entitymanagerfactory-in-web.html I learned that EntityManagerFactory (EMF) should only be created once preferably in application scope. And also make sure to close the EMF once it's used (?) So I wrote EMF helper class for business methods to use: public class EmProvider { private static final String DB_PU = "KogaAlphaPU"; public static final boolean DEBUG = true; private static final EmProvider singleton = new EmProvider(); private EntityManagerFactory emf; private EmProvider() {} public static EmProvider getInstance() { return singleton; } public EntityManagerFactory getEntityManagerFactory() { if(emf == null) { emf = Persistence.createEntityManagerFactory(DB_PU); } if(DEBUG) { System.out.println("factory created on: " + new Date()); } return emf; } public void closeEmf() { if(emf.isOpen() || emf != null) { emf.close(); } emf = null; if(DEBUG) { System.out.println("EMF closed at: " + new Date()); } } }//end class And my method using EmProvider: public String foo() { EntityManager em = null; List<Object[]> out = null; try { em = EmProvider.getInstance().getEntityManagerFactory().createEntityManager(); Query query = em.createNativeQuery(JPQL_JOIN); //just some random query out = query.getResultList(); } catch(Exception e) { //handle error.... } finally { if(em != null) { em.close(); //make sure to close EntityManager } } I made sure to close EntityManager (em) within method level as suggested. But when should EntityManagerFactory be closed then? And why EMF has to be singleton so bad??? I read about concurrency issues but as I am not experienced multi-thread-grammer, I can't really be clear on this idea.

    Read the article

  • Purpose of singletons in programming

    - by thecoshman
    This is admittedly a rather loose question. My current understanding of singletons is that they are a class that you set up in such a way that only one instance is ever created. This sounds a lot like a static class to me. The main differnce being that with a static class you don't / can't instance it, you just use it such as Math.pi(). With a singletong class, you would still need to do something like singleton mySingleton = new singleton(); mysingleton.set_name("foo"); singleton otherSingleton = new singleton(); // correct me if i am wrong, but mysingleton == othersingleton right now, yes? // this the following should happen? otherSingleston.set_name("bar"); mysingleton.report_name(); // will output "bar" won't it? Please note, I am asking this language independently, more about the concept. So I am not so worried about actually how to coed such a class, but more why you would wan't to and what thing you would need to consider.

    Read the article

  • DI and Singleton Pattern in one implementation

    - by Tony
    I want to refactor some code using the Windsor IOC/DI framework, but my issue is that I have some Singleton classes and Factory pattern classes and I am not sure that one can implement a Singleton or Factory using DI. Has anyone any ideas if that is possible and how?

    Read the article

  • Refactoring Singleton Overuse

    - by drharris
    Today I had an epiphany, and it was that I was doing everything wrong. Some history: I inherited a C# application, which was really just a collection of static methods, a completely procedural mess of C# code. I refactored this the best I knew at the time, bringing in lots of post-college OOP knowledge. To make a long story short, many of the entities in code have turned out to be Singletons. Today I realized I needed 3 new classes, which would each follow the same Singleton pattern to match the rest of the software. If I keep tumbling down this slippery slope, eventually every class in my application will be Singleton, which will really be no logically different from the original group of static methods. I need help on rethinking this. I know about Dependency Injection, and that would generally be the strategy to use in breaking the Singleton curse. However, I have a few specific questions related to this refactoring, and all about best practices for doing so. How acceptable is the use of static variables to encapsulate configuration information? I have a brain block on using static, and I think it is due to an early OO class in college where the professor said static was bad. But, should I have to reconfigure the class every time I access it? When accessing hardware, is it ok to leave a static pointer to the addresses and variables needed, or should I continually perform Open() and Close() operations? Right now I have a single method acting as the controller. Specifically, I continually poll several external instruments (via hardware drivers) for data. Should this type of controller be the way to go, or should I spawn separate threads for each instrument at the program's startup? If the latter, how do I make this object oriented? Should I create classes called InstrumentAListener and InstrumentBListener? Or is there some standard way to approach this? Is there a better way to do global configuration? Right now I simply have Configuration.Instance.Foo sprinkled liberally throughout the code. Almost every class uses it, so perhaps keeping it as a Singleton makes sense. Any thoughts? A lot of my classes are things like SerialPortWriter or DataFileWriter, which must sit around waiting for this data to stream in. Since they are active the entire time, how should I arrange these in order to listen for the events generated when data comes in? Any other resources, books, or comments about how to get away from Singletons and other pattern overuse would be helpful.

    Read the article

  • example for Singleton pattern

    - by JavaUser
    Hi, Please give me a real time example for singleton pattern . Different threads accessing a shared file is singleton or not ? Since each thread access the same instance of the file not individual instances of their own .

    Read the article

  • When to use @Singleton in a Jersey resource

    - by dexter
    I have a Jersey resource that access the database. Basically it opens a database connection in the initialization of the resource. Performs queries on the resource's methods. I have observed that when I do not use @Singleton, the database is being open at each request. And we know opening a connection is really expensive right? So my question is, should I specify that the resource be singleton or is it really better to keep it at per request especially when the resource is connecting to the database? My resource code looks like this: //Use @Singleton here or not? @Path(/myservice/) public class MyResource { private ResponseGenerator responser; private Log logger = LogFactory.getLog(MyResource.class); public MyResource() { responser = new ResponseGenerator(); } @GET @Path("/clients") public String getClients() { logger.info("GETTING LIST OF CLIENTS"); return responser.returnClients(); } ... // some more methods ... } And I connect to the database using a code similar to this: public class ResponseGenerator { private Connection conn; private PreparedStatement prepStmt; private ResultSet rs; public ResponseGenerator(){ Class.forName("org.h2.Driver"); conn = DriverManager.getConnection("jdbc:h2:testdb"); } public String returnClients(){ String result; try{ prepStmt = conn.prepareStatement("SELECT * FROM hosts"); rs = prepStmt.executeQuery(); ... //do some processing here ... } catch (SQLException se){ logger.warn("Some message"); } finally { rs.close(); prepStmt.close(); // should I also close the connection here (in every method) if I stick to per request // and add getting of connection at the start of every method // conn.close(); } return result } ... // some more methods ... } Some comments on best practices for the code will also be helpful.

    Read the article

  • Singleton method not getting called in Cocos2d

    - by jini
    I am calling a Singleton method that does not get called when I try doing this. I get no errors or anything, just that I am unable to see the CCLOG message. Under what reasons would a compiler not give you error and not allow you to call a method? [[GameManager sharedGameManager] openSiteWithLinkType:kLinkTypeDeveloperSite]; The method is defined as follows: -(void)openSiteWithLinkType:(LinkTypes)linkTypeToOpen { CCLOG(@"WE ARE IN openSiteWithLinkType"); //I NEVER SEE THIS MESSAGE NSURL *urlToOpen = nil; if (linkTypeToOpen == kLinkTypeDeveloperSite) { urlToOpen = [NSURL URLWithString:@"http://somesite.com"]; } if (![[UIApplication sharedApplication]openURL:urlToOpen]) { CCLOG(@"%@%@",@"Failed to open url:",[urlToOpen description]); [self runSceneWithID:kMainMenuScene]; } } HERE IS THE CODE TO MY SINGLETON: #import "GameManager.h" #import "MainMenuScene.h" @implementation GameManager static GameManager* _sharedGameManager = nil; @synthesize isMusicON; @synthesize isSoundEffectsON; @synthesize hasPlayerDied; +(GameManager*) sharedGameManager { @synchronized([GameManager class]) { if (!_sharedGameManager) { [[self alloc] init]; return _sharedGameManager; } return nil; } } +(id)alloc { @synchronized ([GameManager class]) { NSAssert(_sharedGameManager == nil,@"Attempted to allocate a second instance of the Game Manager singleton"); _sharedGameManager = [super alloc]; return _sharedGameManager; } return nil; } -(id)init { self = [super init]; if (self != nil) { //Game Manager initialized CCLOG(@"Game Manager Singleton, init"); isMusicON = YES; isSoundEffectsON = YES; hasPlayerDied = NO; currentScene = kNoSceneUninitialized; } return self; } -(void) runSceneWithID:(SceneTypes)sceneID { SceneTypes oldScene = currentScene; currentScene = sceneID; id sceneToRun = nil; switch (sceneID) { case kMainMenuScene: sceneToRun = [MainMenuScene node]; break; default: CCLOG(@"Unknown Scene ID, cannot switch scenes"); return; break; } if (sceneToRun == nil) { //Revert back, since no new scene was found currentScene = oldScene; return; } //Menu Scenes have a value of < 100 if (sceneID < 100) { if (UI_USER_INTERFACE_IDIOM() != UIUserInterfaceIdiomPad) { CGSize screenSize = [CCDirector sharedDirector].winSizeInPixels; if (screenSize.width == 960.0f) { //iPhone 4 retina [sceneToRun setScaleX:0.9375f]; [sceneToRun setScaleY:0.8333f]; CCLOG(@"GM: Scaling for iPhone 4 (retina)"); } else { [sceneToRun setScaleX:0.4688f]; [sceneToRun setScaleY:0.4166f]; CCLOG(@"GM: Scaling for iPhone 3G or older (non-retina)"); } } } if ([[CCDirector sharedDirector] runningScene] == nil) { [[CCDirector sharedDirector] runWithScene:sceneToRun]; } else { [[CCDirector sharedDirector] replaceScene:sceneToRun]; } } -(void)openSiteWithLinkType:(LinkTypes)linkTypeToOpen { CCLOG(@"WE ARE IN openSiteWithLinkType"); NSURL *urlToOpen = nil; if (linkTypeToOpen == kLinkTypeDeveloperSite) { urlToOpen = [NSURL URLWithString:@"http://somesite.com"]; } if (![[UIApplication sharedApplication]openURL:urlToOpen]) { CCLOG(@"%@%@",@"Failed to open url:",[urlToOpen description]); [self runSceneWithID:kMainMenuScene]; } } -(void) test { CCLOG(@"this is test"); } @end

    Read the article

  • WebLogic Server Weekly for March 26th, 2012: WLS 1211 Update, Java 7 Certification, Galleria, WebLogic for DBAs, REST and Enterprise Architecture, Singleton Services

    - by Steve Button
    WebLogic Server 12c Certified with Java 7 for Production Use WebLogic Server 12c (12.1.1) has been certified with JDK 7 for development usage since December and we have now completed JDK 7 certification for use with production systems. In doing so, we have updated the WebLogic Server 12c (12.1.1) distributions incorporating fixes associated with JDK 7 support as well as some bundled patches that address several issues that have been discovered since the initial release. These updated distributions are available for download from OTN and will be beneficial for all WebLogic Server 12c (12.1.1) users in general. What's New Release Notes Download Here! Updated Oracle WebLogic Server 12.1.1.0 distribution Never one to miss a trick, Markus Eisele was one of the first to notice the WebLogic Server 12c update and post a blog about it. Sources told me that as of Friday last week you have an updated version of WebLogic Server 12c on OTN. http://blog.eisele.net/2012/03/updated-oracle-weblogic-server-12110.html Using WebLogic Server 12c with Java 7 - Video To illustrate the use of Java 7 with WebLogic Server 12c, I put together a screen cam showing the creation of a domain using Java 7 and then build and deploy a simple web application that uses Java 7 syntax to show it working. Ireland OUG Presentation: WebLogic for DBAs Simon Haslam posted his slides from a presentation he gave Dublin on 21/3/12 at the OUG Ireland conference. In this presentation, he explains the core concepts and ideas behind WebLogic Server, walks through an installation and offers some tips and common gotcha's to avoid. Simon also covers some aspects of installing and use Enterprise Manager 12c. Note: I usually install the JVM and use the generic .jar installer rather than using an installer bundled with a JVM. http://www.slideshare.net/Veriton/weblogic-for-dbas-10h Slightly Retro: Jeff West on Enterprise Architecure and REST In this weeks flashback, we look at Jeff West's blog from early 2011 where he provides some thoughtful opinions on enterprise architecture and innovation, then jumps into his views on REST. After I progressed in my career and did more team-leading and architecture type roles I was ‘educated’ on what it meant to have Asynchronous and Long-Running processes as part of your Enterprise Application architecture. If I had a synchronous process then I needed a thread available to service the request and then provide the response. https://blogs.oracle.com/jeffwest/entry/weblogic_integration_wli_web_services_and_soap_and_rest_part_1 Starting Managed Servers without an Administration Server using Node Manager and WLST Blogger weblogic-tips shows how to start a managed server without going through the Administration Server, using the Node Manager and WLST. Connect WLST to a Node Manager by entering the nmConnect command. http://www.weblogic-tips.com/2012/02/18/starting-managed-servers-without-an-administration-server-using-node-manager-and-wlst/ Using WebLogic Server Singleton Services WebLogic Server has supported the notion of a Singleton Service for a number of releases, in which WebLogic Server will maintain a single instance of a configured singleton service on one managed server within a cluster. This blog demonstrates how the singleton service can be accessed and used from applications deployed on the cluster. http://buttso.blogspot.com.au/2012/03/weblogic-server-singleton-services.html

    Read the article

  • Singleton class issue in Qt

    - by sijith
    i created a singleton class and trying to access that class in other class but getting error "cannot access private member" Setupconfig is my singleton class and i am trying to access this class in other class which have QMainWindow Error 'Setupconfig::Setupconfig' : cannot access private member declared in class 'Setupconfig' ///////////////////////////////////////////////////////////////////// Setupconfig.h static Setupconfig *buiderObj() { static Setupconfig *_setupObj= new Setupconfig(); return _setupObj; } private: Setupconfig(); ////////////////////////////////////// EasyBudget.h class EasyBudget : public QMainWindow, public Ui::EasyBudgetClass, public Setupconfig { Q_OBJECT public: Setupconfig *setupObj; } ////////////////////////////////////// EasyBudget.cpp EasyBudget::EasyBudget(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent,Qt::FramelessWindowHint) { setupObj=Setupconfig::buiderObj(); }

    Read the article

  • Who needs singletons?

    - by sexyprout
    Imagine you access your MySQL database via PDO. You got some functions, and in these functions, you need to access the database. The first thing I thought of is global, like: $db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'root', 'pwd'); function some_function() { global $db; $db->query('...'); } But it's considered as a bad practice. So, after a little search, I ended up with the Singleton pattern, which "applies to situations in which there needs to be a single instance of a class." According to the example of the manual, we should do this: class Database { private static $instance, $db; private function __construct(){} static function singleton() { if(!isset(self::$instance)) self::$instance = new __CLASS__; return self:$instance; } function get() { if(!isset(self::$db)) self::$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'user', 'pwd') return self::$db; } } function some_function() { $db = Database::singleton(); $db->get()->query('...'); } some_function(); But I just can't understand why you need that big class when you can do it merely with: class Database { private static $db; private function __construct(){} static function get() { if(!isset(self::$rand)) self::$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'user', 'pwd'); return self::$db; } } function some_function() { Database::get()->query('...'); } some_function(); This last one works perfectly and I don't need to worry about $db anymore. But maybe I'm forgetting something. So, who's wrong, who's right?

    Read the article

  • Global State and Singletons Dependency injection

    - by Manu
    this is a problem i face lot of times when i am designing a new app i'll use a sample problem to explain this think i am writing simple game.so i want to hold a list of players. i have few options.. 1.use a static field in some class private static ArrayList<Player> players = new ArrayList<Integer>(); public Player getPlayer(int i){ return players.get(i); } but this a global state 2.or i can use a singleton class PlayerList{ private PlayerList instance; private PlayerList(){...} public PlayerList getInstance() { if(instance==null){ ... } return instance; } } but this is bad because it's a singleton 3.Dependency injection class Game { private PlayerList playerList; public Game(PlayerList list) { this.list = list; } public PlayerList getPlayerList() { return playerList; } } this seems good but it's not, if any object outside Game need to look at PlayerList (which is the usual case) i have to use one of the above methods to make the Game class available globally. so I just add another layer to the problem. didn't actually solve anything. what is the optimum solution ? (currently i use Singleton approach)

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >