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 */
相关文章
相关标签/搜索