Search Results

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

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

  • Static vs Singleton in C# (Difference between Singleton and Static)

    - by Jalpesh P. Vadgama
    Recently I have came across a question what is the difference between Static and Singleton classes. So I thought it will be a good idea to share blog post about it.Difference between Static and Singleton classes:A singleton classes allowed to create a only single instance or particular class. That instance can be treated as normal object. You can pass that object to a method as parameter or you can call the class method with that Singleton object. While static class can have only static methods and you can not pass static class as parameter.We can implement the interfaces with the Singleton class while we can not implement the interfaces with static classes.We can clone the object of Singleton classes we can not clone the object of static classes.Singleton objects stored on heap while static class stored in stack.more at my personal blog: dotnetjalps.com

    Read the article

  • Java Singleton Pattern

    - by Spencer
    I'm used the Singleton Design Pattern public class Singleton { private static final Singleton INSTANCE = new Singleton(); // Private constructor prevents instantiation from other classes private Singleton() {} public static Singleton getInstance() { return INSTANCE; } } My question is how do I create an object of class Singleton in another class? I've tried: Singleton singleton = new Singleton(); // error - constructor is private Singleton singleton = Singleton.getInstance(); // error - non-static method cannot be referenced from a static context What is the correct code? Thanks, Spencer

    Read the article

  • Name for Osherove's modified singleton pattern?

    - by Kazark
    I'm pretty well sold on the "singletons are evil" line of thought. Nevertheless, there are limited occurrences when you want to limit the creation of an object. Roy Osherove advises, If you're planning to use a singleton in your design, separate the logic of the singleton class and the logic that makes it a singleton (the part that initializes a static variables, for example) into two separate classes. That way, you can keep the single responsibility principle (SRP) and also have a way to override singleton logic. (The Art of Unit Testing 261-262) This pattern still perpetuates the global state. However, it does result in a testable design, so it seems to me to be a good pattern for mitigating the damage of a singleton. However, Osherove does not give a name to this pattern; but naming a pattern, according to the Gang of Four, is important: Naming a pattern immediately increases our design vocabulary. It lets us design at a higher level of abstraction. (3) Is there a standard name for this pattern? It seems different enough from a standard singleton to deserve a separate name. Decoupled Singleton, perhaps?

    Read the article

  • Difference between Singleton implemention using pointer and using static object

    - by Anon
    EDIT: Sorry my question was not clear, why do books/articles prefer implementation#1 over implementation#2? What is the actual advantage of using pointer in implementation of Singleton class vs using a static object? Why do most books prefer this class Singleton { private: static Singleton *p_inst; Singleton(); public: static Singleton * instance() { if (!p_inst) { p_inst = new Singleton(); } return p_inst; } }; over this class Singleton { public: static Singleton& Instance() { static Singleton inst; return inst; } protected: Singleton(); // Prevent construction Singleton(const Singleton&); // Prevent construction by copying Singleton& operator=(const Singleton&); // Prevent assignment ~Singleton(); // Prevent unwanted destruction };

    Read the article

  • Static class vs Singleton class in C# [closed]

    - by Floradu88
    Possible Duplicate: What is the difference between all-static-methods and applying a singleton pattern? I need to make a decision for a project I'm working of whether to use static or singleton. After reading an article like this I am inclined to use singleton. What is better to use static class or singleton? Edit 1 : Client Server Desktop Application. Please provide code oriented solutions.

    Read the article

  • Python singleton pattern

    - by Javier Garcia
    Hi, someone can tell me why this is incorrect as a singleton pattern: class preSingleton(object): def __call__(self): return self singleton = preSingleton() a = singleton() b = singleton() print a==b a.var_in_a = 100 b.var_in_b = 'hello' print a.var_in_b print b.var_in_a Edit: The above code prints: True hello 100 thank you very much

    Read the article

  • The Template Method Design Pattern using C# .Net

    - by nijhawan.saurabh
    First of all I'll just put this pattern in context and describe its intent as in the GOF book:   Template Method: Define the skeleton of an algorithm in an operation, deferring some steps to Subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the Algorithm's Structure.    Usage: When you are certain about the High Level steps involved in an Algorithm/Work flow you can use the Template Pattern which allows the Base Class to define the Sequence of the Steps but permits the Sub classes to alter the implementation of any/all steps.   Example in the .Net framework: The most common example is the Asp.Net Page Life Cycle. The Page Life Cycle has a few methods which are called in a sequence but we have the liberty to modify the functionality of any of the methods by overriding them.   Sample implementation of Template Method Pattern:   Let's see the class diagram first:            Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:8.0pt; mso-para-margin-left:0in; line-height:107%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi; mso-font-kerning:1.0pt; mso-ligatures:standard;}   And here goes the code:EmailBase.cs     1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     public abstract class EmailBase    10     {    11     12         public bool SendEmail()    13         {    14             if (CheckEmailAddress() == true) // Method1 in the sequence    15             {    16                 if (ValidateMessage() == true) // Method2 in the sequence    17                 {    18                     if (SendMail() == true) // Method3 in the sequence    19                     {    20                         return true;    21                     }    22                     else    23                     {    24                         return false;    25                     }    26     27                 }    28                 else    29                 {    30                     return false;    31                 }    32     33             }    34             else    35             {    36                 return false;    37     38             }    39     40     41         }    42     43         protected abstract bool CheckEmailAddress();    44         protected abstract bool ValidateMessage();    45         protected abstract bool SendMail();    46     47     48     }    49 }    50    EmailYahoo.cs      1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     public class EmailYahoo:EmailBase    10     {    11     12         protected override bool CheckEmailAddress()    13         {    14             Console.WriteLine("Checking Email Address : YahooEmail");    15             return true;    16         }    17         protected override bool ValidateMessage()    18         {    19             Console.WriteLine("Validating Email Message : YahooEmail");    20             return true;    21         }    22     23     24         protected override bool SendMail()    25         {    26             Console.WriteLine("Semding Email : YahooEmail");    27             return true;    28         }    29     30     31     }    32 }    33   EmailGoogle.cs      1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     public class EmailGoogle:EmailBase    10     {    11     12         protected override bool CheckEmailAddress()    13         {    14             Console.WriteLine("Checking Email Address : GoogleEmail");    15             return true;    16         }    17         protected override bool ValidateMessage()    18         {    19             Console.WriteLine("Validating Email Message : GoogleEmail");    20             return true;    21         }    22     23     24         protected override bool SendMail()    25         {    26             Console.WriteLine("Semding Email : GoogleEmail");    27             return true;    28         }    29     30     31     }    32 }    33   Program.cs      1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     class Program    10     {    11         static void Main(string[] args)    12         {    13             Console.WriteLine("Please choose an Email Account to send an Email:");    14             Console.WriteLine("Choose 1 for Google");    15             Console.WriteLine("Choose 2 for Yahoo");    16             string choice = Console.ReadLine();    17     18             if (choice == "1")    19             {    20                 EmailBase email = new EmailGoogle(); // Rather than newing it up here, you may use a factory to do so.    21                 email.SendEmail();    22     23             }    24             if (choice == "2")    25             {    26                 EmailBase email = new EmailYahoo(); // Rather than newing it up here, you may use a factory to do so.    27                 email.SendEmail();    28             }    29         }    30     }    31 }    32    Final Words: It's very obvious that why the Template Method Pattern is a popular pattern, everything at last revolves around Algorithms and if you are clear with the steps involved it makes real sense to delegate the duty of implementing the step's functionality to the sub classes. Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:8.0pt; mso-para-margin-left:0in; line-height:107%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi; mso-font-kerning:1.0pt; mso-ligatures:standard;}

    Read the article

  • Trying to change variables in a singleton using a method

    - by Johnny Cox
    I am trying to use a singleton to store variables that will be used across multiple view controllers. I need to be able to get the variables and also set them. How do I call a method in a singleton to change the variables stored in the singleton. total+=1079; [var setTotal:total]; where var is a static Singleton *var = nil; I need to update the total and send to the setTotal method inside the singleton. But when I do this the setTotal method never gets accessed. The get methods work but the setTotal method does not. Please let me know what should. Below is some of my source code // // Singleton.m // Rolo // // Created by on 6/28/12. // Copyright (c) 2012 Johnny Cox. All rights reserved. // #import "Singleton.h" @implementation Singleton @synthesize total,tax,final; #pragma mark Singleton Methods + (Singleton *)sharedManager { static Singleton *sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[Singleton alloc] init]; // Do any other initialisation stuff here }); return sharedInstance; } +(void) setTotal:(double) tot { Singleton *shared = [Singleton sharedManager]; shared.total = tot; NSLog(@"hello"); } +(double) getTotal { Singleton *shared = [Singleton sharedManager]; NSLog(@"%f",shared.total); return shared.total; } +(double) getTax { Singleton *shared = [Singleton sharedManager]; NSLog(@"%f",shared.tax); return shared.tax; } @end // // Singleton.h // Rolo // // Created by on 6/28/12. // Copyright (c) 2012 Johnny Cox. All rights reserved. // #import <Foundation/Foundation.h> @interface Singleton : NSObject @property (nonatomic, assign) double total; @property (nonatomic, assign) double tax; @property (nonatomic, assign) double final; + (id)sharedManager; +(double) getTotal; +(void) setTotal; +(double) getTax; @end

    Read the article

  • const vs. readonly for a singleton

    - by GlenH7
    First off, I understand there are folk who oppose the use of singletons. I think it's an appropriate use in this case as it's constant state information, but I'm open to differing opinions / solutions. (See The singleton pattern and When should the singleton pattern not be used?) Second, for a broader audience: C++/CLI has a similar keyword to readonly with initonly, so this isn't strictly a C# type question. (Literal field versus constant variable in C++/CLI) Sidenote: A discussion of some of the nuances on using const or readonly. My Question: I have a singleton that anchors together some different data structures. Part of what I expose through that singleton are some lists and other objects, which represent the necessary keys or columns in order to connect the linked data structures. I doubt that anyone would try to change these objects through a different module, but I want to explicitly protect them from that risk. So I'm currently using a "readonly" modifier on those objects*. I'm using readonly instead of const with the lists as I read that using const will embed those items in the referencing assemblies and will therefore trigger a rebuild of those referencing assemblies if / when the list(s) is/are modified. This seems like a tighter coupling than I would want between the modules, but I wonder if I'm obsessing over a moot point. (This is question #2 below) The alternative I see to using "readonly" is to make the variables private and then wrap them with a public get. I'm struggling to see the advantage of this approach as it seems like wrapper code that doesn't provide much additional benefit. (This is question #1 below) It's highly unlikely that we'll change the contents or format of the lists - they're a compilation of things to avoid using magic strings all over the place. Unfortunately, not all the code has converted over to using this singleton's presentation of those strings. Likewise, I don't know that we'd change the containers / classes for the lists. So while I normally argue for the encapsulations advantages a get wrapper provides, I'm just not feeling it in this case. A representative sample of my singleton public sealed class mySingl { private static volatile mySingl sngl; private static object lockObject = new Object(); public readonly Dictionary<string, string> myDict = new Dictionary<string, string>() { {"I", "index"}, {"D", "display"}, }; public enum parms { ABC = 10, DEF = 20, FGH = 30 }; public readonly List<parms> specParms = new List<parms>() { parms.ABC, parms.FGH }; public static mySingl Instance { get { if(sngl == null) { lock(lockObject) { if(sngl == null) sngl = new mySingl(); } } return sngl; } } private mySingl() { doSomething(); } } Questions: Am I taking the most reasonable approach in this case? Should I be worrying about const vs. readonly? is there a better way of providing this information?

    Read the article

  • Multiple Instances of Static Singleton

    - by Nexus
    I've recently been working with code that looks like this: using namespace std; class Singleton { public: static Singleton& getInstance(); int val; }; Singleton &Singleton::getInstance() { static Singleton s; return s; } class Test { public: Test(Singleton &singleton1); }; Test::Test(Singleton &singleton1) { Singleton singleton2 = Singleton::getInstance(); singleton2.val = 1; if(singleton1.val == singleton2.val) { cout << "Match\n"; } else { cout << "No Match " << singleton1.val << " - " << singleton2.val << "\n"; } } int main() { Singleton singleton = Singleton::getInstance(); singleton.val = 2; Test t(singleton); } Every time I run it I get "No Match". From what I can tell when stepping through with GDB is that there are two instances of the Singleton. Why is this?

    Read the article

  • How to change the state of a singleton in runtime

    - by user34401
    Consider I am going to write a simple file based logger AppLogger to be used in my apps, ideally it should be a singleton so I can call it via public class AppLogger { public static String file = ".."; public void logToFile() { // Write to file } public static log(String s) { AppLogger.getInstance().logToFile(s); } } And to use it AppLogger::log("This is a log statement"); The problem is, what is the best time I should provide the value of file since it is a just a singleton? Or how to refactor the above code (or skip using singleton) so I can customize the log file path? (Assume I don't need to write to multiple at the same time) p.s. I know I can use library e.g. log4j, but consider it is just a design question, how to refactor the code above?

    Read the article

  • Singleton design pattern vs Singleton beans in Spring container

    - by Peeyush
    As we all know we have beans as singleton by default in Spring container and if we have a web application based on Spring framework then in that case do we really need to implement Singleton design pattern to hold global data rather than just creating a bean through spring. Please bear with me if I'm not able to explain what I actually meant to ask.

    Read the article

  • General Overview of Design Pattern Types

    Typically most software engineering design patterns fall into one of three categories in regards to types. Three types of software design patterns include: Creational Type Patterns Structural Type Patterns Behavioral Type Patterns The Creational Pattern type is geared toward defining the preferred methods for creating new instances of objects. An example of this type is the Singleton Pattern. The Singleton Pattern can be used if an application only needs one instance of a class. In addition, this singular instance also needs to be accessible across an application. The benefit of the Singleton Pattern is that you control both instantiation and access using this pattern. The Structural Pattern type is a way to describe the hierarchy of objects and classes so that they can be consolidated into a larger structure. An example of this type is the Façade Pattern.  The Façade Pattern is used to define a base interface so that all other interfaces inherit from the parent interface. This can be used to simplify a number of similar object interactions into one single standard interface. The Behavioral Pattern Type deals with communication between objects. An example of this type is the State Design Pattern. The State Design Pattern enables objects to alter functionality and processing based on the internal state of the object at a given time.

    Read the article

  • How to build a Singleton-like dependency injector replacement (Php)

    - by Erparom
    I know out there are a lot of excelent containers, even frameworks almost entirely DI based with good strong IoC classes. However, this doesn't help me to "define" a new pattern. (This is Php code but understandable to anyone) Supose we have: //Declares the singleton class bookSingleton { private $author; private static $bookInstance; private static $isLoaned = FALSE; //The private constructor private function __constructor() { $this->author = "Onecrappy Writer Ofcheap Novels"; } //Sets the global isLoaned state and also gets self instance public static function loanBook() { if (self::$isLoaned === FALSE) { //Book already taken, so return false return FALSE; } else { //Ok, not loaned, lets instantiate (if needed and loan) if (!isset(self::$bookInstance)) { self::$bookInstance = new BookSingleton(); } self::$isLoaned = TRUE; } } //Return loaned state to false, so another book reader can take the book public function returnBook() { $self::$isLoaned = FALSE; } public function getAuthor() { return $this->author; } } Then we get the singelton consumtion class: //Consumes the Singleton class BookBorrower() { private $borrowedBook; private $haveBookState; public function __construct() { this->haveBookState = FALSE; } //Use the singelton-pattern behavior public function borrowBook() { $this->borrowedBook = BookSingleton::loanBook(); //Check if was successfully borrowed if (!this->borrowedBook) { $this->haveBookState = FALSE; } else { $this->haveBookState = TRUE; } } public function returnBook() { $this->borrowedBook->returnBook(); $this->haveBookState = FALSE; } public function getBook() { if ($this->haveBookState) { return "The book is loaned, the author is" . $this->borrowedbook->getAuthor(); } else { return "I don't have the book, perhaps someone else took it"; } } } At last, we got a client, to test the behavior function __autoload($class) { require_once $class . '.php'; } function write ($whatever,$breaks) { for($break = 0;$break<$breaks;$break++) { $whatever .= "\n"; } echo nl2br($whatever); } write("Begin Singleton test", 2); $borrowerJuan = new BookBorrower(); $borrowerPedro = new BookBorrower(); write("Juan asks for the book", 1); $borrowerJuan->borrowBook(); write("Book Borrowed? ", 1); write($borrowerJuan->getAuthorAndTitle(),2); write("Pedro asks for the book", 1); $borrowerPedro->borrowBook(); write("Book Borrowed? ", 1); write($borrowerPedro->getAuthorAndTitle(),2); write("Juan returns the book", 1); $borrowerJuan->returnBook(); write("Returned Book Juan? ", 1); write($borrowerJuan->getAuthorAndTitle(),2); write("Pedro asks again for the book", 1); $borrowerPedro->borrowBook(); write("Book Borrowed? ", 1); write($borrowerPedro->getAuthorAndTitle(),2); This will end up in the expected behavior: Begin Singleton test Juan asks for the book Book Borrowed? The book is loaned, the author is = Onecrappy Writer Ofcheap Novels Pedro asks for the book Book Borrowed? I don't have the book, perhaps someone else took it Juan returns the book Returned Book Juan? I don't have the book, perhaps someone else took it Pedro asks again for the book Book Borrowed? The book is loaned, the author is = Onecrappy Writer Ofcheap Novels So I want to make a pattern based on the DI technique able to do exactly the same, but without singleton pattern. As far as I'm aware, I KNOW I must inject the book inside "borrowBook" function instead of taking a static instance: public function borrowBook(BookNonSingleton $book) { if (isset($this->borrowedBook) || $book->isLoaned()) { $this->haveBook = FALSE; return FALSE; } else { $this->borrowedBook = $book; $this->haveBook = TRUE; return TRUE; } } And at the client, just handle the book: $borrowerJuan = new BookBorrower(); $borrowerJuan-borrowBook(new NonSingletonBook()); Etc... and so far so good, BUT... Im taking the responsability of "single instance" to the borrower, instead of keeping that responsability inside the NonSingletonBook, that since it has not anymore a private constructor, can be instantiated as many times... making instances on each call. So, What does my NonSingletonBook class MUST be in order to never allow borrowers to have this same book twice? (aka) keep the single instance. Because the dependency injector part of the code (borrower) does not solve me this AT ALL. Is it needed the container with an "asShared" method builder with static behavior? No way to encapsulate this functionallity into the Book itself? "Hey Im a book and I shouldn't be instantiated more than once, I'm unique"

    Read the article

  • null values vs "empty" singleton for optional fields

    - by Uko
    First of all I'm developing a parser for an XML-based format for 3D graphics called XGL. But this question can be applied to any situation when you have fields in your class that are optional i.e. the value of this field can be missing. As I was taking a Scala course on coursera there was an interesting pattern when you create an abstract class with all the methods you need and then create a normal fully functional subclass and an "empty" singleton subclass that always returns false for isEmpty method and throws exceptions for the other ones. So my question is: is it better to just assign null if the optional field's value is missing or make a hierarchy described above and assign it an empty singleton implementation?

    Read the article

  • C++ Singleton Constructor and Destructor

    - by Aaron
    Does it matter if the constructor/destructor implementation is provided in the header file or the source file? For example, which way is preferred and why? Way 1: class Singleton { public: ~Singleton() { } private: Singleton() { } }; Way 2: class Singleton { public: ~Singleton(); private: Singleton(); }; In the source .cc file: Singleton::Singleton() { } Singleton::~Singleton() { } Initially, I have the implementation in a source file, but I was asked to remove it. Does anyone know why?

    Read the article

  • General question about Ruby singleton class

    - by Dex
    module MyModule def my_method; 'hello'; end end class MyClass class << self include MyModule end end MyClass.my_method # => "hello I'm unsure why "include MyModule" needs to be in the singleton class in order to be called using just MyClass. Why can't I go: X = MyClass.new X.my_method

    Read the article

  • The Singleton Pattern

    - by Darren Young
    Hi, I am a new programmer (4 months into my first job) and have recently taken an interest in design patterns. One that I have used recently is the Singleton. However, looking at some comments on this thread Overused or abused programming techniques .......it has some bad feedback. Come somebody explain why? I have found it useful in some places, however I could probably have achieved the same without it using a static class. Thanks.

    Read the article

  • What are the advantages of the delegate pattern over the observer pattern?

    - by JoJo
    In the delegate pattern, only one object can directly listen to another object's events. In the observer pattern, any number of objects can listen to a particular object's events. When designing a class that needs to notify other object(s) of events, why would you ever use the delegate pattern over the observer pattern? I see the observer pattern as more flexible. You may only have one observer now, but a future design may require multiple observers.

    Read the article

  • How to create a fully lazy singleton for generics

    - by Brendan Vogt
    I have the following code implementation of my generic singleton provider: public sealed class Singleton<T> where T : class, new() { Singleton() { } public static T Instance { get { return SingletonCreator.instance; } } class SingletonCreator { static SingletonCreator() { } internal static readonly T instance = new T(); } } This sample was taken from 2 articles and I merged the code to get me what I wanted: http://www.yoda.arachsys.com/csharp/singleton.html and http://www.codeproject.com/Articles/11111/Generic-Singleton-Provider. This is how I tried to use the code above: public class MyClass { public static IMyInterface Initialize() { if (Singleton<IMyInterface>.Instance == null // Error 1 { Singleton<IMyInterface>.Instance = CreateEngineInstance(); // Error 2 Singleton<IMyInterface>.Instance.Initialize(); } return Singleton<IMyInterface>.Instance; } } And the interface: public interface IMyInterface { } The error at Error 1 is: 'MyProject.IMyInterace' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'MyProject.Singleton<T>' The error at Error 2 is: Property or indexer 'MyProject.Singleton<MyProject.IMyInterface>.Instance' cannot be assigned to -- it is read only How can I fix this so that it is in line with the 2 articles mentioned above? Any other ideas or suggestions are appreciated.

    Read the article

  • Singleton by Jon Skeet clarification

    - by amutha
    public sealed class Singleton { Singleton() { } public static Singleton Instance { get { return Nested.instance; } } class Nested { // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static Nested() { } internal static readonly Singleton instance = new Singleton(); } } I wish to implement Jon Skeet's Singleton pattern in my current application in C#. I have two doubts on the code 1) How is it possible to access the outer class inside nested class? I mean internal static readonly Singleton instance = new Singleton(); Is something called closure? 2) I did not get this comment // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit what does this comment suggest us?

    Read the article

  • Extending a singleton class

    - by cakyus
    i used to create an instance of a singleton class like this: $Singleton = SingletonClassName::GetInstance(); and for non singleton class: $NonSingleton = new NonSingletonClassName; i think we should not differentiate how we create an instance of a class whether this is a singleton or not. if i look in perception of other class, i don't care whether the class we need a singleton class or not. so, i still not comfortable with how php treat a singleton class. i think and i always want to write: $Singleton = new SingletonClassName; just another non singleton class, is there a solution to this problem ?

    Read the article

  • Using singleton instead of a global static instance

    - by Farstucker
    I ran into a problem today and a friend recommended I use a global static instance or more elegantly a singleton pattern. I spent a few hours reading about singletons but a few things still escape me. Background: What Im trying to accomplish is creating an instance of an API and use this one instance in all my classes (as opposed to making a new connection, etc). There seems to be about 100 ways of creating a singleton but with some help from yoda I found some thread safe examples. ..so given the following code: public sealed class Singleton { public static Singleton Instance { get; private set; } private Singleton() { APIClass api = new APIClass(); //Can this be done? } static Singleton() { Instance = new Singleton(); } } How/Where would you instantiate the this new class and how should it be called from a separate class? EDIT: I realize the Singleton class can be called with something like Singleton obj1 = Singleton.Instance(); but would I be able to access the methods within the APIs Class (ie. obj1.Start)? (not that I need to, just asking) EDIT #2: I might have been a bit premature in checking the answer but I do have one small thing that is still causing me problems. The API is launching just fine, unfortunately Im able to launch two instances? New Code public sealed class SingletonAPI { public static SingletonAPI Instance { get; private set; } private SingletonAPI() {} static SingletonAPI() { Instance = new SingletonAPI(); } // API method: public void Start() { API myAPI = new API();} } but if I try to do something like this... SingletonAPI api = SingletonAPI.Instance; api.Start(); SingletonAPI api2 = SingletonAPI.Instance; // This was just for testing. api2.Start(); I get an error saying that I cannot start more than one instance.

    Read the article

  • Singleton class in DLL used on multiple virtual directories

    - by Drejc
    I have the following situation: multiple virtual directories under same application pool in IIS copy of same DLL in all those directories (same version number) a singleton class in one in this DLL The question is, is this singleton class created only once for all those Virtual Directory instances or is there for each of there one singleton class. The code looks something like this: [ Transaction(TransactionOption.Supported), ClassInterface(ClassInterfaceType.AutoDispatch), Guid("7DE45C4D-19BE-4AA4-A2DA-F4D86E6502A8") ] public class SomeClass { private static readonly Singleton singleton = new Singleton();

    Read the article

  • Singleton with inheritance, Derived class is not able to get instantiated in parent?

    - by yesraaj
    Below code instantiates a derived singleton object based on environment variable. The compiler errors saying error C2512: 'Dotted' : no appropriate default constructor. I don't understand what the compiler is complaining about. #include <stdlib.h> #include <iostream> #include <string> using namespace std; class Dotted; class Singleton{ public: static Singleton instant(){ if (!instance_) { char * style = getenv("STYLE"); if (!style){ if (strcmp(style,"dotted")==0) { instance_ = new Dotted(); return *instance_; } } else{ instance_ = new Singleton(); return *instance_; } } return *instance_; } void print(){cout<<"Singleton";} ~Singleton(){}; protected: Singleton(){}; private: static Singleton * instance_; Singleton(const Singleton & ); void operator=(const Singleton & ); }; class Dotted:public Singleton{ public: void print(){cout<<"Dotted";} protected: Dotted(); }; Dotted::Dotted():Singleton(){} int main(){ Singleton::instant().print(); cin.get(); }

    Read the article

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