- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
class Cms extends Object
{
static $tree;
static $routes;
static $smartyVars;
function &getInstance()
{
static $instance = array();
if (!$instance) {
$instance[0] = new Cms();
}
return $instance[0];
}
Смущает только массив. Задел на будущее, если вдруг понадобится создать несколько экземпляров?
конвеер?
Паттерн godfather:
Good. Someday, and that day may never come, I'll call upon you to do a service for me. But until that day, accept this instance as a gift on my daughter's wedding day.
<?php
/**
* @package ActiveRecord
*/
namespace ActiveRecord;
/**
* This implementation of the singleton pattern does not conform to the strong definition
* given by the "Gang of Four." The __construct() method has not be privatized so that
* a singleton pattern is capable of being achieved; however, multiple instantiations are also
* possible. This allows the user more freedom with this pattern.
*
* @package ActiveRecord
*/
abstract class Singleton
{
/**
* Array of cached singleton objects.
*
* @var array
*/
private static $instances = array();
/**
* Static method for instantiating a singleton object.
*
* @return object
*/
final public static function instance()
{
$class_name = get_called_class();
if (!isset(self::$instances[$class_name]))
self::$instances[$class_name] = new $class_name;
return self::$instances[$class_name];
}
/**
* Singleton objects should not be cloned.
*
* @return void
*/
Вообще конечно говно. В нормальных ЯП синглетон делается одной строчкой
// Singleton.h
class Singleton
{
private:
static Singleton * p_instance;
// Конструкторы и оператор присваивания недоступны клиентам
Singleton() {}
Singleton( const Singleton& );
Singleton& operator=( Singleton& );
public:
static Singleton * getInstance() {
if(!p_instance)
p_instance = new Singleton();
return p_instance;
}
};
// Singleton.cpp
#include "Singleton.h"
Singleton* Singleton::p_instance = 0;
В котлине
В питоне. Создаем метакласс, потом юзаем
И потом просто:
Груви:
Руби
В общем пых, как всегда, доказал свою ущербность
https://ruby-doc.org/stdlib-1.9.3/libdoc/singleton/rdoc/Singleton.html ;)
зы: ну честный конечно, что не так?
Это только фрагмент. Всё в комментарий не влезет.
Я вас умоляю... Написал один раз шаблон и делай себе Singleton<MyClazz>::get(). Другое дело, что синглетоны не нужны.
Синглтоны нужны, но управлять ими должен DI. Самопись не нужна, правда
http://govnokod.ru/22043#comment368652
победил котлин