Skip to content

Commit

Permalink
✅ Add Proxy pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
twent committed Mar 7, 2023
1 parent 2cec670 commit d55650c
Show file tree
Hide file tree
Showing 5 changed files with 75 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,4 @@ How to dev:
8. Facade
9. Fluent Interface
10. Flyweight
11. Proxy
11 changes: 11 additions & 0 deletions src/Patterns/Structural/Proxy/BankAccount.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

namespace Twent\DesignPatterns\Structural\Proxy;

interface BankAccount
{
public function deposit(int $amount);
public function getBalance(): int;
}
20 changes: 20 additions & 0 deletions src/Patterns/Structural/Proxy/BankAccountProxy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

declare(strict_types=1);

namespace Twent\DesignPatterns\Structural\Proxy;

final class BankAccountProxy extends HeavyBankAccount implements BankAccount
{
private ?int $balance = null;

public function getBalance(): int
{
if (! $this->balance) {
// Call heavy operations
$this->balance = parent::getBalance();
}

return $this->balance;
}
}
21 changes: 21 additions & 0 deletions src/Patterns/Structural/Proxy/HeavyBankAccount.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

namespace Twent\DesignPatterns\Structural\Proxy;

class HeavyBankAccount implements BankAccount
{
private array $transactions = [];

public function deposit(int $amount)
{
$this->transactions[] = $amount;
}

public function getBalance(): int
{
// Здесь ресурсоёмкие расчёты, "дорогое" взаимодействие с БД и т.д.
return array_sum($this->transactions);
}
}
22 changes: 22 additions & 0 deletions tests/Feature/Structural/ProxyTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace Structural;

use Tests\TestCase;
use Twent\DesignPatterns\Structural\Proxy\BankAccountProxy;

final class ProxyTest extends TestCase
{
public function testProxyPatternWorksFine(): void
{
$bankAccount = new BankAccountProxy();
$bankAccount->deposit(3000);
$this->assertSame(3000, $bankAccount->getBalance());

$bankAccount->deposit(5000);
// Heavy operations isn't running again
$this->assertSame(3000, $bankAccount->getBalance());
}
}

0 comments on commit d55650c

Please sign in to comment.