FAQ Database Discussion Community


How to set NSDictionary in SingleTon class in swift language

ios,swift,ios8,xcode6,singleton
Am newbie to swift language. I want to store my login response from a dictionary in singleton class. Whenever i want that data, i want to reuse it from dictionary in singleton class. Please find my mistakes. Herewith i attached my sample code. My SingleTon Class class MarblesSingleton: NSObject {...

Scala Script Engine creating another instance of a singleton

java,scala,singleton,jsr223
So, I'm creating a scripting system using JSR 223 for Scala, but I came across this problem I can't find any cause for. There is a singleton-like class, which has methods to add event listeners (from the scripts) and dispatch events (from the core). Everything worked fine, but for some...

Singleton and Interface implementation

c++,interface,singleton
I have an interface class Interface with pure virtual methods. class Interface { public: virtual void DoSomething() = 0; } Also, there is a class Implementation that implements the interface. class Implementation : public Interface { void DoSomething(); } In my program I need to have a Singleton (single instance)...

Singleton: is there a memory leak?

c++,memory-leaks,singleton
This is a simple singleton: class Singleton { Singleton(); virtual ~Singleton(); Singleton * Singleton::getInstance() { static Singleton * instance; if (!instance) { instance = new Singleton(); }; return instance; }; } When main code calls Singleton::getInstance()->someMethod() for the first time, isn't the class instantiated twice? Will be there memory leak?...

How to call a singleton method from a Java POJO?

java,methods,interface,singleton,instance
I wondered if it would be possible to call from a POJO a singleton bean's method through its interface. Maybe this idea is wrong or the architecture...but this is what I would like to accomplish if it is possible, because this is the architecture of the project. I notice that...

Static Constructor and singleton

c#,design-patterns,singleton
My friend told me that the following is one of the ways to create singleton design pattern in C# public class class1{ public static class1 Obj { get; private set; } static class1() { Obj = new class1(); } } He told me that the static constructor runs only one...

Is this a correct use of double checked singleton?

java,static,singleton,wrapper,double-checked-locking
I am basically looking for a caching mechanism for the users of HelperWrapper. Is this a correct use of double checked singleton? final class HelperWrapper {   private static volatile Helper helper = null;     public static Helper getHelper() {     if (helper == null) {       synchronized (HelperWrapper.class) {         if (helper ==...

Singleton object in java play! framework

java,web-applications,playframework,singleton
I'm really new to the Play! framework and I'm having troubles. Basically I'm making a web app whose first action is to read a Model from a file, I only need to do this once and never again, but this model has to be available for the controllers in the...

Garbage Collector: Taking care of object with a reference to singleton

c#,asp.net-web-api,garbage-collection,singleton
Imagine such situation: you have a singleton object and a class that has a field that points to this singleton public class MyClass { private readonly MySingleton singleton = MySingleton.Instance; ... } And now you have an WebApi Controller and in every request you are creating new object of type...

ClickOnce not passing second Uri

c#,wpf,singleton,clickonce
We have a WPF application, which uses WindowsFormsApplicationBase class to make it singleton; and is deployed using ClickOne. Whenever we wanted to execute this exe, we invoke it through Uri (deployed directory in server with query string). All works fine only for first instance of this application. Problem: ClickOnce always...

@PostConstruct called twice on simple @Singleton @Startup bean

java,singleton,ejb,startup,postconstruct
my problem is that the @PostConstruct is called twice even though it shouldn't. I searched a lot and found similiar problems with jersey https://java.net/jira/browse/JERSEY-1883?filter=-3. However I tried to make a small example which apparently still causes the problem even without any clatter. import javax.annotation.PostConstruct; import javax.ejb.Singleton; import javax.ejb.Startup; @Singleton @Startup...

iOS Swift : EXC_BAD_ACCESS(code=EXC_i386_GPFLT ) regarding a singleton

ios,objective-c,swift,singleton
My iOS app is returning this error. EXC_BAD_ACCESS(code=EXC_i386_GPFLT ) This is occuring on return Singleton.instance Here is the code regarding the singleton I am using. class var sharedData : SharedData { struct Singleton { static let instance = SharedData() } return Singleton.instance } Can someone help me understand this error...

Returning a reference from a pointer

c++,pointers,c++11,reference,singleton
I have this class in singleton.h: class SingletonSample { public: static SingletonSample& Instance(); int DoSomething() const; private: SingletonSample(); ~SingletonSample(); SingletonSample(const SingletonSample&) = delete; SingletonSample& operator=(const SingletonSample&) = delete; static SingletonSample* _instance; } And I have this implementation in singleton.cpp: SingletonSample::SingletonSample() {} SingletonSample::~SingletonSample() {} SingletonSample& SingletonSample::Instance() { if(!_instance) _instance = new...

Function pointer to singleton class instance function

c++,oop,pointers,singleton
What I'm trying to do is create a function pointer to a single class instance function. I want to do this so I can do something like this: C->member_method(); instead of: Config::inst()->member_method(); but I'm not sure how to go about it. Here is my singleton class: class Config { private:...

lazy loaded Singleton - will a static field call cause instantiation

java,singleton
i have the following what you might call a lazy loaded singleton per the definition: public class MySingleton { public static String myTrigger="a trigger"; private MySingleton(){ } private static enum LazyLoad { IMDB_LOOKUP_INSTANCE; private static final IMDB_LOOKUP = new MySingleton(); } public static MySingleton getInstance() { return LazyLoad.IMDB_LOOKUP_INSTANCE.IMDB_LOOKUP; } }...

Updating a singleton from daemon thread

android,multithreading,service,singleton
I have a singleton where I store shared information used from different fragments. On the other hand, I have a service that spawns a daemon thread. This thread connects to an event bus and is resposible to receive events from a external server. When it receives a new event, updates...

How to get the get(…) index manually

java,android,singleton
I have the following problem. I think it's, at least, interesting. And I would like to find a solution too :) I have an internal array of users that, for some reasons, is storing the images of each user in a singleton class. This singleton class is storing correctly each...

Thread synch and singleton questions

java,multithreading,synchronization,locking,singleton
First off I need to clear something basic, assume I have a synchronized block or a synchronized method and one thread already entered the synchronized part and 5 new threads try to access the synchronized part, will they stop running until the first thread leaves the synchronized part? and if...

Singleton Pattern with a public constructor

php,oop,design-patterns,singleton
I want to implement Singleton Design Pattern to a class which extends another class with a public constructor in PHP. For example, consider a class, say Animal: class Animal { public function __construct() { } } I want to implement Singleton Design Pattern to a class which extends Animal, for...

Shared instance with global variables

ios,objective-c,static,singleton,global-variables
Thanks to some previous questions I managed to share global variables in my whole application. But still I'm wondering if what I've done is a good practice : GlobalVariables.h @interface GlobalVariables : NSObject @property (nonatomic, retain) NSMutableArray *eventType; @property (nonatomic, retain) NSMutableArray *docType; // Getters of properties + (NSMutableArray *)...

meaning and location of string inside Magento's Mage:getSingleton

magento,singleton
Here is a string I see a lot of similar in Magento: Mage::getSingleton('checkout/type_onepage'); However, I'm trying to find out where that class is located, and what the meaning of the string is specifically. Can anyone explain this to me?...

How does a singleton property with a lock ensure thread safety?

c#,multithreading,design-patterns,locking,singleton
I rarely use singletons, in this case it's appropriate. While trying to investigate the best implementation thereof I came across this bit of code which has left me believing I improperly understand how brackets encapsulate a "scope." public sealed class Singleton { private static Singleton instance = null; private static...

how do I call sibling functions in a singleton class?

javascript,object,singleton,siblings
In the following code, .refresh could call .add, but I get Uncaught TypeError: undefined is not a function My guess is because it is not defined at the time class is created, but if this is true, without replicating the code, is there a way to call a sibling public...

Objective C protocol method is not called

objective-c,singleton,protocols,avaudioplayer
I have created singleton class for AVAudioPlayer. I am able to call the methods in the class and everything works fine. When the song finishes,the method (void)audioPlayerDidFinishPlaying is called which in turn suppose to call the method ' processSuccessful' in my downloadPlay.m class. But, it is not calling the method...

Spring MVC refresh database beans in application context

spring,singleton,refresh,javabeans,apache-commons-dbcp
I am developping a Spring MVC web application that use the dbcp database connection pool. <bean id="datasourceAR_XXX" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" scope="singleton"> <property name="driverClassName"><value>oracle.jdbc.driver.OracleDriver</value></property> <property name="url"><value>jdbc:oracle:thin:@XXX.XXX.com:1500:SERVICE</value></property> <property name="maxActive"><value>100</value></property>...

Best way to pass a ConcurrentHashMap to another class?

java,thread-safety,singleton,concurrenthashmap
I have a handler class that contains a private ConcurrentHashMap which other classes want, but I'm not sure the best way to give it to them. My apparent options are.. Return the entire ConcurrentHashMap (sample code below--this sounds dangerous to me, given that CHMs are meant to be used by...

How do I use Autofac instead singleton in c#?

c#,asp.net-mvc,c#-4.0,singleton,autofac
I have used singleton pattern a using static property, constructor public class MyClass { private readonly MemoryCacheManager _cacheManager; private static readonly Lazy<MyClass> _Lazy = new Lazy<MyClass>(() => new MyClass()); public static MyClass Language { get { return _Lazy.Value; } } private MyClass() { _cacheManager = new MemoryCacheManager(); LoadCacheData(); } //...

How to refactor a singleton class and avoid doing the same mistakes again

c#,design-patterns,design,singleton,static-classes
I've started a small application in WPF and used a Singleton class to handle all the application logic. Plus I had a few ObservableCollections there that are binded to DataGrids on the View. The problem: what was supposed to be a small program started to grow in functionality and the...

How to guarantee only one instance of a class through singletons

java,singleton
I've just learnt about the use of singletons and I'm struggling to see how they could be used to limit object instantiation to only one. I found the following example on a tutorial website: public class Singleton { private static Singleton singleton = new Singleton( ); private Singleton(){ } public...

Swift - Issue trying to access to Singleton object

swift,design-patterns,ios8,singleton,apple
This is my first question on StackOverflow, I'll try to be specific. I am trying to implement the Singleton pattern on my app, without success so far. When I try to access to my Singleton, it seems that the program is not accessing the real singleton, but a copy of...

Objective C singleton class members

objective-c,osx,singleton
This is for a Mac OS X app. I have created a singleton class, but I'm not sure how to add class members (not sure if this is the correct term). I am getting the error Property 'chordDictionary' not found on object of type '__strong id' and I'm not sure...

trying to implement simple ostream singleton class

c++,singleton,iostream
I want to implement a singleton class that receives file path as a parameter. I tried to write the following code . I know it doesn't work and not good but I can't find why.. class OutputData { std::fstream ofile; std::ostream iout; static OutputData *odata; OutputData(const char* path):iout(std::cout), ofile(path) {...

Is using singleton pattern in angularjs a bad practise?

javascript,angularjs,singleton,frontend
I have been coding in Angular JS for a while now. A friend of mine suggested me not to use singleton pattern in AngularJS, as it is a bad practise. I was totally unaware of that. Is it so?

In Node.js is there a way to access the variable scope of the parent from a required module?

javascript,node.js,singleton
For my project, I have many functions make changes to a single global variable, but since the file is very big, i would like to split these functions into different modules. however, when passing the global variable, it creates another instance. is there a way to prevent this? for example,...

Is using a Observable Singleton Class to handle network calls bad?

java,sockets,design-patterns,singleton,observable
I have to develop a client/server game that uses a lot of network request to complete its task. Both the client and the server receive multiple Command through socket. To handle these commands I created a NetworkHandler class that listens for new Input on a separate thread and that allow...

CollectionViewSource to be bind to a property in a singleton

c#,wpf,xaml,singleton,collectionviewsource
I have such a singleton class public class Sample { private static readonly Lazy<Sample> lazy = new Lazy<Sample>(() => new Sample()); private ObservableCollection<SampleGroup> _groups; public ObservableCollection<SampleGroup> Groups { get { return _groups; } } } I bind the Groups property to a ListView by this, <Window.Resources> <!-- Data Source For...

What s the difference between singleton and plugin?

javascript,jquery,plugins,singleton
I want to know: What is the difference between singleton and plugin?

visual studio cannot resolve static functions

c++,visual-studio,linker,singleton,static-functions
Here is the code and the output. win_main.cpp #include <Windows.h> #include <tchar.h> #include "d3d9_object.h" #pragma comment(lib, "d3d9.lib") #pragma comment(lib, "d3dx9.lib") LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); WNDCLASSEX createWndClassEx(HINSTANCE); HWND createWindow(const wchar_t *caption, HINSTANCE); void exitWithFailure(const wchar_t *message, HINSTANCE); const wchar_t gszWndClassName[] = L"MainWindowClassName"; WNDCLASSEX gWndClassEx; int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE,...

Prolog- singleton variable in branch warning

variables,prolog,singleton
Hello here is my code in Prolog: arc(a,h). arc(b,c). related_to(X, Ys) :- setof(Y, arc(X, Y), Ys). cut([H|T],Y) :- check(H,Y), T = [] -> cut(T,Y). check(X,Y) :- related_to(X,Xs), member(Y,Xs) -> write('There is a road'); cut(Xs,Y). When I am trying to run check(a,b) it doesn't run. I get the message Singleton variable...

how can I recreate singleton class in java

java,android,singleton
I thought I wrote it right, but I dont follow where the mistake is. I create a singleton class (of ringbuffer using apache commons); this is used in mainactivity and guimanager (both are my implementation)-hence a singleton class for ringbuffer. Above classes get the reference for singleton by calling RingBuffer.getInstance()...

Java Singleton Design Pattern implementation [duplicate]

java,design-patterns,singleton
This question already has an answer here: How to write a Singleton in proper manner? 11 answers Can the implementation for a Singleton class can be as simple as below : public class MyClass { private final static MyClass myClass = new MyClass(); private MyClass() {} public static MyClass...

Ninject Singleton vs CS Singleton

c#,singleton,ninject
Can someone please tell me the difference between a C# Singleton Class and a Ninject Singleton? My current boss would like to convert a Singleton class into a Ninject Singleton. This goes against methodology for me that I would have Ninject define the singleton rather than the class itself define...

Cant get value from struct wrapped in NSValue

ios,objective-c,audio,struct,singleton
I need to pass a struct AudioStreamBasicDescription to a random view controller. In order to that I have created a singleton class and I want to store AudioStreamBasicDescription in that singleton class. When the other view controller needs to use the AudioStreamBasicDescription I want to get the values inside of...

Are Kotlin's singletons thread safe?

thread-safety,singleton,kotlin
Are Kotlin singletons (more specifically, object declarations) thread-safe by construction? If not, what is the best practice to write thread safe singletons in Kotlin? I would guess they are, but I haven't been able to find any explicit statement about it in the docs....

Defining Macros that are equal to functions that return objects in C++

c++,static,macros,singleton
So I have the singleton pattern working the way I want to, I think the main problem is something with pointers and refrences. ("..." represents irrelevent code). Universe.h ... #define TheUniverse Universe::GetInstance (); ... public: static Universe& GetInstance (); ... private: static Universe* x_instance; ... Universe.cpp ... Universe* Universe::x_instance =...

Swift Singleton not Working

swift,singleton
Trying to get a Singleton class going in Swift. I'm not getting any errors, but its also just plain not working properly. Here's the code: // The Singleton class: class DataWarehouse { class var sharedData:DataWarehouse { struct Static { static var onceToken : dispatch_once_t = 0 static var instance :...

Implementing enum-based singleton

java,enums,singleton
J. Bloch in his Effective Java suggests we use an enum-based singleton implementation. For instance: public enum Application { INSTANCE; //methods, fields } This implementation is nice in the case of serialization because enums provide us with the capability of serialization by default (and we don't have to be afraid...

concurrent user read and update to mysql using c#

c#,mysql,singleton,record-locking
I have a problem on my program, by solving this issue, it maybe can be done by using singleton method. But, i read from some article, they said,it is not a good way to implement it as the asp.net application concurrent users might have a lot. My problem is,system running...

How to create a singleton class using enum

java,enums,singleton
I am trying to create a singleton class in Java. The best available solution with Java5 and above versions seems to be using enum. But I am not sure how to convert my class into a singleton class using enum. Following is my simplified class: public class Employee { private...

processes & singleton in Android

android,singleton,android-service
Three questions concerning processes in Android. I am developing one app. If I declare a service to be running in another process in AndroidManifest.xml <service android:name=".MyService" android:process=":MyProcess"/> Does it mean there will be two JVM instances , one used by MyService while the other one used by other code? If...

C# singleton pattern in a static class?

c#,static,singleton
My event dispatcher class loosely couples instances of other classes by implementing sort of signals-slots design pattern. Only one unique event dispatcher is supposed to exist in an application. Since my Dispatcher class – which does all the work – inherits from Dictionary<TKey, TValue>, it cannot be declared static. To...

unrecognized selector sent to class when create a singleton object

ios,singleton
I have a shared class .h ` #import <Foundation/Foundation.h> @interface ArraysClass : NSObject @property(nonatomic,copy)NSMutableArray *mutArraySongs; +(ArraysClass *)SharedManager; @end ` .m ` #import "ArraysClass.h" @implementation ArraysClass static ArraysClass *sharedService = nil; #pragma mark - #pragma mark Singleton Methods +(ArraysClass *)sharedManager { if(sharedService == nil){ sharedService = [[super allocWithZone:NULL] init]; } return...

Can't add object to NSMutableArray in singleton

ios,xcode6,singleton,nsmutablearray
I made a singleton and i'm trying to add objects to self.timelineArray but i can't. When i do this i have 9 objects: NSNumber* nmb = [[NSNumber alloc] initWithInt:1]; [self.dataManager.timelineArray addObject:nmb]; After i insert the nmb object, i still have 9 objects. Here's my singleton header (only important bits): @interface...

Can I set a final variable in Java with a result of a divison? [duplicate]

java,static,singleton,final
This question already has an answer here: Why the result of 1/3=0 in java? 10 answers I want to have a global-scale variable, so some graphical objects can always have the same size in relation to the window. My idea: public static final double GLOBALSCALE = SCREENWIDTH / 1920;...

Trying to implement singleton gives me stackoverflow error c#

c#,asp.net,singleton
I am trying to make a singleton to account all the controllers I am going to create. When I run the website I get the stackoverflow error. This is my singleton class: public class MainController { private DatabaseController databaseController; private UserDBController userDBController; private static MainController MCinstance = null; public MainController()...

Using a Singleton to pass data in Watchkit

swift,singleton,watchkit
I've used a Singleton in IOS with success before, but the same approach isn't working for me in watchkit...any idea why my second interface controller displays 0 (initialized value) instead of the numbers entered in the first interface controller? class Singleton { static let instance = Singleton() var salesPriceAsInt: Int...

What is the difference between a class wrapper and Java, and a singleton in Objective-C?

java,ios,objective-c,singleton,wrapper
I hear the term "Class Wrapper" float around a lot, and I was curious what it is. I read explanations on this site about them, and they basically you just sound like a Singleton and Objective-C. My two questions are: 1. What is the difference between a singleton in the...

Why declare all instance fields transient in singletons? [duplicate]

java,serialization,singleton,effective-java
This question already has an answer here: transient for serializing singleton 3 answers To make a singleton class that is implemented using either of the previous approaches serializable (Chapter 11), it is not sufficient merely to add imple- ments Serializable to its declaration. To maintain the singleton guarantee, you...

Singleton in swift is not accessible from another class

swift,singleton
I am new to Swift and am trying to access a 'problemSolved' array that is appended during gameplay in my main GameController class, from another class. For some reason the array is not visible in a UIViewController class where I want to show all the problems solved in a table....

WCF singleton service with multiple endpoints?

wcf,serialization,singleton,wcf-endpoint
I have a singleton wcf service (InstanceContextMode.Single) i.e MyService with multiple endpoints namely netmsmq and http. The call to netmsmq works fine but when I call it as : Binding bin = new BasicHttpBinding(); EndpointAddress end = new EndpointAddress("http://localhost/WcfService1/MyService.svc"); var obje = new ChannelFactory<IMyService>(bin, end); obje.Open(); var factory = obje.CreateChannel();...

Singleton classes with inheritance - Ruby ( I think)

ruby,singleton,class-variables
I'm trying to use Ruby classes that are never instantiated, but still have the concept of inheritance.So looking at the code below, I have class "Room" that allows access to variables without instantiating the class (I have them as instance variables, but I'm not sure that's correct). But I want...

How to create object/singleton of generic type in Scala?

scala,generics,singleton
In below code, How can I convert EmptyTree to object ( Singleton) ? trait Tree[T] { def contains(num: T): Boolean def inc( num: T ): Tree[T] } class EmptyTree[T <% Ordered[T] ] extends Tree[T] { def contains(num:T):Boolean = false def inc(num:T):Tree[T] = { new DataTree(num, new EmptyTree, new EmptyTree) }...

What's wrong when not using singleton pattern

java,design-patterns,singleton
I'm reading about the singleton pattern from my ebook (Head First Design Patterns), and I know that using this pattern is suitable in case you need only one instance of some class. But I have a little trouble with the problem introduction in this ebook. (Yeah, I think I can...

django rest-framework singleton ViewSet

python,django,singleton,django-rest-framework
I need to pass a set of config-settings (key-value pairs) through the django rest_framework to an api-enpoint. Read-only is fine. Django 1.7, Python3 and rest-framework v3.0.5. I have pip installed django-solo, and I can access to it in the admin section, so I assume it works. I have set up...

Is using a singleton to store data incorrect in android?

android,singleton,data-persistence
This is a practice I've been using for a while now, but it seem to be deprecated, the literature seems to say that the correct way to save and restore data when the screen goes to the background or rotates is fragments. I would like your opinion on this What...

Preventing a class method from executing more than once at a time

c#,asp.net-mvc,dependency-injection,singleton
I have a asp.net mvc controller that when executed calls a method in a service class to open a file and start the import of records into a database. I'd somehow like to restrict this method or class so that another instance can't be created and prevent the method from...

How to close the PDO connection in php singleton class

php,pdo,singleton
I have a singleton class for PDO, below is the relevant part of the class public static function getInstance( $config ) { if ( ! isset(self::$instance)) self::$instance = new self( $config ); return self::$instance; } public function __construct( $config ) { self::$start = self::timer(); try { $host = $config['host']; $dbname...

Accessing properties of enclosing class

singleton,kotlin
How do I access the properties of an enclosing class? I am working with singletons in Kotlin. private object IndeterminateAnimationListener : Animation.AnimationListener { override fun onAnimationStart(animation: Animation?) {} override fun onAnimationEnd(animation: Animation?) { // How do I access the properties of the enclosing // from here? } override fun onAnimationRepeat(animation:...

How to instantiate a child singleton of an abstract class?

php,singleton,abstract-class
I have an abstract class and a child that extends the abstract class. The child is supposed to be a sigleton. Here is simplified example of the abstract class: abstract class AbstractClass{ protected static $instance = NULL; abstract protected function meInit(); private function __construct(){ $this->meInit(); $this->init(); } private function __clone(){}...

How to access a singleton from other classes C++

c++,class,singleton
I can't find any answer to this question for C++ (for other languages yes) though I've searched for a number of hours. How can I access a Singleton from another class? Declaration: #include "Store.h" Store *store = Store::Instance(); // Singleton int main() { store->GetDepts(); return 0; } I want to...

VollyError return null on below API Leval 21 android

android,singleton,android-volley
I am Using volley as networking library for my android application. Now mainly i want to handle two type of error 1. Authentication 2. Network Error Below snippet code work perfectly on Lollipop. But when i run application on lower API 21 then object of VolleyError return null. public Response.ErrorListener...

Tryning to understand when and when to not use a singleton

ios,design,singleton
There is a lot of information about singletons, when to use it, why you shouldn't use it etc. So in hope of grasping it somewhat better maybe someone can explain it with a sample from an app I'm making. I'm using Parse to create an app with user registration. If...

Singleton injection order

java-ee,dependency-injection,singleton,ejb,ejb-3.0
I have the following: @Singleton public class A { @Inject private B b; @PostConstruct void initialize(){ b.someMethod(); } } @Singleton public class B { } Can we be sure that B will always be injected before A?...

Singleton session bean

java-ee,singleton,ejb,ejb-3.1,session-bean
Singleton session bean has been introduced to address what problems ?? is it only for sharing the data that is common for all the beans ?? How that problem is managed in ejb 3.0 and versions before that ? If it retains the client specific conversational state , that...

How to define Singleton in TypeScript

singleton,typescript
What is the best and most convenient way to implement a Singleton pattern for a class in TypeScript? (Both with and without lazy initialisation).

Is Lazy a good solution for a thread safe lazy loaded singleton?

c#,multithreading,singleton
We implemented a lazy loaded singleton using double locking on get to make sure the instance is only initialized once (and not twice due to thread race conditions). I was wondering if simply using Lazy<T> is a good solution for this problem? I.E. private static Lazy<MyClass> _instance = new Lazy<MyClass>(()...

How to Implement Singleton Pattern without Nullable

design-patterns,singleton,hhvm,hacklang
I am trying to implement the Singleton pattern in Hack. However, I keep running into issues with Nullable. <?hh //strict class Foo { private static Foo $foo; public function __construct() { // Do stuff here. } public static function theFoo(): Foo { if (null === self::$foo) { self::$foo = new...

GeoFenceController with CLLocationManager as singleton?

ios,singleton,cllocationmanager,locationmanager,geofencing
I have a GeoFence class. I'm debating myself whether or not it should be a singleton. My code works either way and I have read a couple of articles and posts here on SO about it. But I didn't find any good rules for when it is correct to use...

Explaining the following statement in Java

java,design-patterns,singleton
I would like you guys to help me out with the following things in this program. I am a beginner in java so would appreciate any help on this: What does this means? private static Singleton singleton = new Singleton Are we creating a variable with type as class. I...

Why two constructors in this singleton code example

c#,constructor,singleton
I need to implement a singleton pattern in code and found this version (#4) that seems to fit my needs. public sealed class Singleton { private static readonly Singleton instance = new Singleton(); // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static Singleton()...

how to implement ads on 2 view controllers

singleton,admob,viewcontroller,banner,didfailwitherror
I want the iAd/AdMob mediation banner to NOT be affected by what ViewController I'm in. Currently. When I change View Controllers didFailToReceiveAdWithError is called and the AdMob banner in that method appears when I change ViewControllers. I use 2 ViewControllers for my entire app, so is there a way to...

Passing Variables to a Golang Package

design,go,singleton
Given a package containing the following local variable and functions: var bucket *gocb.Bucket func Init(b *gocb.Bucket) { bucket = b } func DoSomething() { // do something with 'bucket' } Is it acceptable to call the Init function, passing in an instance of bucket, before calling DoSomething, which is dependent...

Should I cache a comparer in a static field?

c#,.net,performance,singleton,icomparer
I have added the following property to my ApplicationUser class, which is supposed to return current user on top of other results. public static IComparer<string> IdComparer { get { return Comparer<string>.Create((x, y) => { var curUser = HttpContext.Current.User; if (curUser != null) { var curId = curUser.Identity.GetUserId(); if (x ==...

Make a factory not Singleton in angularJS

javascript,angularjs,singleton,factory
UPDATE: Thanks for your reply! I've rewritten my code: (function () { 'use strict'; angular .module('Services', []).factory('services', ['$http', function($http,services) { function services($http) { var serviceProvider = function () { this.data = []; this.errors = []; } var model = { getInstance:function(){ return new serviceProvider(); } } serviceProvider.prototype.init = function(){//put some...

Closing connections in java application which uses singleton frames

java,swing,singleton,database-connection
I am creating a java application using SwingGUI. I have used singleton classes for frames (to avoid creation of multiple frames). Also, the class uses database connectivity. Now, at the start of the application (HomeScreen), I have created and initialised the DB connection and close it when the app is...

How to properly call singleton implementation

c#,model-view-controller,singleton
I have got this singleton implementation in MVC project: public sealed class Singleton<T> where T : class { private static volatile T _instance; private static object _lock = new object(); static Singleton() {} public static T Instance { get { if (_instance == null) lock (_lock) { if (_instance ==...

Boost unit test dynamic linking on Ubuntu

c++,ubuntu,singleton,dynamic-linking,boost-unit-test-framework
I am trying to build a unit test using Boost's unit test framework. I would like to dynamically link test suite libraries with the auto generated test module that Boost provides. Here is the basic construction I've been using: test_main.cpp: #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> lib_case.cpp: #define BOOST_TEST_DYN_LINK #include...

How to stop creating instance of Singleton

java,singleton
I have a Singleton class like this: class Singleton { static class SingletonHolder { static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; } } Can I call like this from other class: Singleton dummy = new Singleton(); if yes how can I disable...

difficulty in singleton swift

ios,swift,singleton
I am trying to use singleton in my swift app. I have a class which i used in ObjectiveC and now i am using it in swift using bridging-header... In singleton class here is my code... SharedManger.h file +(SharedManager *)sharedInstance; @property (strong, nonatomic) NSMutableDictionary *dictobject; SharedManger.m file + (id)sharedInstance {...

How to pass derived type to abstract class with singleton

c#,singleton
This is the code that I use to apply Singleton pattern to all derived class. public abstract class Service<T> where T : Service<T>, new() { private static T _instance = null; public static T I() { if (_instance == null) _instance = new T(); return _instance; } } public class...

Laravel 5 - expected location for a singleton

laravel,singleton,laravel-5
Hello guys ! I want to create a singleton for my oauth server, like this : App::singleton('oauth2', function() { // connect to the oauth2 server, check grant type, client credentials.... }); Currently it's in my routes, and it works... I call it in a route just a little after. But...

Insert std::string and shared pointer to object in map

c++,c++11,dictionary,singleton
I'm using singleton design pattern (I can't use the copy constructor). I have a: Obj.hpp and Obj.cpp file House.hpp and House.cpp file The Obj class contains a map of Houses, where I can search for a house using a string. I can't even compile my Obj.cpp file, don't know why......

C# singleton instance is never null

c#,null,singleton,instance
I am attempting to implement a singleton pattern in an Azure webjob. Debugging locally the instance is never null. It is always set to the singleton object itself. I feel I'm missing something brutally obvious here. public sealed class HubErrorList { private static volatile HubErrorList instance; private static object syncRoot...

Unresolved external symbol (singleton class C++) [duplicate]

c++,singleton
This question already has an answer here: What is an undefined reference/unresolved external symbol error and how do I fix it? 18 answers I already looked up some answers in Stackoverflow for this type of problem, none of which are helping me out. This question describes how to resolve...

Trouble setting long value in singleton IOS

ios,singleton,long-integer
I'm having trouble with setting and accessing long properties on a Singleton object. Every time I try to access a long property it returns -1. My singleton interface file is as follows: @interface gameData : NSObject <NSCoding> @property (assign, nonatomic) long score; @property (assign, nonatomic) long level; @property (assign, nonatomic)...

Execute a method when a variable value changes in Swift

ios,swift,properties,singleton
I need to execute a method when a variable value changes. More specifically I have a singleton class which has a shared variable called labelChange. Values of this variable are taken from another class called Model. Moreover I have two VC classes one of them has a button and a...

At what point does the Singleton instantiation and “static” Code Occur [duplicate]

java,singleton
This question already has an answer here: Use and flow of Static statements in Singleton Program 6 answers I have two questions about the Singleton class below: 1) At what point in the code does the instance get invoked, via the "new" in the declaration? Is it the first...

How to save a Singleton Object to an XML file using JAXBContext?

java,xml,jaxb,singleton
I am looking to save a Singleton Object to an XML file using JAXBContext. The Object in question is called Player which is extending an abstract class Entity. Entity does also extend Thread. Since Player is a Singleton Object, its constructor is made private and and unaccessible from outside the...

c# - Unique instance of a subclass

c#,interface,singleton,instance,subclass
I'm asking the question here cause i'm not finding the answer... Maybe i'm not looking for the right terms... My question is pretty simple, I have an interface class in C#, the thing is that one of the requirements of the program is that one and only one instance of...

ios/xcode/objective c: set and get session variable [duplicate]

ios,singleton,session-variables,userid
This question is an exact duplicate of: ios/objective c/singleton: Storing userid in session variable 2 answers This should not be that hard but I cannot get it to work. IOS newb trying to set userid in session instance following the answer by Ismael here. But cannot access value of...