PHP設計模式 - 享元模式

運用共享技術有效的支持大量細粒度的對象php

享元模式變化的是對象的存儲開銷this

享元模式中主要角色:對象

抽象享元(Flyweight)角色:此角色是全部的具體享元類的超類,爲這些類規定出須要實現的公共接口。那些須要外運狀態的操做能夠經過調用商業以參數形式傳入blog

具體享元(ConcreteFlyweight)角色:實現Flyweight接口,併爲內部狀態(若是有的話)拉回存儲空間。ConcreteFlyweight對象必須是可共享的。它所存儲的狀態必須是內部的接口

不共享的具體享元(UnsharedConcreteFlyweight)角色:並不是全部的Flyweight子類都須要被共享。Flyweigth使共享成爲可能,但它並不強制共享內存

享元工廠(FlyweightFactory)角色:負責建立和管理享元角色。本角色必須保證享元對象可能被系統適當地共享get

客戶端(Client)角色:本角色須要維護一個對全部享元對象的引用。本角色須要自行存儲全部享元對象的外部狀態io

享元模式的優勢:function

Flyweight模式能夠大幅度地下降內存中對象的數量class

享元模式的缺點:

Flyweight模式使得系統更加複雜

Flyweight模式將享元對象的狀態外部化,而讀取外部狀態使得運行時間稍微變長

享元模式適用場景:

當一下狀況成立時使用Flyweight模式:

1 一個應用程序使用了大量的對象

2 徹底因爲使用大量的對象,形成很大的存儲開銷

3 對象的大多數狀態均可變爲外部狀態

4 若是刪除對象的外部狀態,那麼能夠用相對較少的共享對象取代不少組對象

5 應用程序不依賴於對象標識

 

<?php
abstract class Resources{
    public $resource=null;

    abstract public function operate();
}

class unShareFlyWeight extends Resources{
    public function __construct($resource_str) {
        $this->resource = $resource_str;
    }

    public function operate(){
        echo $this->resource."<br>";
    }
}

class shareFlyWeight extends Resources{
    private $resources = array();

    public function get_resource($resource_str){
        if(isset($this->resources[$resource_str])) {
            return $this->resources[$resource_str];
        }else {
            return $this->resources[$resource_str] = $resource_str;
        }
    }

    public function operate(){
        foreach ($this->resources as $key => $resources) {
            echo $key.":".$resources."<br>";
        }
    }
}


// client
$flyweight = new shareFlyWeight();
$flyweight->get_resource('a');
$flyweight->operate();


$flyweight->get_resource('b');
$flyweight->operate();

$flyweight->get_resource('c');
$flyweight->operate();

// 不共享的對象,單獨調用
$uflyweight = new unShareFlyWeight('A');
$uflyweight->operate();

$uflyweight = new unShareFlyWeight('B');
$uflyweight->operate();
/* 輸出:
 a:a
 a:a
 b:b
 a:a
 b:b
 c:c
 A
 B */
相關文章
相關標籤/搜索