Skip to content

Commit 35aa338

Browse files
committed
create-singleton-design-pattern
1 parent 7a700a2 commit 35aa338

File tree

3 files changed

+82
-0
lines changed

3 files changed

+82
-0
lines changed

composer.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@
1414
"Growthdev\\DesignPatterns\\": "src/"
1515
}
1616
},
17+
"autoload-dev": {
18+
"psr-4": {
19+
"Growthdev\\DesignPatterns\\Tests\\": "tests/"
20+
}
21+
},
1722
"authors": [
1823
{
1924
"name": "Walmir Silva",
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace DesignPatterns\Creational\Singleton;
6+
7+
final class Singleton
8+
{
9+
private static ?Singleton $instance = null;
10+
11+
public static function getInstance(): Singleton
12+
{
13+
if (null === static::$instance) {
14+
static::$instance = new static();
15+
}
16+
17+
return static::$instance;
18+
}
19+
20+
protected function __construct()
21+
{
22+
}
23+
24+
private function __clone()
25+
{
26+
}
27+
28+
private function __wakeup()
29+
{
30+
}
31+
32+
private function __sleep()
33+
{
34+
}
35+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Growthdev\DesignPatterns\Creational\Singleton;
6+
7+
use DesignPatterns\Creational\Singleton\Singleton;
8+
use PHPUnit\Framework\TestCase;
9+
10+
final class SingletonTest extends TestCase
11+
{
12+
public function testShoudBeTheSameInstanceForTwoObjets(): void
13+
{
14+
$firstInstance = Singleton::getInstance();
15+
$secondInstance = SingleTon::getInstance();
16+
17+
$this->assertSame($firstInstance, $secondInstance);
18+
}
19+
20+
public function testThrowErrorWhenTryToCreateInstance(): void
21+
{
22+
$this->expectException(Error::class);
23+
24+
$instance = new Singleton();
25+
}
26+
27+
public function testThrowExceptionWhenTryToClone(): void
28+
{
29+
$this->expectException(Error::class);
30+
31+
$instance = Singleton::getInstance();
32+
$clone = clone $instance;
33+
}
34+
35+
public function testThrowExceptionWhenTryToSerialize(): void
36+
{
37+
$this->expectException(Error::class);
38+
39+
$instance = Singleton::getInstance();
40+
$serialize = serialize($instance);
41+
}
42+
}

0 commit comments

Comments
 (0)