1// Copyright (C) 2011 The Libphonenumber Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Author: Philippe Liard
16
17#ifndef I18N_PHONENUMBERS_BASE_MEMORY_SINGLETON_H_
18#define I18N_PHONENUMBERS_BASE_MEMORY_SINGLETON_H_
19
20#if defined(I18N_PHONENUMBERS_USE_BOOST)
21
22#include <boost/scoped_ptr.hpp>
23#include <boost/thread/once.hpp>
24#include <boost/utility.hpp>
25
26namespace i18n {
27namespace phonenumbers {
28
29template <class T>
30class Singleton : private boost::noncopyable {
31 public:
32  virtual ~Singleton() {}
33
34  static T* GetInstance() {
35    boost::call_once(Init, flag);
36    return instance.get();
37  }
38
39 private:
40  static void Init() {
41    instance.reset(new T());
42  }
43
44  static boost::scoped_ptr<T> instance;
45  static boost::once_flag flag;
46};
47
48template <class T> boost::scoped_ptr<T> Singleton<T>::instance;
49template <class T> boost::once_flag Singleton<T>::flag = BOOST_ONCE_INIT;
50
51}  // namespace phonenumbers
52}  // namespace i18n
53
54#else  // !I18N_PHONENUMBERS_USE_BOOST
55
56#include "phonenumbers/base/logging.h"
57#include "phonenumbers/base/thread_checker.h"
58
59#if !defined(__linux__) && !defined(__APPLE__)
60
61namespace i18n {
62namespace phonenumbers {
63
64// Note that this implementation is not thread-safe. For a thread-safe
65// implementation on non-POSIX platforms, please compile with
66// -DI18N_PHONENUMBERS_USE_BOOST.
67template <class T>
68class Singleton {
69 public:
70  Singleton() : thread_checker_() {}
71
72  virtual ~Singleton() {}
73
74  static T* GetInstance() {
75    static T* instance = NULL;
76    if (!instance) {
77      instance = new T();
78    }
79    DCHECK(instance->thread_checker_.CalledOnValidThread());
80    return instance;
81  }
82
83 private:
84  const ThreadChecker thread_checker_;
85};
86
87}  // namespace phonenumbers
88}  // namespace i18n
89
90#else
91#include "phonenumbers/base/memory/singleton_posix.h"
92#endif  // !defined(__linux__) && !defined(__APPLE__)
93
94#endif  // !I18N_PHONENUMBERS_USE_BOOST
95#endif  // I18N_PHONENUMBERS_BASE_MEMORY_SINGLETON_H_
96