michael@0: // Copyright (c) 2008 The Chromium Authors. All rights reserved. michael@0: // Use of this source code is governed by a BSD-style license that can be michael@0: // found in the LICENSE file. michael@0: michael@0: // Support for using the Singleton pattern with Objective-C objects. A michael@0: // SingletonObjC is the same as a Singleton, except the default traits are michael@0: // appropriate for Objective-C objects. A typical Objective-C object of type michael@0: // NSExampleType can be maintained as a singleton and accessed with: michael@0: // michael@0: // NSExampleType* exampleSingleton = SingletonObjC::get(); michael@0: // michael@0: // The first time this is used, it will create exampleSingleton as the result michael@0: // of [[NSExampleType alloc] init]. Subsequent calls will return the same michael@0: // NSExampleType* object. The object will be released by calling michael@0: // -[NSExampleType release] when Singleton's atexit routines run michael@0: // (see singleton.h). michael@0: // michael@0: // For Objective-C objects initialized through means other than the michael@0: // no-parameter -init selector, DefaultSingletonObjCTraits may be extended michael@0: // as needed: michael@0: // michael@0: // struct FooSingletonTraits : public DefaultSingletonObjCTraits { michael@0: // static Foo* New() { michael@0: // return [[Foo alloc] initWithName:@"selecty"]; michael@0: // } michael@0: // } michael@0: // ... michael@0: // Foo* widgetSingleton = SingletonObjC::get(); michael@0: michael@0: #ifndef BASE_SINGLETON_OBJC_H_ michael@0: #define BASE_SINGLETON_OBJC_H_ michael@0: michael@0: #import michael@0: #include "base/singleton.h" michael@0: michael@0: // Singleton traits usable to manage traditional Objective-C objects, which michael@0: // are instantiated by sending |alloc| and |init| messages, and are deallocated michael@0: // in a memory-managed environment when their retain counts drop to 0 by michael@0: // sending |release| messages. michael@0: template michael@0: struct DefaultSingletonObjCTraits : public DefaultSingletonTraits { michael@0: static Type* New() { michael@0: return [[Type alloc] init]; michael@0: } michael@0: michael@0: static void Delete(Type* object) { michael@0: [object release]; michael@0: } michael@0: }; michael@0: michael@0: // Exactly like Singleton, but without the DefaultSingletonObjCTraits as the michael@0: // default trait class. This makes it straightforward for Objective-C++ code michael@0: // to hold Objective-C objects as singletons. michael@0: template, michael@0: typename DifferentiatingType = Type> michael@0: class SingletonObjC : public Singleton { michael@0: }; michael@0: michael@0: #endif // BASE_SINGLETON_OBJC_H_