Design Patterns

Материал из Wiki.crossplatform.ru

(Различия между версиями)
Перейти к: навигация, поиск
(Одиночка (Singleton))
(Одиночка (Singleton))
Строка 74: Строка 74:
}
}
</source>
</source>
 +
 +
=== Шаблонный ===
 +
<source lang="cpp">class CClass
 +
{
 +
public:
 +
    virtual ~CClass(){  }
 +
};
 +
 +
template <class T>
 +
class CTypedSingleton;
 +
 +
template<class T>
 +
class CTypedWrapper : public T, private CTypedSingleton<T>
 +
{
 +
public:
 +
    void operator delete(void *p)
 +
    {
 +
        CTypedSingleton<T>::free();
 +
    }
 +
};
 +
 +
template <class T>
 +
class CTypedSingleton
 +
{
 +
    static T* m_self;
 +
    static int m_refcount;
 +
 +
protected:
 +
    CTypedSingleton(){}
 +
    CTypedSingleton(const CTypedSingleton&){}
 +
    virtual ~CTypedSingleton(){ m_self = 0; }
 +
    CTypedSingleton &operator=(const CTypedSingleton&){}
 +
 +
public:
 +
  static T *init()
 +
  {
 +
      if(!m_self)
 +
          m_self = new CTypedWrapper<T>;
 +
      m_refcount++;
 +
      return m_self;
 +
  }
 +
 +
  static void free()
 +
  {
 +
      if( m_refcount > 0)
 +
      {
 +
          --m_refcount;
 +
          if( m_refcount == 0)
 +
          {
 +
              delete m_self;
 +
              m_self = 0;
 +
          }
 +
      }
 +
  }
 +
};
 +
 +
template <class T>
 +
T *CTypedSingleton<T>::m_self = 0;
 +
 +
template <class T>
 +
int CTypedSingleton<T>::m_refcount = 0;
 +
 +
int main(int , char **)
 +
{
 +
    CClass *p = CTypedSingleton<CClass>::init();
 +
    delete p;
 +
 +
    return 0;
 +
}</source>
== Прототип (Prototype) ==
== Прототип (Prototype) ==

Версия 07:24, 16 апреля 2013

Содержание

Порождающие паттерны проектирования

Абстрактная фабрика (Abstract Factory, Factory), др. название Инструментарий (Kit)

Одиночка (Singleton)

Статический

class CSingleton
{
private:
    static CSingleton m_singleton;
 
private:
    CSingleton() {}
    ~CSingleton() {}
    CSingleton(const CSingleton &) {}
    CSingleton & operator=(const CSingleton &) { return *this; }
 
public:
    static CSingleton *instance() { return &m_singleton; }
};
 
CSingleton CSingleton::m_singleton;
 
int main(int , char **)
{
    CSingleton *p = CSingleton::instance();
    // ...
    return 0;
}

Динамический

class CSingleton
{
private:
    static CSingleton *m_pSingleton;
    static int m_nCounter;
 
private:
    CSingleton() {}
    ~CSingleton() {}
    CSingleton(const CSingleton &) {}
    CSingleton & operator=(const CSingleton &) { return *this; }
 
public:
    static CSingleton *instance()
    {
        if( m_nCounter == 0 )
        {
            m_pSingleton = new CSingleton();
        }
        m_nCounter++;
        return m_pSingleton;
    }
    static CSingleton *freeInstance()
    {
        if( m_nCounter > 0 )
        {
            m_nCounter--;
            if( m_nCounter == 0 )
            {
                delete m_pSingleton;
                m_pSingleton = 0;
            }
        }
    }
};
 
CSingleton *CSingleton::m_pSingleton = 0;
int CSingleton::m_nCounter = 0;
 
int main(int , char **)
{
    CSingleton *p = CSingleton::instance();
 
    return 0;
}

Шаблонный

class CClass
{
public:
    virtual ~CClass(){  }
};
 
template <class T>
class CTypedSingleton;
 
template<class T>
class CTypedWrapper : public T, private CTypedSingleton<T>
{
public:
    void operator delete(void *p)
    {
        CTypedSingleton<T>::free();
    }
};
 
template <class T>
class CTypedSingleton
{
    static T* m_self;
    static int m_refcount;
 
protected:
    CTypedSingleton(){}
    CTypedSingleton(const CTypedSingleton&){}
    virtual ~CTypedSingleton(){ m_self = 0; }
    CTypedSingleton &operator=(const CTypedSingleton&){}
 
public:
  static T *init()
  {
      if(!m_self)
          m_self = new CTypedWrapper<T>;
      m_refcount++;
      return m_self;
  }
 
  static void free()
  {
      if( m_refcount > 0)
      {
          --m_refcount;
          if( m_refcount == 0)
          {
              delete m_self;
              m_self = 0;
          }
      }
  }
};
 
template <class T>
T *CTypedSingleton<T>::m_self = 0;
 
template <class T>
int CTypedSingleton<T>::m_refcount = 0;
 
int main(int , char **)
{
    CClass *p = CTypedSingleton<CClass>::init();
    delete p;
 
    return 0;
}

Прототип (Prototype)

Создатель экземпляров класса (Creator)

Строитель (Builder)

Фабричный метод (Factory Method) или Виртуальный конструктор (Virtual Constructor)

Структурные паттерны проектирования классов/обьектов

Адаптер (Adapter)

Декоратор (Decorator) или Оболочка (Wrapper)

Заместитель (Proxy) или Суррогат (Surrogate)

Информационный эксперт (Information Expert)

Компоновщик (Composite)

Мост (Bridge), Handle (описатель) или Тело (Body)

Низкая связанность (Low Coupling)

Приспособленец (Flyweight)

Устойчивый к изменениям (Protected Variations)

Фасад (Facade)

Паттерны проектирования поведения классов/обьектов

Интерпретатор (Interpreter )

Итератор (Iterator) или Курсор (Cursor)

Команда (Command), Действие (Action) или Транзакция (Транзакция)

Наблюдатель (Observer), Опубликовать - подписаться (Publish - Subscribe) или Delegation Event Model

Не разговаривайте с неизвестными (Don't talk to strangers)

Посетитель (Visitor)

Посредник (Mediator)

Состояние (State)

Стратегия (Strategy)

Хранитель (Memento)

Цепочка обязанностей (Chain of Responsibility)

Шаблонный метод (Template Method)

Высокое зацепление (High Cohesion)

Контроллер (Controller)

Полиморфизм (Polymorphism)

Искусственный (Pure Fabrication)

Перенаправление (Indirection)