Search Results

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

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

  • Is MVC a Design Pattern or Architectural pattern

    - by JCasso
    According to Sun and Msdn it is a design pattern. According to Wikipedia it is an architectural pattern In comparison to design patterns, architectural patterns are larger in scale. (Wikipedia - Architectural pattern) Or it is an architectural pattern that also has a design pattern ? Which one is true ?

    Read the article

  • game state singleton cocos2d, initWithEncoder always returns null

    - by taber
    Hi, I'm trying to write a basic test "game state" singleton in cocos2d, but for some reason upon loading the app, initWithCoder is never called. Any help would be much appreciated, thanks. Here's my singleton GameState.h: #import "cocos2d.h" @interface GameState : NSObject <NSCoding> { NSInteger level, score; Boolean seenInstructions; } @property (readwrite) NSInteger level; @property (readwrite) NSInteger score; @property (readwrite) Boolean seenInstructions; +(GameState *) sharedState; +(void) loadState; +(void) saveState; @end ... and GameState.m: #import "GameState.h" #import "Constants.h" @implementation GameState static GameState *sharedState = nil; @synthesize level, score, seenInstructions; -(void)dealloc { [super dealloc]; } -(id)init { if(!(self = [super init])) return nil; level = 1; score = 0; seenInstructions = NO; return self; } +(void)loadState { @synchronized([GameState class]) { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *saveFile = [documentsDirectory stringByAppendingPathComponent:kSaveFileName]; Boolean saveFileExists = [[NSFileManager defaultManager] fileExistsAtPath:saveFile]; if(!sharedState) { sharedState = [GameState sharedState]; } if(saveFileExists == YES) { [sharedState release]; sharedState = [[NSKeyedUnarchiver unarchiveObjectWithFile:saveFile] retain]; } // at this point, sharedState is null, saveFileExists is 1 if(sharedState == nil) { // this always occurs CCLOG(@"Couldn't load game state, so initialized with defaults"); sharedState = [self sharedState]; } } } +(void)saveState { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *saveFile = [documentsDirectory stringByAppendingPathComponent:kSaveFileName]; [NSKeyedArchiver archiveRootObject:[GameState sharedState] toFile:saveFile]; } +(GameState *)sharedState { @synchronized([GameState class]) { if(!sharedState) { [[GameState alloc] init]; } return sharedState; } return nil; } +(id)alloc { @synchronized([GameState class]) { NSAssert(sharedState == nil, @"Attempted to allocate a second instance of a singleton."); sharedState = [super alloc]; return sharedState; } return nil; } +(id)allocWithZone:(NSZone *)zone { @synchronized([GameState class]) { if(!sharedState) { sharedState = [super allocWithZone:zone]; return sharedState; } } return nil; } ... -(void)encodeWithCoder:(NSCoder *)coder { [coder encodeInt:level forKey:@"level"]; [coder encodeInt:score forKey:@"score"]; [coder encodeBool:seenInstructions forKey:@"seenInstructions"]; } -(id)initWithCoder:(NSCoder *)coder { CCLOG(@"initWithCoder called"); self = [super init]; if(self != nil) { CCLOG(@"initWithCoder self exists"); level = [coder decodeIntForKey:@"level"]; score = [coder decodeIntForKey:@"score"]; seenInstructions = [coder decodeBoolForKey:@"seenInstructions"]; } return self; } @end ... I'm saving the state on app exit, like this: - (void)applicationWillTerminate:(UIApplication *)application { [GameState saveState]; [[CCDirector sharedDirector] end]; } ... and loading the state when the app finishes loading, like this: - (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { ... [GameState loadState]; ... } I've tried moving around where I call loadState too, for example in my main CCScene, but that didn't seem to work either. Thanks again in advance.

    Read the article

  • Rebinding and singleton-behaviour [NInject]

    - by Maximilian Csuk
    Hi! I have set up a NInject (using version 1.5) binding like this: Bind<ISessionFactory>().ToMethod<ISessionFactory>(ctx => { try { // create session factory, might fail because of database issues like wrong connection string } catch (Exception e) { throw new DatabaseException(e); } }).Using<SingletonBehavior>(); As you can see, this binding uses a singleton behavior but can also throw exception when something is not configured correctly, like a wrong connection string to the database. Now, when the creation of a session factory fails at first (throwing a database exception), NInject doesn't try to create the object again but always returns null. I would need NInject to check for null first and recreate when the instance is null, but of course not when there already is an instance successfully constructed (keeping it singleton). Like this: var a = Kernel.Get<ISessionFactory>(); // might fail, a = null // ... change some database settings var b = Kernel.Get<ISessionFactory>(); // might not fail anymore, b = ISessionFactory object Would I need to write a custom behavior or am I missing something else? Thanks for your answers!

    Read the article

  • PHP OOP: Avoid Singleton/Static Methods in Domain Model Pattern

    - by sunwukung
    I understand the importance of Dependency Injection and its role in Unit testing, which is why the following issue is giving me pause: One area where I struggle not to use the Singleton is the Identity Map/Unit of Work pattern (Which keeps tabs on Domain Object state). //Not actual code, but it should demonstrate the point class Monitor{//singleton construction omitted for brevity static $members = array();//keeps record of all objects static $dirty = array();//keeps record of all modified objects static $clean = array();//keeps record of all clean objects } class Mapper{//queries database, maps values to object fields public function find($id){ if(isset(Monitor::members[$id]){ return Monitor::members[$id]; } $values = $this->selectStmt($id); //field mapping process omitted for brevity $Object = new Object($values); Monitor::new[$id]=$Object return $Object; } $User = $UserMapper->find(1);//domain object is registered in Id Map $User->changePropertyX();//object is marked "dirty" in UoW // at this point, I can save by passing the Domain Object back to the Mapper $UserMapper->save($User);//object is marked clean in UoW //but a nicer API would be something like this $User->save(); //but if I want to do this - it has to make a call to the mapper/db somehow $User->getBlogPosts(); //or else have to generate specific collection/object graphing methods in the mapper $UserPosts = $UserMapper->getBlogPosts(); $User->setPosts($UserPosts); Any advice on how you might handle this situation? I would be loathe to pass/generate instances of the mapper/database access into the Domain Object itself to satisfy DI - At the same time, avoiding that results in lots of calls within the Domain Object to external static methods. Although I guess if I want "save" to be part of its behaviour then a facility to do so is required in its construction. Perhaps it's a problem with responsibility, the Domain Object shouldn't be burdened with saving. It's just quite a neat feature from the Active Record pattern - it would be nice to implement it in some way.

    Read the article

  • Singleton pattern and broken double checked locking in real world java application

    - by saugata
    I was reading the article Double-checked locking and the Singleton pattern, on how double checked locking is broken, and some related questions here on stackoverflow. I have used this pattern/idiom several times without any issues. Since I have been using Java 5, my first thought was that this has been rectified in Java 5 memory model. However the article says This article refers to the Java Memory Model before it was revised for Java 5.0; statements about memory ordering may no longer be correct. However, the double-checked locking idiom is still broken under the new memory model. I'm wondering if anyone has actually run into this problem in any application and under what conditions.

    Read the article

  • C++ boost thread id and Singleton

    - by aaa
    hi. Sorry to flood so many questions this week. I assume thread index returned by thread.get_id is implementation specific. In case of the pthreads, is index reused? IE, if thread 0 runs and joins, is thread launched afterwords going to have a different ID? the reason I ask this is a need to implement Singleton pattern with a twist: each thread gets its own instance. I know it sounds very crazy, but threads control hardware (cuda) which does not permit device memory sharing. What is a good way to implement such pattern?

    Read the article

  • Calls to singleton library

    - by metdos
    I have a singleton class, and I will compile it as a library static(lib) or dynamic(dll). Is it guaranteed that calls to same file in a machine always refer to same and unique instance in both cases?

    Read the article

  • Boost singleton and restricted

    - by Ockonal
    Hello, I'm using boost singleton from thread/detail. There is in manual, that constructor should have signlature: boost::restricted. But I can't find any reference for this type in boost library. Why do I need in this and where I can find it?

    Read the article

  • Spring - singleton problem - No bean named '....' found

    - by lisak
    Hey, I can't figure out what is wrong with this beans definition. I'm getting this error http://pastebin.com/ecn5SWLa . Especially the 14th log message is interesting. This is my app-context file http://pastebin.com/dreubpRY httpParams is a singleton which is set up in httpParamBean and then used by tsccManager and httpClient. The various depends-on settings is a result of my effort to figure it out.

    Read the article

  • Stateless singleton VS Static methods

    - by Sebastien Lorber
    Hey, Don't find any good answer to this simple question about helper/utils classes: Why would i create a singleton (stateless) rather than static methods? Why an object instance could be needed while the object has no state? Sometimes i really don't know what to use...

    Read the article

  • Singleton Pattern Implementation Issues?

    - by locky28
    Hi I am revising for an exam and need to know some implementation issues with the singleton pattern. they do not need to be too complex just basic things that would affect a developers decision to include them, Thanks P.S. Could any code examples be given in Java thanks.

    Read the article

  • Singleton rule questions (do not allow to create copy and deserialization)

    - by Petr
    Hi, Reading some article about singleton, I stopped at the point saying: "Do not allow to crate copy of existing instance". I realized that I do not know how would I do that! Could you tell me, please, how could I copy existing instance of class? And the second one: deserializaition. How it could be dangerous? And for both - how to deny creating copies or deserialization? Thanks

    Read the article

  • How do I find out if the variable is declared in Python?

    - by golergka
    I want to use a module as a singleton referenced in other modules. It looks something like this (that's not actually a code I'm working on, but I simplified it to throw away all unrelated stuff): main.py import singleton import printer def main(): singleton.Init(1,2) printer.Print() if __name__ == '__main__': pass singleton.py variable1 = '' variable2 = '' def Init(var1, var2) variable1 = var1 variable2 = var2 printer.py import singleton def Print() print singleton.variable1 print singleton.variable2 I expect to get output 1/2, but instead get empty space. I understand that after I imported singleton to the print.py module the variables got initialized again. So I think that I must check if they were intialized before in singleton.py: if not (variable1): variable1 = '' if not (variable2) variable2 = '' But I don't know how to do that. Or there is a better way to use singleton modules in python that I'm not aware of :)

    Read the article

  • Boost C++ Singleton error LNK2001: unresolved external symbol "private: static long Nsp::HL::flag" (

    - by Soós Roland
    I try to create a multi-threaded singleton pattern class. Header: class HL{ public: static HL* getInstance(); ......... private: static HL* instance; static boost::once_flag flag; HL(); static void initOnce(); } CPP: HL* HL::instance = NULL; HL* HL::getInstance(){ if(instance == NULL){ boost::call_once(flag, initOnce); } return instance; } void HL::initOnce(){ instance = new HL(); } I get this error: error LNK2001: unresolved external symbol "private: static long Nsp::HL::flag" (?flag@HL@Nsp@@0JA) What's wrong?

    Read the article

  • some confusions to singleton pattern in PHP

    - by SpawnCxy
    Hi all, In my team I've been told to write resource class like this style: class MemcacheService { private static $instance = null; private function __construct() { } public static function getInstance($fortest = false) { if (self::$instance == null) { self::$instance = new Memcached(); if ($fortest) { self::$instance->addServer(MEMTEST_HOST, MEMTEST_PORT); } else { self::$instance->addServer(MEM_HOST, MEM_PORT); } } return self::$instance; } } But I think in PHP resource handles will be released and initialized again every time after a request over. That means MemcacheService::getInstance() is totally equal new Memcached() which cannot be called singleton pattern at all. Please correct me if I'm wrong. Regards

    Read the article

  • Generic Abstract Singleton with Custom Constructor in C#

    - by Heka
    I want to write a generic singleton with an external constructor. In other words the constructor can be modified. I have 2 designs in my mind but I don't know whether they are practical or not. First one is to enforce derived class' constructor to be non-public but I do not know if there is a way of it? Second one is to use a delegate and call it inside the constructor? It isn't necessarily to be a constructor. The reason I chose custom constructor is doing some custom initializations. Any suggestions would be appreciated :)

    Read the article

  • Circular reference problem Singleton

    - by Ismail
    I'm trying to creating a Singleton class like below where MyRepository lies in separate DAL project. It's causing me a circular reference problem because GetMySingleTon() method returns MySingleTon class and needs its access. Same way I need MyRepository access in constructor of MySingleTon class. public class MySingleTon { static MySingleTon() { if (Instance == null) { MyRepository rep = new MyRepository(); Instance = rep.GetMySingleTon(); } } public static MySingleTon Instance { get; private set; } public string prop1 { get; set; } public string prop2 { get; set; } }

    Read the article

  • StructureMap 'conditional singleton' for Lucene.Net IndexReader

    - by Gareth D
    I have a threadsafe object that is expensive to create and needs to be available through my application (a Lucene.Net IndexReader). The object can become invalid, at which point I need to recreate it (IndexReader.IsCurrent is false, need a new instance using IndexReader.Reopen). I'd like to able to use an IoC container (StructureMap) to manage the creation of the object, but I can't work out if this scenario is possible. It feels like some kind of "conditional singleton" lifecycle. Does StructureMap provide such a feature? Any alternative suggestions?

    Read the article

  • Thread-safe use of a singleton's members

    - by Anthony Mastrean
    I have a C# singleton class that multiple classes use. Is access through Instance to the Toggle() method thread-safe? If yes, by what assumptions, rules, etc. If no, why and how can I fix it? public class MyClass { private static readonly MyClass instance = new MyClass(); public static MyClass Instance { get { return instance; } } private int value = 0; public int Toggle() { if(value == 0) { value = 1; } else if(value == 1) { value = 0; } return value; } }

    Read the article

  • StructureMap singleton behavior not working

    - by user137348
    My code is public static class ContainerBootstrapper { public static void BootstrapStructureMap() { ObjectFactory.Initialize(x => x .ForRequestedType<ValueHolder>() .CacheBy(InstanceScope.Singleton) .TheDefaultIsConcreteType<ValueHolder>()); } } Initialization code (its a windows service) static class Program { static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new AppServer() }; ServiceBase.Run(ServicesToRun); ContainerBootstrapper.BootstrapStructureMap(); } } And then I call an instance like this: var valueHolder = ObjectFactory.GetInstance<ValueHolder>(); But I get everytime an new instance not the one used before.

    Read the article

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