Search Results

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

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

  • Singletons and constants

    - by devoured elysium
    I am making a program which makes use of a couple of constants. At first, each time I needed to use a constant, I'd define it as //C# private static readonly int MyConstant = xxx; //Java private static final int MyConstant = xxx; in the class where I'd need it. After some time, I started to realise that some constants would be needed in more than one class. At this time, I had 3 choises: To define them in the different classes that needed it. This leads to repetition. If by some reason later I need to change one of them, I'd have to check in all classes to replace them everywhere. To define a static class/singleton with all the constants as public. If I needed a constant X in ClassA, ClassB and ClassC, I could just define it in ClassA as public, and then have ClassB and ClassC refer to them. This solution doesn't seem that good to me as it introduces even more dependencies as the classes already have between them. I ended up implementing my code with the second option. Is that the best alternative? I feel I am probably missing some other better alternative. What worries me about using the singleton here is that it is nowhere clear to a user of the class that this class is using the singleton. Maybe I could create a ConstantsClass that held all the constants needed and then I'd pass it in the constructor to the classes that'd need it? Thanks

    Read the article

  • What is the difference between all-static-methods and applying a singleton pattern?

    - by shahensha
    I am making a database to store information about the users of my website (I am using stuts2 and hence Java EE technology). For the database I'll be making a DBManager. Should I apply singleton pattern here or rather make all it's methods static? I will be using this DBManager for basic things like adding, deleting and updating User profiles. Along with it, I'll use for all other querying purposes, for instance to find out whether a username already exists and to get all users for administrative purposes and stuff like that. My questions What is the benefit of singleton pattern? Which thing is most apt here? All static methods or a singleton pattern? Please compare both of them. P.S. The database is bigger than this. Here I am talking only about the tables which I'll be using for storing User Information.

    Read the article

  • Categories & singelton in cocoa

    - by Nava Carmon
    Hi, I have a SingletonClass, which has only one instance. I want to expand it and add to it a category (MoreFeatures). I created a source SingletonClass+MoreFeatures, which interface/implementation looks like that: @interface SingletonClass (MoreFeatures) - (void) feature; @end @implementation SingletonClass (MoreFeatures) - (void) feature() { } @end When I created my SingletonClass i followed the Apple's example of Singleton implementation in cocoa. This singleton resides in a project B, which is a dependency of a bigger project A. I can call for [[SingletonClass sharedInstance] foo] from a source in project A and it works in case that function foo is located in SingletonClass interface/implementation. When I try to call [[SingletonClass sharedInstance] feature] from a source in project A, I get a crash, which says that there is no method feature for class SingletonClass... Why it happens? Thanks a lot, Nava EDIT: The crash happens in a runtime. The category file source resides in project B along with a SingletonClass

    Read the article

  • are Hierarchical SIngletons in Java possible?

    - by Zach H
    I've been toying with an interesting idea (No idea if I'll include it in any code, but it's fun to think about) Let's say we have a program that requires a large number of classes, all of a certain subclass. And those classes all need to be singletons. Now, we could write the singleton pattern for each of those classes, but it seems wasteful to write the same code over and over, and we already have a common base class. It would be really nice to create a getSingleton method of A that when called from a subclass, returns a singleton of the B class (cast to class A for simplicity) class A{ public A getSingleton(){ //Wizardry } } class B extends A{ } A blargh = B.getSingleton() A gish = B.getSingleton() if(A == B) System.out.println("It works!") It seems to me that the way to do this would be to recognize and call B's default constructor (assuming we don't need to pass anything in.) I know a little of the black magic of reflection in Java, but i'm not sure if this can be done. Anyone interested in puzzling over this?

    Read the article

  • Question about singleton property

    - by Jack
    I'm reading the java tutorial for enums located here and have a question: http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html#Card The part i'm confused about is as follows: "The Card class, above, contains a static factory that returns a deck, but there is no way to get an individual card from its rank and suit. Merely exposing the constructor would destroy the singleton property (that only a single instance of each card is allowed to exist). Here is how to write a static factory that preserves the singleton property, using a nested EnumMap: " Now as I understand, changing the original private "Card" constructor to public would allow us to instantiate an unlimited number of copies of a "Card" object with a given suit+rank. The solution as proposed was to create an EnumMap which would store four Maps (one for each suit), which themselves contained 13 Card objects with the rank as their keys. And so now if you wanted to retrieve a specific Card object from the deck, you would just call the "valueOf" method. My question now is, what's the prevent you with calling the valueOf method as many times as you like? Wouldn't that lead to the same problem as making the original private constructor public? Thanks.

    Read the article

  • C# Unit Testing: How do I set a Lazy<T>.ValueCreated to false?

    - by michael paul
    Basically, I have a unit test that gets a singleton instance of a class. Some of my tests required me to mock this singleton, so when I do Foo.Instance I get a different type of instance. The problem is that my checks are passing individually, but failing overall because one test is interfering with another. I tried to do a TestCleanup where I set: Foo_Accessor._instance = null; but that didn't work. What I really need is Foo_Accessor._instance.IsValueCreated = false; (_instance is a Lazy). Any way to unset the Lazy object that I didn't think of?

    Read the article

  • What data (if any) persists across web-requests in Ruby on Rails?

    - by Daniel Beardsley
    I decided to use the singleton design pattern while creating a view helper class. This got me thinking; will the singleton instance survive across requests? This led to another question, Which variables (if any) survive across web requests and does that change depending on deployment? (Fastcgi, Mongrel, Passenger, ...) I know that Controller instance variables aren't persisted. I know Constants are persisted (or reloaded?). But I don't know about class variables, instance variables on a class, Eigenclasses, ...

    Read the article

  • singleton vs factory?

    - by fayer
    i've got 3 Log classes that all implements iLog interface: DatabaseLog FileLog ScreenLog there can only be one instance of them. initially i though of using single pattern for each class but then i thought why not use a factory for instantiation instead, cause then i wont have to create single pattern for each one of them and for all future Log classes. and maybe someone would want them as multiple objects in the future. so my questions is: should i use factory or singleton pattern here?

    Read the article

  • ObjectDataSource typename of a singleton Business object

    - by luppi
    My singleton business object is defined in Global: public class Global : HttpApplication { public static BusinessForm BusinessFormLayer; void Application_Start(object sender, EventArgs e) { FormDalProvider concreteProvider = FormDalProvider.Instance; BusinessForumLayer = new BusinessForum(concreteProvider); } } My page: <asp:ObjectDataSource ID="objThreads" runat="server" SelectMethod="GetForms" SelectCountMethod="GetFormsCount" TypeName="Global.BusinessFormLayer" EnablePaging="true" SortParameterName="sortExpression">

    Read the article

  • Session vs singleton pattern

    - by chobo
    Hi, I have a web application where I would like to pull user settings from a database and store them for Global access. Would it make more sense to store the data in a Singleton, or a Session object? What's the difference between the two? Is it better to store the data as an object reference or break it up into value type objects (ints and strings)? Thanks!

    Read the article

  • Java : Singleton class instances in a Web based Application

    - by Preethi Jain
    I have this Singleton class inside a Web Application . public class MyDAO { private static MyDAO instance; private MyDAO() { } public static MyDAO getInstance() { if (instance == null) { instance = new MyDAO(); } return instance; } I will access it this way public void get_Data() { MyDAO dao = MyDAO.getInstance(); } How many Objects of MyDAO class will be created if there are 3 Users accessing the Application ?? Will there be one instance of MyDAO per User ??

    Read the article

  • Spring singleton lifecycle

    - by EugeneP
    Reading this When a bean is a singleton, only one shared instance of the bean will be managed and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned. Will be managed... What does that mean? If there's only one object, than any modification to this object will result in that every another attempt to get this bean will return a modified instance??

    Read the article

  • 'Singleton' application - or let the user only launch one instance of a program at the time

    - by Disco
    I'm running a few linux desktops; mainly for kids (yeah, trying to teach them the right OS at early stage) (running Ubuntu 10.10, Gnome) The problem is that they found very funny to make their workstations (actually, old 512 Mb pentium 4) by launching thousands of firefox instances. I'm looking for a way to restrict them to launch 'N' instances of a particular application. Haven't figured yet how. Thought of a monitoring daemon but I think that would be too ressources hungry. Any idea of a script/trick to achieve this ? Note: i might have 1-2 level of users (the kids, and the more grown up kids) so i have also to limit per user; something like user1: 3firefox, user2: 2firefox instances.

    Read the article

  • The IOC "child" container / Service Locator

    - by Mystagogue
    DISCLAIMER: I know there is debate between DI and service locator patterns. I have a question that is intended to avoid the debate. This question is for the service locator fans, who happen to think like Fowler "DI...is hard to understand...on the whole I prefer to avoid it unless I need it." For the purposes of my question, I must avoid DI (reasons intentionally not given), so I'm not trying to spark a debate unrelated to my question. QUESTION: The only issue I might see with keeping my IOC container in a singleton (remember my disclaimer above), is with the use of child containers. Presumably the child containers would not themselves be singletons. At first I thought that poses a real problem. But as I thought about it, I began to think that is precisely the behavior I want (the child containers are not singletons, and can be Disposed() at will). Then my thoughts went further into a philosophical realm. Because I'm a service locator fan, I'm wondering just how necessary the notion of a child container is in the first place. In a small set of cases where I've seen the usefulness, it has either been to satisfy DI (which I'm mostly avoiding anyway), or the issue was solvable without recourse to the IOC container. My thoughts were partly inspired by the IServiceLocator interface which doesn't even bother to list a "GetChildContainer" method. So my question is just that: if you are a service locator fan, have you found that child containers are usually moot? Otherwise, when have they been essential? extra credit: If there are other philosophical issues with service locator in a singleton (aside from those posed by DI advocates), what are they?

    Read the article

  • Loading 2 Singletons With Dependencies when an app is opened (appDelegate / appDidBecomeActive) iPhone SDK

    - by taber
    I'm trying to load two standard-issue style singletons: http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html when my iPhone app is loaded. Here's my code: - (void) applicationDidFinishLaunching:(UIApplication *)application { // first, restore user prefs [AppState loadState]; // then, initialize the camera [[CameraModule sharedCameraModule] initCamera]; } My "camera module" has code that checks a property of the AppState singleton. But I think what's happening is a race condition where the camera module singleton is trying to access the AppState property while it's in the middle of being initialized (so the property is nil, and it's re-initializing AppState). I'd really like to keep these separate, instead of just throwing one (or both) into the App Delegate. Has anyone else seen something like this? What kind of workaround did you use, or what would you suggest? Thanks in advance! Here's the loadState method: + (void)loadState { @synchronized([AppState class]) { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *file = [documentsDirectory stringByAppendingPathComponent:@"prefs.archive"]; Boolean saveFileExists = [[NSFileManager defaultManager] fileExistsAtPath:file]; if(saveFileExists) { sharedAppState = [[NSKeyedUnarchiver unarchiveObjectWithFile:file] retain]; } else { [AppState sharedAppState]; } } }

    Read the article

  • Monotouch threads, GC, WCF

    - by cvista
    Hi This is a question about best practices i guess but it applies directly to my current MT project. I'm using WCF services to communicate with the server. To do this i do the following: services.MethodToCall(params); and the asynch: services.OnMethodToCallCompleted += delegate{ //do stuff and ting }; This can lead to issues if you're not careful in that variables defined within the scope of the asynch callback can sometimes be cleaned up by the gc and this can cause crashes. So - I am making it a practice to declare these outside of the scope of the callback unless I am 100% sure they are not needed. Now - when doing stuff and ting implies changing the ui - i wrap it all in an InvokeOnMainThread call. I guess wrapping everything in this would slow the main thread down and rubbish the point of having multi threads. Even though I'm being careful about all this i am still getting crashes and I have no idea why! I am certain it has something to do with threads, scope and all that. Now - the only thing I can think of outside of updating the UI that may need to happen inside of InvokeOnMainThread is that I have a singleton 'Database' class. This is based on the version 5 code from this thread http://www.yoda.arachsys.com/csharp/singleton.html So now if the service method returns data that needs to be added/updated to the Database class -I also wrap this inside an InvokeOnMainThread call. Still getting random crashes. So... My question is this: I am new to thick client dev - I'm coming from a web dev perspective where we don't need to worry about threads so much :) Aside from what I have mentioned -are there any other things I should be aware of? Is the above stuff correct? Or am i miss-understanding something? Cheers w://

    Read the article

  • Encapsulate update method inside of object or have method which accepts an object to update

    - by Tom
    Hi, I actually have 2 questions related to each other: I have an object (class) called, say MyClass which holds data from my database. Currently I have a list of these objects ( List < MyClass ) that resides in a singleton in a "communal area". I feel it's easier to manage the data this way and I fail to see how passing a class around from object to object is beneficial over a singleton (I would be happy if someone can tell me why). Anyway, the data may change in the database from outside my program and so I have to update the data every so often. To update the list of the MyClass I have a method called say, Update, written in another class which accepts a list of MyClass. This updates all the instances of MyClass in the list. However would it be better instead to encapulate the Update() method inside the MyClass object, so instead I would say foreach(MyClass obj in MyClassList) { obj.update(); } What is a better implementation and why? The update method requires a XML reader. I have written an XML reader class which is basically a wrapper over the standard XML reader the language natively provides which provides application specific data collection. Should the XML reader class be in anyway in the "inheritance path" of the MyClass object - the MyClass objects inherits from the XML reader because it uses a few methods. I can't see why it should. I don't like the idea of declaring an instance of the XML Reader class inside of MyClass and an MyClass object is meant to be a simple "record" from the database and I feel giving it loads of methods, other object instances is a bit messy. Perhaps my XML reader class should be static but C#'s native XMLReader isn't static.? Any comments would be greatly appreciated Thanks Thomas

    Read the article

  • How to call a wpf singleton service within a wpf singleton service without hanging?

    - by Michael Hedgpeth
    I have two services, one that calls another. Both are marked as singletons as follows: [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)] public class Service : IService And I set these up with a ServiceHost as follows: ServiceHost serviceHost = new ServiceHost(singletonElement); serviceHost.Open(); When the parent service tries to call the child service on the same machine, the parent service hangs, waiting for the child service. I'm already considering moving away from the singleton model, but is there anything wrong with my approach? Is there an explanation for this behavior and a way out of it?

    Read the article

  • How to call a WCF singleton service within a WCF singleton service without hanging?

    - by Michael Hedgpeth
    I have two services, one that calls another. Both are marked as singletons as follows: [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)] public class Service : IService And I set these up with a ServiceHost as follows: ServiceHost serviceHost = new ServiceHost(singletonElement); serviceHost.Open(); When the parent service tries to call the child service on the same machine, the parent service hangs, waiting for the child service. I'm already considering moving away from the singleton model, but is there anything wrong with my approach? Is there an explanation for this behavior and a way out of it?

    Read the article

  • Singleton array deallocated? EXC_BAD_ACCESS

    - by lclaud
    Ok, so I have this singleton object and in it is an array that needs to be shown in a tableview. The thing is that it deallocates and after the first show, i get EXC_BAD_ACCESS in cellForRowAtIndexPath - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [[dataBase shareddataBase].dateActive count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"celula"]; int i; i=indexPath.row; if (cell==nil) { cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"celula"]; } count sent to dealocated instance of CFArray .. in cellForRowAtIndexPath.. WHAT is deallocating it? why? it's declarea as an NSMutableArray and has a (nonatomic,retain) property defined .. if ((i<[[dataBase shareddataBase].dateActive count])&&(i>=0)) { NSDictionary *d=[[dataBase shareddataBase].dateActive objectAtIndex:i]; cell.textLabel.text=[d objectForKey:@"detaliu"]; } return cell; }

    Read the article

  • Compile Error Using singleton - iPhone SDK

    - by mrburns05
    Since someone here is a bit hot-headed and deleted my last question ill post a new one with a title to better please his ego...Hows this Michael? Anyways, im getting this error when i compile: Undefined symbols: "_OBJC_CLASS_$_SortedItems", referenced from: __objc_classrefs__DATA@0 in SortedByNameTableDataSource.o ld: symbol(s) not found collect2: ld returned 1 exit status Basically i followed apples "TheElements" sample app to create the singleton, tableview datasource and just changed some stuff around to suit my needs - ive triple checked all my code and cannot figure out why im getting this.. If anyone can help please do, it would be much appreciated. if more of my code is needed ill post.. let me know

    Read the article

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