PHP设计模式系列(二十一):享元模式
来源:互联网 发布:java zxing 二维码 编辑:程序博客网 时间:2024/06/05 13:36
享元模式
享元模式(Flyweight Pattern):运用共享技术有效地支持大量细粒度对象的复用。系统只使用少量的对象,而这些对象都很相似,状态变化很小,可以实现对象的多次复用。由于享元模式要求能够共享的对象必须是细粒度对象,因此它又称为轻量级模式,它是一种对象结构型模式。
模式结构
享元模式包含如下角色:
- Flyweight: 抽象享元类
- ConcreteFlyweight: 具体享元类
- UnsharedConcreteFlyweight: 非共享具体享元类
- FlyweightFactory: 享元工厂类
结构图
PHP代码实现
<?php/** * 享元模式 */abstract class Flyweight { abstract public function operation($state);}//具体享元角色class ConcreteFlyweight extends Flyweight { private $state = null; public function __construct($state) { $this->state = $state; } public function operation($state) { var_dump('具体Flyweight:'.$state); }}//不共享的具体享元,客户端直接调用class UnsharedConcreteFlyweight extends Flyweight { private $state = null; public function __construct($state) { $this->state = $state; } public function operation($state) { var_dump('不共享的具体Flyweight:'.$state); }}//享元工厂角色class FlyweightFactory { private $flyweights; public function __construct() { $this->flyweights = array(); } public function getFlyweigth($state) { if (isset($this->flyweights[$state])) { return $this->flyweights[$state]; } else { return $this->flyweights[$state] = new ConcreteFlyweight($state); } }}$f = new FlyweightFactory();$a = $f->getFlyweigth('state A');$a->operation("other state A");$b = $f->getFlyweigth('state B');$b->operation('other state B');/* 不共享的对象,单独调用 */$u = new UnsharedConcreteFlyweight('state A');$u->operation('other state A');
运行结果
string '具体Flyweight:other state A' (length=29)string '具体Flyweight:other state B' (length=29)string '不共享的具体Flyweight:other state A' (length=41)
0 0
- PHP设计模式系列(二十一):享元模式
- Android设计模式(二十一)-享元模式
- 二十一、享元设计模式
- Java设计模式菜鸟系列(二十一)享元模式建模与实现
- 设计模式学习(十一):享元模式
- JAVA设计模式(十一)----享元模式
- PHP设计模式系列(十一):状态模式
- 设计模式之(十一)--享元模式(flyweight)
- Java设计模式之十一(享元模式)
- Java设计模式(十一) 享元模式
- 小话设计模式(十一)享元模式
- (十一)Java设计模式之享元模式
- Java设计模式(十一) 享元模式
- C++设计模式之十一:Flyweight(享元)
- 设计模式(十一)之 Flyweight(享元)
- 设计模式(二十一)---组合模式
- 设计模式(二十一) 状态模式
- JAVA系列-设计模式-享元模式
- #HDU3435#A new Graph Game(环+KM)
- Ubuntu输入su提示认证失败的解决方法
- 编译原理(1)
- 数据库的水平分割和垂直分割
- leetcode:Jump Game II
- PHP设计模式系列(二十一):享元模式
- kafka-01-基础知识
- 基于 Django1.10 文档的深入学习(27)—— django.conf.urls utility functions 之 url(),include(),static()
- 【C语言训练】亲密数
- ATM面向对象分析与设计之——顺序图
- ACM中字符串题常用算法
- 三步开启win10的ubuntu子系统
- DP---最长公共子序列&最长公共字串
- View 浮在软键盘上多种实现方式及踩坑