mirror of
https://github.com/DesignPatternsPHP/DesignPatternsPHP.git
synced 2025-08-01 20:50:15 +02:00
Merge pull request #192 from marius-rizac/fixed-wrong-singleton-pattern
Fixed wrong implementation of Singleton Pattern
This commit is contained in:
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
namespace DesignPatterns\Creational\Singleton;
|
namespace DesignPatterns\Creational\Singleton;
|
||||||
|
|
||||||
|
use DesignPatterns\Creational\Singleton\SingletonPatternViolationException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* class Singleton
|
* class Singleton
|
||||||
*/
|
*/
|
||||||
@@ -36,19 +38,21 @@ class Singleton
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* prevent the instance from being cloned
|
* prevent the instance from being cloned
|
||||||
*
|
* @throws SingletonPatternViolationException
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
private function __clone()
|
public final function __clone()
|
||||||
{
|
{
|
||||||
|
throw new SingletonPatternViolationException('This is a Singleton. Clone is forbidden');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* prevent from being unserialized
|
* prevent from being unserialized
|
||||||
*
|
* @throws SingletonPatternViolationException
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
private function __wakeup()
|
public final function __wakeup()
|
||||||
{
|
{
|
||||||
|
throw new SingletonPatternViolationException('This is a Singleton. __wakeup usage is forbidden');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -0,0 +1,8 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace DesignPatterns\Creational\Singleton;
|
||||||
|
|
||||||
|
class SingletonPatternViolationException extends \Exception
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
@@ -26,4 +26,25 @@ class SingletonTest extends \PHPUnit_Framework_TestCase
|
|||||||
$meth = $refl->getMethod('__construct');
|
$meth = $refl->getMethod('__construct');
|
||||||
$this->assertTrue($meth->isPrivate());
|
$this->assertTrue($meth->isPrivate());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @expectedException \DesignPatterns\Creational\Singleton\SingletonPatternViolationException
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function testNoCloneAllowed()
|
||||||
|
{
|
||||||
|
$obj1 = Singleton::getInstance();
|
||||||
|
$obj2 = clone $obj1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @expectedException \DesignPatterns\Creational\Singleton\SingletonPatternViolationException
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function testNoSerializationAllowed()
|
||||||
|
{
|
||||||
|
$obj1 = Singleton::getInstance();
|
||||||
|
$serialized = serialize($obj1);
|
||||||
|
$obj2 = unserialize($serialized);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user