Search Results

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

Page 3/31 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Can the Singleton be replaced by Factory?

    - by lostiniceland
    Hello Everyone There are already quite some posts about the Singleton-Pattern around, but I would like to start another one on this topic since I would like to know if the Factory-Pattern would be the right approach to remove this "anti-pattern". In the past I used the singleton quite a lot, also did my fellow collegues since it is so easy to use. For example, the Eclipse IDE or better its workbench-model makes heavy usage of singletons as well. It was due to some posts about E4 (the next big Eclipse version) that made me start to rethink the singleton. The bottom line was that due to this singletons the dependecies in Eclipse 3.x are tightly coupled. Lets assume I want to get rid of all singletons completely and instead use factories. My thoughts were as follows: hide complexity less coupling I have control over how many instances are created (just store the reference I a private field of the factory) mock the factory for testing (with Dependency Injection) when it is behind an interface In some cases the factories can make more than one singleton obsolete (depending on business logic/component composition) Does this make sense? If not, please give good reasons for why you think so. An alternative solution is also appreciated. Thanks Marc

    Read the article

  • Trouble implementing Singleton pattern in Tomcat web application due to Class Loader

    - by jwegan
    I'm trying to implement a Singleton in Tomcat 6.24 on Linux with x86_64 OpenJDK 1.6. My application is just a bunch of JSPs and some static content and the JSPs make calls to my Java code. Currently the web.xml just looks like this: <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <description> App Name </description> <display-name>App Name</display-name> <!-- The Usual Welcome File List --> <welcome-file-list> <welcome-file>pages/index.jsp</welcome-file> </welcome-file-list> </web-app> Before when I was trying to load my Singleton it was getting instantiated twice since the class was getting loaded by two different class loaders (I'm not sure why) and each loader would create an instance of the singleton which is not acceptable for my application. I finally figured out if I exported my code as a jar and put it in $CATALINA_HOME/lib then there was only one instance, but this is not an elegant solution. I've been googling for hours, but I haven't come up with anything yet. I'm wondering if there is some other solution. Currently I'm not precompling my JSPs, could this be part of the problem? Could I write a servlet to ensure the singleton is created? If so how do I do that?

    Read the article

  • Singleton issue causing a buffer overrun

    - by Rudiger
    Hi everyone, Ive created a singleton to store 2 arrays: @interface Globals : NSObject { NSMutableArray *items; NSMutableArray *extras; } + (Globals *)sharedInstance; @property (nonatomic, assign) NSMutableArray *items; @property (nonatomic, assign) NSMutableArray *extras; @end @implementation Globals @synthesize items, extras; + (Globals *)sharedInstance { static Globals *myInstance = nil; @synchronized(self) { if(!myInstance) { myInstance = [[Globals alloc] init]; } } return myInstance; } -(void)dealloc { [items release]; [extras release]; [super dealloc]; } @end When I set the Arrays in the singleton from the App delegate and then output them to NSLog it displays what is expected. But when I call it from a view controller further into the App it displays the first entry fine, some of the second entry and then garbage which is i assume a buffer overrun, sometimes it also crashes. I set the singleton array in the appDelegate like so: Globals *sharedInstance = [Globals sharedInstance]; [sharedInstance setItems:items]; and retrieve it: [[[sharedInstance items] objectAtIndex:indexPath.row] objectForKey:@"name"]; cell.description.text = [[[sharedInstance items] objectAtIndex:indexPath.row] objectForKey:@"description"]; Name works fine in both cells if there is 2, description works in the first case, never in the second case. Is it because the arrays in my singleton aren't static? If so why is it outputting the first entry fine? Cheers for any help.

    Read the article

  • Singleton pattern in C++

    - by skydoor
    I have a question about the singleton pattern. I saw two cases concerning the static member in the singleton class. First it is an object, like this class CMySingleton { public: static CMySingleton& Instance() { static CMySingleton singleton; return singleton; } // Other non-static member functions private: CMySingleton() {} // Private constructor ~CMySingleton() {} CMySingleton(const CMySingleton&); // Prevent copy-construction CMySingleton& operator=(const CMySingleton&); // Prevent assignment }; One is an pointer, like this class GlobalClass { int m_value; static GlobalClass *s_instance; GlobalClass(int v = 0) { m_value = v; } public: int get_value() { return m_value; } void set_value(int v) { m_value = v; } static GlobalClass *instance() { if (!s_instance) s_instance = new GlobalClass; return s_instance; } }; What's the difference between the two cases? Which one is correct?

    Read the article

  • [PHP] Singleton class and using inheritance

    - by Saif Bechan
    I have am working on a web application that makes use of helper classes. These classes hold functions to various operation such as form handling. Sometimes I need these classes at more than one spot in my application, The way I do it now is to make a new Object. I can't pass the variable, this will be too much work. I was wondering of using singleton classes for this. This way I am sure only one instance is running at a time. My question however is when I use this pattern, should I make a singleton class for all the objects, this would b a lot of code replication. Could I instead make a super class of superHelper, which is a singleton class, and then let every helper extend it. Would this sort of set up work, or is there another alternative? And if it works, does someone have any suggestions on how to code such a superHelper class. Thank you guys

    Read the article

  • Managing string resources in a Java application - singleton?

    - by Joe Attardi
    I seek a solution to the age-old problem of managing string resources. My current implementation seems to work well, but it depends on using singletons, and I know how often singletons can be maligned. The resource manager class has a singleton instance that handles lookups in the ResourceBundle, and you use it like so: MessageResources mr = MessageResources.getMessageResources(); // returns singleton instance ... JLabel helloLabel = new JLabel(mr.getString("label.hello")); Is this an appropriate use of a singleton? Is there some better, more universally used approach that I'm not aware of? I understand that this is probably a bit subjective, but any feedback I can get would be appreciated. I'd rather find out early on that I'm doing it wrong than later on in the process. Thanks!

    Read the article

  • Java singleton VO class implementing serializable, having default values using getter methods

    - by user309281
    Hi All I have a J2SE application having user threads running in a separate JVM outside JBOSS server. During startup, J2SE invokes a EJB inside jboss, by passing a new object(singleton) of simple JAVA VO class having getter/setter methods. {The VO class is a singleton and implements serialiable(as mandated by EJB)}. EJB receives the object, reads all db configuration and uses the setter methods of new object to set all the values. It then returns back this updated object back to J2SE in the same remote call. After J2SE receives the object(singleton/serializable), if i invoke getter methods, I could see only default values set during object creation before EJB call, and not the values set by the EJB. Kindly throw some light on, why the received object from EJB does not see any updated values and how to rectify this. I believe it got to do with object initialization during deserialization. And i tried overriding readResolve() in the VO class, but of no help. With Regards, Krishna

    Read the article

  • iPhone: Using a Singleton with Tabview Controller and Navigation Controller

    - by malleswar
    Hi Friends, I have developed a small iPhone application by using singleton that I use to navigate through the views. Here is a sample method from my singleton class. + (void) loadMenuController:(NSMutableArray *)menuItems{ MenuViewController *menuViewControler = [[MenuViewController alloc] initWithNibName:@"MenuViewController" bundle:nil]; [menuViewControler setMenuItems:menuItems]; RootViewController *root = ( P2MAppDelegate *appDelegate = (P2MAppDelegate*) [[UIApplication sharedApplication] delegate]; UINavigationController *navController = [appDelegate navigationController]; [navController pushViewController:menuViewControler animated:YES]; [menuViewControler release]; } Now my requirement has changed to require a tab view controller . I could change my application delegate to a tabview controller but I still need to navigate inside each tab. I am unable get a clue how to navigate from my singleton class. Please guide me. Please let me know if my query is not clear. Thanks in advance. Regards, Malleswar

    Read the article

  • C#: How to kill a singleton window

    - by Anonymous Coward
    Hi Everyone I'm working on a WPF application which should be utilizable with two monitors. In the main window is a button which detaches a part of the content in a second window wich can then be used on the other minitor. That second window I implemented as a singleton. That works quite good except that the second window doesn't get destoryed on application shutdown which means that the app keeps running in the background. Regarding that problem I'd like to know if a singleton is the right way to do this and if not what would be the right way. If it is, how do I get rid of the instance and why can't I access the singleton instance from app.xaml.cs? Thanks for your help.

    Read the article

  • How to test Guice Singleton?

    - by 01
    Guice Singletons are weird for me First I thought that IService ser = Guice.createInjector().getInstance(IService.class); System.out.println("ser=" + ser); ser = Guice.createInjector().getInstance(IService.class); System.out.println("ser=" + ser); will work as singleton, but it returns ser=Service2@1975b59 ser=Service2@1f934ad its ok, it doesnt have to be easy. Injector injector = Guice.createInjector(); IService ser = injector.getInstance(IService.class); System.out.println("ser=" + ser); ser = injector.getInstance(IService.class); System.out.println("ser=" + ser); works as singleton ser=Service2@1975b59 ser=Service2@1975b59 So i need to have static field with Injector(Singleton for Singletons) how do i pass to it Module for testing?

    Read the article

  • Class design question (Disposable and singleton behavior)

    - by user137348
    The Repository class has singleton behavior and the _db implements the disposable pattern. As excepted the _db object gets disposed after the first call and because of the singleton behavior any other call of _db will crash. [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class Repository : IRepository { private readonly DataBase _db; public Repository(DataBase db) { _db = db; } public int GetCount() { using(_db) { return _db.Menus.Count(); } } public Item GetItem(int id) { using(_db) { return _db.Menus.FirstOrDefault(x=>x.Id == id); } } } My question is, is there any way to design this class to work properly without removing the singleton behavior? The Repositoryclass will be serving big amount of requests.

    Read the article

  • Way of knowing who called a singleton - objective C

    - by Cyril
    Hello, I am designing a game with several levels. I have a CCLayer defined as a singleton (called MasterScene) where I handle the pause page, transition page, player's score banner,... all the things common to all levels. So in each level, when the user pushes the pause button, a call is made to the singleton to display the CClayer corresponding to the pause page. My problem is that I want to know who called the singleton (which level) t. Is there a way of doing that ? Thanks

    Read the article

  • PHP - static DB class vs DB singleton object

    - by Marco Demaio
    I don't want to create a discussion about singleton better than static or better than global, etc. I read dozens of questions about it on SO, but I couldn't come up with an answer to this SPECIFIC question, so I hope someone could now illuminate me buy answering this question with one (or more) real simple EXAMPLES, and not theoretical discussions. In my app I have the typical DB class needed to perform tasks on DB without having to write everywhere in code mysql_connect/mysql_select_db/mysql... (moreover in future I might decide to use another type of DB engine in place of mySQL so obviously I need a class of abstration). I could write the class either as a static class: class DB { private static $connection = FALSE; //connection to be opened //DB connection values private static $server = NULL; private static $usr = NULL; private static $psw = NULL; private static $name = NULL; public static function init($db_server, $db_usr, $db_psw, $db_name) { //simply stores connections values, withour opening connection } public static function query($query_string) { //performs query over alerady opened connection, if not open, it opens connection 1st } ... } or as a Singletonm class: class DBSingleton { private $inst = NULL; private $connection = FALSE; //connection to be opened //DB connection values private $server = NULL; private $usr = NULL; private $psw = NULL; private $name = NULL; public static function getInstance($db_server, $db_usr, $db_psw, $db_name) { //simply stores connections values, withour opening connection if($inst === NULL) $this->inst = new DBSingleton(); return $this->inst; } private __construct()... public function query($query_string) { //performs query over already opened connection, if connection is not open, it opens connection 1st } ... } Then after in my app if I wanto to query the DB i could do //Performing query using static DB object DB:init(HOST, USR, PSW, DB_NAME); DB::query("SELECT..."); //Performing query using DB singleton $temp = DBSingleton::getInstance(HOST, USR, PSW, DB_NAME); $temp->query("SELECT..."); My simple brain sees Singleton has got the only advantage to avoid declaring as 'static' each method of the class. I'm sure some of you could give me an EXAMPLE of real advantage of singleton in this specific case. Thanks in advance.

    Read the article

  • linq2sql: singleton or using, best practices

    - by zerkms
    what is the preferred practice when linq2sql using (in asp.net mvc applications): to create "singleton" for DataContext like: partial class db { static db _db = new db(global::data.Properties.Settings.Default.nanocrmConnectionString, new AttributeMappingSource()); public static db GetInstance() { return _db; } } or to retrieve new instance when it needed within using: using (db _db = new db()) { ... } the usage of using brings some limitations on code. so I prefer to use singleton one. is it weird practice?

    Read the article

  • Singleton with eager initialization

    - by jesper
    I have class X that takes much time to initialize itself. I want to make that class singleton and force its creation when rails application starts. I've made the singleton: class X @@instance = nil def self.instance if @@instance.nil? @@instance = X.new puts 'CREATING' end return @@instance end private_class_method :new end The problem is that every time I use this class I see 'CREATING' in logs. I've tried to put creation of class in initializers directory but it doesn't work either.

    Read the article

  • Example of Singleton pattern

    - by Supereme
    Hi, Can anybody tell me a good example of Singleton pattern? Also I've one doubt to ask, Is the following scenario is that of singleton pattern: When we have many printers connected in LAN but only one printer queue?

    Read the article

  • Singleton & Multithreading in Java

    - by vivek jagtap
    What is the preferred way to work with Singleton class in multithreaded environment? Suppose if I have 3 thread, and all they try to access getInstance() method of singleton class at the same time - What would happen if no synchronization is maintained? Is it good practice to use synchronized getInstance() method or use synchronized block inside getInstance(). Please advise if there is any other way out.

    Read the article

  • [PHP] Making a good singleton registry class structure which hold your objects

    - by Saif Bechan
    I am working on a web application in PHP. I have a singleton class called registry. This class will hold all the objects i need throughout my application, such as loader classes, template classes, database, classes, etc. When an object of the registry class is created I send it an array with the classes it need to load: // Create the registry $registry = registry::singleton(); // Store those core objects $registry->storeObjects(Array('session','db','page','template','errors')); In this example I only put some of the classes, to get the basic idea. Now I have some classes in the registry that use each other. For example the 'errors' object uses the 'page' object. Now I was wondering if it is a good practice to make an instance of the registry object in the errors object. Like this; class errors{ private $registry; public function __construct(){ $this->registry = registry::singleton(); } } So there is an instance of the registry object, inside an object of the registry object. This does not sound like a good idea to me. Anyone have a suggestion how to model such a thing?

    Read the article

  • Call from a singleton class to a function which in turn calls that class's method

    - by dare2be
    Hello, I am still looking for a way to phrase it properly (I'm not a native speaker...). So I have this class SQL which implements the singleton pattern (for obvious reasons) and I also have this function, checkUsr(), which queries the database using one of SQL's methods. Everything works fine as long as I don't call checkUsr() from within the SQL class. When I do so, the scripts just exits and a blank page is displayed - no errors are returned, no exception is thrown... What's happening? And how do I work around this problem? EDIT: class SQL { public static function singleton() { static $instance; if(!isset($instance)) $instance = new SQL; return $instance; } public function tryLoginAuthor( $login, $sha1 ) { (...) } } function checkUsr() { if (!isset($_SESSION['login']) || !isset($_SESSION['sha1'])) throw new Exception('Not logged in', 1); $SQL = SQL::singleton(); $res = $SQL->tryLoginAuthor($_SESSION['login'], $_SESSION['sha1']); if (!isset($res[0])) throw new Exception('Not logged in', 1); }

    Read the article

  • What is the best way to create a Singleton Webservice in PHP?

    - by ChronoFish
    Hello, We have a need to access a DB that only allows one connection at a time. This screams "singleton" to me. The catch of course is that the singleton connection will be exposed (either directly or indirectly) via a web-service (most probable a SOAP based web-service - located on a separate server from the calling app(s) ) - which means that there may be more than one app / instance attempting to connect to the singleton class. In PHP, what is the best way to create a global singleton or a web-service singleton? TIA

    Read the article

  • Advantages of Singleton Class over Static Class?

    Point 1)Singleton We can get the object of singleton and then pass to other methods.Static Class We can not pass static class to other methods as we pass objectsPoint 2) Singleton In future, it is easy to change the logic of of creating objects to some pooling mechanism. Static Class Very difficult to implement some pooling logic in case of static class. We would need to make that class as non-static and then make all the methods non-static methods, So entire your code needs to be changed.Point3:) Singleton Can Singletone class be inherited to subclass? Singleton class does not say any restriction of Inheritence. So we should be able to do this as long as subclass is also inheritence.There's nothing fundamentally wrong with subclassing a class that is intended to be a singleton. There are many reasons you might want to do it. and there are many ways to accomplish it. It depends on language you use.Static Class We can not inherit Static class to another Static class in C#. Think about it this way: you access static members via type name, like this: MyStaticType.MyStaticMember(); Were you to inherit from that class, you would have to access it via the new type name: MyNewType.MyStaticMember(); Thus, the new item bears no relationships to the original when used in code. There would be no way to take advantage of any inheritance relationship for things like polymorphism. span.fullpost {display:none;}

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >