From d55650c02c544287b843d76ea13f166fd4e813a3 Mon Sep 17 00:00:00 2001 From: twent Date: Tue, 7 Mar 2023 16:49:45 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=85=20Add=20Proxy=20pattern?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + src/Patterns/Structural/Proxy/BankAccount.php | 11 ++++++++++ .../Structural/Proxy/BankAccountProxy.php | 20 +++++++++++++++++ .../Structural/Proxy/HeavyBankAccount.php | 21 ++++++++++++++++++ tests/Feature/Structural/ProxyTest.php | 22 +++++++++++++++++++ 5 files changed, 75 insertions(+) create mode 100644 src/Patterns/Structural/Proxy/BankAccount.php create mode 100644 src/Patterns/Structural/Proxy/BankAccountProxy.php create mode 100644 src/Patterns/Structural/Proxy/HeavyBankAccount.php create mode 100644 tests/Feature/Structural/ProxyTest.php diff --git a/README.md b/README.md index 9fe367d..f46bf44 100644 --- a/README.md +++ b/README.md @@ -34,3 +34,4 @@ How to dev: 8. Facade 9. Fluent Interface 10. Flyweight + 11. Proxy diff --git a/src/Patterns/Structural/Proxy/BankAccount.php b/src/Patterns/Structural/Proxy/BankAccount.php new file mode 100644 index 0000000..4d0cabd --- /dev/null +++ b/src/Patterns/Structural/Proxy/BankAccount.php @@ -0,0 +1,11 @@ +balance) { + // Call heavy operations + $this->balance = parent::getBalance(); + } + + return $this->balance; + } +} diff --git a/src/Patterns/Structural/Proxy/HeavyBankAccount.php b/src/Patterns/Structural/Proxy/HeavyBankAccount.php new file mode 100644 index 0000000..8d4aa3c --- /dev/null +++ b/src/Patterns/Structural/Proxy/HeavyBankAccount.php @@ -0,0 +1,21 @@ +transactions[] = $amount; + } + + public function getBalance(): int + { + // Здесь ресурсоёмкие расчёты, "дорогое" взаимодействие с БД и т.д. + return array_sum($this->transactions); + } +} diff --git a/tests/Feature/Structural/ProxyTest.php b/tests/Feature/Structural/ProxyTest.php new file mode 100644 index 0000000..9a6a15b --- /dev/null +++ b/tests/Feature/Structural/ProxyTest.php @@ -0,0 +1,22 @@ +deposit(3000); + $this->assertSame(3000, $bankAccount->getBalance()); + + $bankAccount->deposit(5000); + // Heavy operations isn't running again + $this->assertSame(3000, $bankAccount->getBalance()); + } +}