享元模式其實就是共享獨享模式,減小重複實例化對象的操做,從而將實例化對象形成的內存開銷降到最低。php
享元模式嘗試重用現有的同類對象,若是未找到匹配的對象,則建立新對象。咱們將經過建立 5 個對象來畫出 20 個分佈於不一樣位置的圓來演示這種模式。因爲只有 5 種可用的顏色,因此 color 屬性被用來檢查現有的 Circle 對象。設計模式
<?php interface Shape{ public function draw(); } class Circle implements Shape{ private $color; private $num; public function __construct($color){ $this->color = $color; } public function draw(){ echo "this is a {$this->color} circle {$this->num} \n"; } public function setNum($num){ $this->num = $num; } } class ShapeFactory{ public static $shape_arr = []; public static function getShape($color){ if(!array_key_exists($color,static::$shape_arr)){ static::$shape_arr[$color] = new Circle($color); } return static::$shape_arr[$color]; } } $colors = ["Red", "Green", "Blue", "White", "Black"]; for ($i=0; $i < 20; $i++) { $a = $i%5; $circle = ShapeFactory::getShape($colors[$a]); $circle->setNum($i); $circle->draw(); }
輸出this
this is a Red circle 0 this is a Green circle 1 this is a Blue circle 2 this is a White circle 3 this is a Black circle 4 this is a Red circle 5 this is a Green circle 6 this is a Blue circle 7 this is a White circle 8 this is a Black circle 9 this is a Red circle 10 this is a Green circle 11 this is a Blue circle 12 this is a White circle 13 this is a Black circle 14 this is a Red circle 15 this is a Green circle 16 this is a Blue circle 17 this is a White circle 18 this is a Black circle 19
注意:享元模式適用於對象存在時間不長的狀況,就像例子中畫一個圓形只要這個圓形畫完後其對象就沒有意義啦,這時咱們將這個對象的屬性改變後成爲一個新的對象是能夠的。假設咱們是在一個建立遊戲人物的場景中使用,當建立了某個類型的英雄人物對象以後,咱們想要再建立一個相同類型不一樣屬性的英雄人物時,則不適合使用這種設計模式,由於後來的英雄人物對象會是前一個對象改變屬性後生成的,這將致使以前的英雄就不存在啦。spa