Development Blog

Collection of development articles I've put together...
Return to articles

Proxy Pattern

Create an interface to anything that is expensive or impossible to duplicate.
1
Likes
2 years ago
Design Patterns: Structural
Purpose

Create an interface to anything that is expensive or impossible to duplicate.

UML


Code

BankAccountProxy


namespace DesignPatterns\Structural\Proxy;

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

    public function getBalance(): int
    {
        // because calculating balance is so expensive,
        // the usage of BankAccount::getBalance() is delayed until it really is needed
        // and will not be calculated again for this instance

        if ($this->balance === null) {
            $this->balance = parent::getBalance();
        }

        return $this->balance;
    }
}

BankAccount


namespace DesignPatterns\Structural\Proxy;

interface BankAccount
{
    public function deposit(int $amount);

    public function getBalance(): int;
}

HeavyBankAccount


namespace DesignPatterns\Structural\Proxy;

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

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

    public function getBalance(): int
    {
        // this is the heavy part, imagine all the transactions even from
        // years and decades ago must be fetched from a database or web service
        // and the balance must be calculated from it

        return array_sum($this->transactions);
    }
}