Search Results

Search found 6142 results on 246 pages for 'singleton pattern'.

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

  • Observer pattern for unpredictable observation time

    - by JoJo
    I have a situation where objects are created at unpredictable times. Some of these objects are created before an important event, some after. If the event already happened, I make the object execute stuff right away. If the event is forthcoming, I make the object observe the event. When the event triggers, the object is notified and executes the same code. if (subject.eventAlreadyHappened()) { observer.executeStuff(); } else { subject.subscribe(observer); } Is there another design pattern to wrap or even replace this observer pattern? I think it looks a little dirty to me.

    Read the article

  • Singleton pattern in web applications

    - by ryudice
    I'm using a singleton pattern for the datacontext in my web application so that I dont have to instantiate it every time, however I'm not sure how web applications work, does IIS open a thread for every user connected? if so, what would happend if my singleton is not thread safe? Also, is it OK to use a singleton pattern for the datacontext? Thanks.

    Read the article

  • Examples of IOC/DI over Singleton

    - by Amitd
    Hi, Just started learning/reading about DI and IOC frameworks. Also I read many articles on SO and internet that say that one should prefer DI/IOC over singleton. Can anyone give/link examples of exactly how DI/IOC eliminates/solves the various issues regarding the Singleton pattern? (hopefully code and explanation for better understanding) Also given a system has already implemented Singleton pattern, how to refactor/implement DI/IOC for the same? (any examples for the same?) (Language/Framework no bars..C# would be helpful) Thanks

    Read the article

  • Thread safe lazy contruction of a singleton in C++

    - by pauldoo
    Is there a way to implement a singleton object in C++ that is: Lazily constructed in a thread safe manner (two threads might simultaneously be the first user of the singleton - it should still only be constructed once). Doesn't rely on static variables being constructed beforehand (so the singleton object is itself safe to use during the construction of static variables). (I don't know my C++ well enough, but is it the case that integral and constant static variables are initialized before any code is executed (ie, even before static constructors are executed - their values may already be "initialized" in the program image)? If so - perhaps this can be exploited to implement a singleton mutex - which can in turn be used to guard the creation of the real singleton..) Excellent, it seems that I have a couple of good answers now (shame I can't mark 2 or 3 as being the answer). There appears to be two broad solutions: Use static initialisation (as opposed to dynamic initialisation) of a POD static varible, and implementing my own mutex with that using the builtin atomic instructions. This was the type of solution I was hinting at in my question, and I believe I knew already. Use some other library function like pthread_once or boost::call_once. These I certainly didn't know about - and am very grateful for the answers posted.

    Read the article

  • Singleton Pattern for C#

    - by cam
    I need to store a bunch of variables that need to be accessed globally and I'm wondering if a singleton pattern would be applicable. From the examples I've seen, a singleton pattern is just a static class that can't be inherited. But the examples I've seen are overly complex for my needs. What would be the very simplest singleton class? Couldn't I just make a static, sealed class with some variables inside?

    Read the article

  • How to create a true singleton in java?

    - by rjoshi
    I am facing a problem with my singleton when used across multiple class loaders. E.g Singleton accessed by multiple EJBs. Is there any way to create a singleton which has only one instance across all class loader? I am looking for pure java solution either using custom class loader or some other way.

    Read the article

  • Javascript 'class' and singleton problems

    - by Kucebe
    I have a singleton object that use another object (not singleton), to require some info to server: var singleton = (function(){ /*_private properties*/ var myRequestManager = new RequestManager(params, //callbacks function(){ previewRender(response); }, function(){ previewError(); } ); /*_public methods*/ return{ /*make a request*/ previewRequest: function(request){ myRequestManager.require(request); //err:myRequestManager.require is not a func }, previewRender: function(response){ //do something }, previewError: function(){ //manage error } }; }()); This is the 'class' that make the request to the server function RequestManager(params, success, error){ //create an ajax manager this.param = params; this._success = success; //callbacks this._error = error; } RequestManager.prototype = { require: function(text){ //make an ajax request }, otherFunc: function(){ //do other things } } The problem is that i can't call myRequestManager.require from inside singleton object. Firebug consolle says: "myRequestManager.require is not a function", but i don't understand where the problem is. Is there a better solution for implement this situation?

    Read the article

  • How to instantiate a Singleton multiple times?

    - by Sebi
    I need a singleton in my code. I implemented it in Java and it works well. The reason I did it, is to ensure that in a mulitple environment, there is only one instance of this class. But now I want to test my Singleton object locally with a Unit test. For this reason I need to simulate another instance of this Singleton (the object that would be from another device). So is there a possiblity to instantiate a Singleton a second time for testing purpose or do I have to mock it? I'm not sure, but I think it could be possible by using a different class loader?

    Read the article

  • What are the downsides of implementing a singleton with Java's enum?

    - by irreputable
    Traditionally, a singleton is usually implemented as public class Foo1 { private static final Foo1 INSTANCE = new Foo1(); public static Foo1 getInstance(){ return INSTANCE; } private Foo1(){} public void doo(){ ... } } With Java's enum, we can implement a singleton as public enum Foo2 { INSTANCE; public void doo(){ ... } } As awesome as the 2nd version is, are there any downsides to it? (I gave it some thoughts and I'll answer my own question; hopefully you have better answers)

    Read the article

  • should singleton be life-time available or should it be destroyable?

    - by Manoj R
    Should the singleton be designed so that it can be created and destroyed at any time in program or should it be created so that it is available in life-time of program. Which one is best practice? What are the advantages and disadvantages of both? EDIT :- As per the link shared by Mat, the singleton should be static. But then what are the disadvantages of making it destroyable? One advantage is it memory can be saved when it is not useful.

    Read the article

  • SSIS Design Pattern: Loading Variable-Length Rows

    - by andyleonard
    Introduction I encounter flat file sources with variable-length rows on occassion. Here, I supply one SSIS Design Pattern for loading them. What's a Variable-Length Row Flat File? Great question - let's start with a definition. A variable-length row flat file is a text source of some flavor - comma-separated values (CSV), tab-delimited file (TDF), or even fixed-length, positional-, or ordinal-based (where the location of the data on the row defines its field). The major difference between a "normal"...(read more)

    Read the article

  • Ocaml Pattern Matching

    - by Atticus
    Hey guys, I'm pretty new to OCaml and pattern matching, so I was having a hard time trying to figure this out. Say that I have a list of tuples. What I want to do is match a parameter with one of the tuples based on the first element in the tuple, and upon doing so, I want to return the second element of the tuple. So for example, I want to do something like this: let list = [ "a", 1; "b", 2"; "c", 3; "d", 4 ] ;; let map_left_to_right e rules = match e with | first -> second | first -> second | first -> second If I use map_left_to_right "b" list, I want to get 2 in return. I therefore want to list out all first elements in the list of rules and match the parameter with one of these elements, but I am not sure how to do so. I was thinking that I need to use either List.iter or List.for_all to do something like this. Any help would be appreciated. Thanks!

    Read the article

  • iPhone noob - setting NSMutableDictionary entry inside Singleton?

    - by codemonkey
    Yet another iPhone/Objective-C noob question. I'm using a singleton to store app state information. I'm including the singleton in a Utilities class that holds it (and eventually other stuff). This utilities class is in turn included and used from various view controllers, etc. The utilities class is set up like this: // Utilities.h #import <Foundation/Foundation.h> @interface Utilities : NSObject { } + (id)GetAppState; - (id)GetAppDelegate; @end // Utilities.m #import "Utilities.h" #import "CHAPPAppDelegate.h" #import "AppState.h" @implementation Utilities CHAPPAppDelegate* GetAppDelegate() { return (CHAPPAppDelegate *)[UIApplication sharedApplication].delegate; } AppState* GetAppState() { return [GetAppDelegate() appState]; } @end ... and the AppState singleton looks like this: // AppState.h #import <Foundation/Foundation.h> @interface AppState : NSObject { NSMutableDictionary *challenge; NSString *challengeID; } @property (nonatomic, retain) NSMutableDictionary *challenge; @property (nonatomic, retain) NSString *challengeID; + (id)appState; @end // AppState.m #import "AppState.h" static AppState *neoAppState = nil; @implementation AppState @synthesize challengeID; @synthesize challenge; # pragma mark Singleton methods + (id)appState { @synchronized(self) { if (neoAppState == nil) [[self alloc] init]; } return neoAppState; } + (id)allocWithZone:(NSZone *)zone { @synchronized(self) { if (neoAppState == nil) { neoAppState = [super allocWithZone:zone]; return neoAppState; } } return nil; } - (id)copyWithZone:(NSZone *)zone { return self; } - (id)retain { return self; } - (unsigned)retainCount { return UINT_MAX; //denotes an object that cannot be released } - (void)release { // never release } - (id)init { if (self = [super init]) { challengeID = [[NSString alloc] initWithString:@"0"]; challenge = [NSMutableDictionary dictionary]; } return self; } - (void)dealloc { // should never be called, but just here for clarity [super dealloc]; } @end ... then, from a view controller I'm able to set the singleton's "challengeID" property like this: [GetAppState() setValue:@"wassup" forKey:@"challengeID"]; ... but when I try to set one of the "challenge" dictionary entry values like this: [[GetAppState() challenge] setObject:@"wassup" forKey:@"wassup"]; ... it fails giving me an "unrecognized selector sent..." error. I'm probably doing something really obviously dumb? Any insights/suggestions will be appreciated.

    Read the article

  • Is there a design pattern for chained observers?

    - by sharakan
    Several times, I've found myself in a situation where I want to add functionality to an existing Observer-Observable relationship. For example, let's say I have an Observable class called PriceFeed, instances of which are created by a variety of PriceSources. Observers on this are notified whenever the underlying PriceSource updates the PriceFeed with a new price. Now I want to add a feature that allows a (temporary) override to be set on the PriceFeed. The PriceSource should still update prices on the PriceFeed, but for as long as the override is set, whenever a consumer asks PriceFeed for it's current value, it should get the override. The way I did this was to introduce a new OverrideablePriceFeed that is itself both an Observer and an Observable, and that decorates the actual PriceFeed. It's implementation of .getPrice() is straight from Chain of Responsibility, but how about the handling of Observable events? When an override is set or cleared, it should issue it's own event to Observers, as well as forwarding events from the underlying PriceFeed. I think of this as some kind of a chained observer, and was curious if there's a more definitive description of a similar pattern.

    Read the article

  • Is Structuremap singleton thread safe?

    - 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

  • Thread implemented as a Singleton

    - by rocknroll
    Hi all, I have a commercial application made with C,C++/Qt on Linux platform. The app collects data from different sensors and displays them on GUI. Each of the protocol for interfacing with sensors is implemented using singleton pattern and threads from Qt QThreads class. All the protocols except one work fine. Each protocol's run function for thread has following structure: void <ProtocolClassName>::run() { while(!mStop) //check whether screen is closed or not { mutex.lock() while(!waitcondition.wait(&mutex,5)) { if(mStop) return; } //Code for receiving and processing incoming data mutex.unlock(); } //end while } Hierarchy of GUI. 1.Login screen. 2. Screen of action. When a user logs in from login screen, we enter the action screen where all data is displayed and all the thread's for different sensors start. They wait on mStop variable in idle time and when data arrives they jump to receiving and processing data. Incoming data for the problem protocol is 117 bytes. In the main GUI threads there are timers which when timeout, grab the running instance of protocol using <ProtocolName>::instance() function Check the update variable of singleton class if its true and display the data. When the data display is done they reset the update variable in singleton class to false. The problematic protocol has the update time of 1 sec, which is also the frame rate of protocol. When I comment out the display function it runs fine. But when display is activated the application hangs consistently after 6-7 hours. I have asked this question on many forums but haven't received any worthwhile suggestions. I Hope that here I will get some help. Also, I have read a lot of literature on Singleton, multithreading, and found that people always discourage the use of singletons especially in C++. But in my application I can think of no other design for implementation. Thanks in advance A Hapless programmer

    Read the article

  • 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

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