Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Flyweight pattern
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== PHP === <syntaxhighlight lang="php"><?php class CoffeeFlavour { private static array $CACHE = []; private function __construct(private string $name) {} public static function intern(string $name): self { self::$CACHE[$name] ??= new self($name); return self::$CACHE[$name]; } public static function flavoursInCache(): int { return count(self::$CACHE); } public function __toString(): string { return $this->name; } } class Order { private function __construct( private CoffeeFlavour $flavour, private int $tableNumber ) {} public static function create(string $flavourName, int $tableNumber): self { $flavour = CoffeeFlavour::intern($flavourName); return new self($flavour, $tableNumber); } public function __toString(): string { return "Serving {$this->flavour} to table {$this->tableNumber}"; } } class CoffeeShop { private array $orders = []; public function takeOrder(string $flavour, int $tableNumber) { $this->orders[] = Order::create($flavour, $tableNumber); } public function service() { print(implode(PHP_EOL, $this->orders).PHP_EOL); } } $shop = new CoffeeShop(); $shop->takeOrder("Cappuccino", 2); $shop->takeOrder("Frappe", 1); $shop->takeOrder("Espresso", 1); $shop->takeOrder("Frappe", 897); $shop->takeOrder("Cappuccino", 97); $shop->takeOrder("Frappe", 3); $shop->takeOrder("Espresso", 3); $shop->takeOrder("Cappuccino", 3); $shop->takeOrder("Espresso", 96); $shop->takeOrder("Frappe", 552); $shop->takeOrder("Cappuccino", 121); $shop->takeOrder("Espresso", 121); $shop->service(); print("CoffeeFlavor objects in cache: ".CoffeeFlavour::flavoursInCache().PHP_EOL); </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)