Singleton added

This commit is contained in:
2025-07-03 12:02:19 +03:00
commit 91f8ded888
31 changed files with 5025 additions and 0 deletions

View File

@@ -0,0 +1,105 @@
<?php
/**
* @package: patterns
* @author: Yevhen Odynets
* @date: 2025-07-03
* @time: 07:00
*/
declare(strict_types = 1);
namespace Pattern\Creational;
use RuntimeException;
/**
* The Singleton class defines the `GetInstance` method that serves as an
* alternative to constructor and lets clients access the same instance of this
* class over and over.
*/
class Singleton
{
/**
* The Singleton's instance is stored in a static field. This field is an
* array, because we'll allow our Singleton to have subclasses. Each item in
* this array will be an instance of a specific Singleton's subclass. You'll
* see how this works in a moment.
*/
private static array $instances = [];
public ?string $value = null;
/**
* The Singleton's constructor should always be private to prevent direct
* construction calls with the `new` operator.
*/
protected function __construct() {}
/**
* This is the static method that controls the access to the singleton
* instance. On the first run, it creates a singleton object and places it
* into the static field. On subsequent runs, it returns the client existing
* object stored in the static field.
*
* This implementation lets you subclass the Singleton class while keeping
* just one instance of each subclass around.
*/
public static function getInstance(?string $message = null): Singleton
{
$cls = static::class;
/** @noinspection ForgottenDebugOutputInspection */
dump(trim($message . ': ' . $cls, ' :'));
if (!isset(self::$instances[$cls])) {
self::$instances[$cls] = new static();
}
return self::$instances[$cls];
}
/**
* Singletons should not be restorable from strings.
*/
public function __wakeup()
{
throw new RuntimeException("Cannot unserialize a singleton.");
}
/**
* Finally, any singleton should define some business logic, which can be
* executed on its instance.
*/
public function someBusinessLogic(): void
{
echo 'I AM SINGLETON: ' . date('H:i:s') . '<br>';
}
/**
* Singletons should not be cloneable.
*/
protected function __clone() {}
/**
* @return string|null
*/
public function getValue(): ?string
{
return $this->value;
}
/**
* @param string|null $value
*
* @return $this
*/
public function setValue(?string $value): static
{
$this->value = $value;
return $this;
}
}

View File

@@ -0,0 +1,24 @@
<?php
/**
* @package: patterns
* @author: Yevhen Odynets
* @date: 2025-07-03
* @time: 10:22
*/
//phpcs:ignore
declare(strict_types = 1);
namespace Pattern\Creational\Sub;
use Contracts\SingleInterface;
use Pattern\Creational\Singleton;
class Single extends Singleton implements SingleInterface
{
public function childish(): void
{
/** @noinspection ForgottenDebugOutputInspection */
dump(__METHOD__);
}
}