Расширьте абстрактный singleton-класс

Вид. Проверьте этот запрос:

SELECT total_worker_time/execution_count AS AvgCPU  
, total_worker_time AS TotalCPU
, total_elapsed_time/execution_count AS AvgDuration  
, total_elapsed_time AS TotalDuration  
, (total_logical_reads+total_physical_reads)/execution_count AS AvgReads 
, (total_logical_reads+total_physical_reads) AS TotalReads
, execution_count   
, SUBSTRING(st.TEXT, (qs.statement_start_offset/2)+1  
, ((CASE qs.statement_end_offset  WHEN -1 THEN datalength(st.TEXT)  
ELSE qs.statement_end_offset  
END - qs.statement_start_offset)/2) + 1) AS txt  
, query_plan
FROM sys.dm_exec_query_stats AS qs  
cross apply sys.dm_exec_sql_text(qs.sql_handle) AS st  
cross apply sys.dm_exec_query_plan (qs.plan_handle) AS qp 
ORDER BY 1 DESC

Это получит Вас запросы в кэше плана в порядке того, сколько ЦП они израсходовали. Можно периодически выполнять это, как в задании SQL Agent, и вставлять результаты в таблицу, чтобы удостовериться, что данные сохраняются вне перезагрузок.

при чтении результатов Вы, вероятно, поймете, почему мы не можем сопоставить те данные непосредственно назад к отдельной базе данных. Во-первых, единый запрос может также скрыть своего истинного родителя базы данных путем выполнения приемов как это:

USE msdb
DECLARE @StringToExecute VARCHAR(1000)
SET @StringToExecute = 'SELECT * FROM AdventureWorks.dbo.ErrorLog'
EXEC @StringToExecute

запрос был бы выполнен в MSDB, но он опросит результаты AdventureWorks. Где мы должны присвоить потребление ресурсов ЦП?

Это ухудшается когда Вы:

  • Соединение между несколькими базами данных
  • Выполнение транзакция в нескольких базах данных и усилие по блокировке охватывают несколько баз данных
  • задания SQL Agent Выполнения в MSDB, которые "работают" в MSDB, но создают резервную копию отдельных баз данных

, Это продолжается и на. Вот почему это имеет смысл к мелодии производительности на уровне запроса вместо уровня базы данных.

В SQL Server 2008R2, Microsoft представила управление производительностью и функции управления приложением, которые позволят нам упаковать единую базу данных в распространяемом и развертываемом пакете DAC, и они обещают функциям помочь справиться с производительностью отдельных баз данных и их приложений. Это все еще не делает то, что Вы ищете, все же.

Для больше из тех, проверьте репозиторий T-SQL в Жабе SQL Server В мире Wiki (раньше в SQLServerPedia) .

Обновленный на 1/29 для включения общих количеств вместо просто средних чисел.

20
задан Deniss Kozlovs 30 November 2009 в 09:31
поделиться

6 ответов

In PHP methods, self always refers to the class where the method is defined. Since version 5.3.0, PHP supports “late static binding”, where you can use the static keyword to access overridden static methods, as well as the function get_called_class() to get the name of the derived class in static context.

However, your design has a major flaw: The static property $factory defined in Base_Factory is shared across all derived classes. Therefore, the first time a singleton is created and stored in this property, all other calls to getInstance() will return the same object, no matter what derived class is used.

You could use a static dictionary mapping class names to singleton objects:

abstract class Base_Factory {
    private static $_instances = array();
    public static function getInstance() {
        $class = get_called_class();
        if (!isset(self::$_instances[$class])) {
            self::$_instances[$class] = new $class();
        }
        return self::$_instances[$class];
    }
}

Oh, one more thing: The fact that you are looking for a possibility to re-use code for singleton objects could be a cue to the fact that you are over-using the singleton design pattern! Ask yourself if the classes you are planning to implement as singletons really are singletons and if there will be no use case where you might want to have multiple instances of the particular class.

Often it is much better to use just one singleton representing the current “application context” that provides accessors for objects that are singletons with respect to this context.

36
ответ дан 29 November 2019 в 23:27
поделиться

Зарегистрируйте свои синглтоны в простом классе вроде этого

class Singletons {
    static private $singleton = array();
    public function getSingleton($class) {
    if (!isset(self::$singleton[$class])) {
        self::$singleton[$class] = new $class;
    }
    return self::$singleton[$class];
    }
}

Затем сделайте это

class aSingleton {
    public $i;
    public function test() {
    ++$this->i;
    echo get_class() . " called {$this->i} times\n";
    }
}

Singletons::getSingleton('aSingleton')->test();
Singletons::getSingleton('aSingleton')->test();

Выход

aSingleton called 1 times
aSingleton called 2 times
1
ответ дан 29 November 2019 в 23:27
поделиться

By definition abstract classess cannot be instantiated in PHP like any other object oriented languages. So your Base_Factory should be interface instead of abstract class.

From the PHP manual: "It is not allowed to create an instance of a class that has been defined as abstract."

-1
ответ дан 29 November 2019 в 23:27
поделиться

PHP >= 5.3 only

abstract class Base_Factory {
    protected static $factory;
    public static function getInstance(){
        if (!self::$factory) {
            $class = get_called_class();
            self::$factory = new $class();
        }
        return self::$factory;
    }
}
4
ответ дан 29 November 2019 в 23:27
поделиться

Well you could do a check to make sure the class calling the function isn't the Base_Factory.

if(__CLASS__!='Base_Factory')

Then use $this instead of self to refer to the current object instead of the current class.

if (!$this->factory)
        $this->factory = new self();
    return $this->factory;
-2
ответ дан 29 November 2019 в 23:27
поделиться

PHP 5.3+

abstract class Singleton
{
    /**
     * Instance
     *
     * @var Singleton
     */
    protected static $_instance;

    /**
     * Constructor
     *
     * @return void
     */
    protected function __construct() {}

    /**
     * Get instance
     *
     * @return Singleton
     */
    public final static function getInstance() {
        if (null === static::$_instance) {
            static::$_instance = new static();
        }

        return static::$_instance;
    }
}
9
ответ дан 29 November 2019 в 23:27
поделиться
Другие вопросы по тегам:

Похожие вопросы: