PHP7 Singleton und Multiton

This commit is contained in:
Dominik Liebler
2016-09-22 13:15:24 +02:00
parent 4cf817b143
commit 6a98bcb73b
5 changed files with 37 additions and 66 deletions

View File

@@ -2,7 +2,7 @@
namespace DesignPatterns\Creational\Singleton;
class Singleton
final class Singleton
{
/**
* @var Singleton
@@ -31,21 +31,15 @@ class Singleton
/**
* prevent the instance from being cloned (which would create a second instance of it)
*
* @throws SingletonPatternViolationException
*/
final public function __clone()
private function __clone()
{
throw new \Exception('This is a Singleton. __clone is forbidden');
}
/**
* prevent from being unserialized (which would create a second instance of it)
*
* @throws SingletonPatternViolationException
*/
final public function __wakeup()
private function __wakeup()
{
throw new \Exception('This is a Singleton. __wakeup is forbidden');
}
}

View File

@@ -1,7 +0,0 @@
<?php
namespace DesignPatterns\Creational\Singleton;
class SingletonPatternViolationException extends \Exception
{
}

View File

@@ -14,23 +14,4 @@ class SingletonTest extends \PHPUnit_Framework_TestCase
$this->assertInstanceOf('DesignPatterns\Creational\Singleton\Singleton', $firstCall);
$this->assertSame($firstCall, $secondCall);
}
/**
* @expectedException \DesignPatterns\Creational\Singleton\SingletonPatternViolationException
*/
public function testNoCloneAllowed()
{
$obj1 = Singleton::getInstance();
$obj2 = clone $obj1;
}
/**
* @expectedException \DesignPatterns\Creational\Singleton\SingletonPatternViolationException
*/
public function testNoSerializationAllowed()
{
$obj1 = Singleton::getInstance();
$serialized = serialize($obj1);
unserialize($serialized);
}
}