Home Backend Development PHP Tutorial PHP设计模式之享元模式

PHP设计模式之享元模式

Jun 23, 2016 pm 01:03 PM

享元模式属于结构型模式

概述:运用共享技术有效地支持大量细粒度的对象

享元模式:

运用共享技术有效的支持大量细粒度的对象

享元模式变化的是对象的存储开销

享元模式中主要角色:

抽象享元(Flyweight)角色:此角色是所有的具体享元类的超类,为这些类规定出需要实现的公共接口。那些需要外运状态的操作可以通过调用商业以参数形式传入

具体享元(ConcreteFlyweight)角色:实现Flyweight接口,并为内部状态(如果有的话)拉回存储空间。ConcreteFlyweight对象必须是可共享的。它所存储的状态必须是内部的

不共享的具体享元(UnsharedConcreteFlyweight)角色:并非所有的Flyweight子类都需要被共享。Flyweigth使共享成为可能,但它并不强制共享

享元工厂(FlyweightFactory)角色:负责创建和管理享元角色。本角色必须保证享元对象可能被系统适当地共享

客户端(Client)角色:本角色需要维护一个对所有享元对象的引用。本角色需要自行存储所有享元对象的外部状态

享元模式的优点:

Flyweight模式可以大幅度地降低内存中对象的数量

享元模式的缺点:

Flyweight模式使得系统更加复杂

Flyweight模式将享元对象的状态外部化,而读取外部状态使得运行时间稍微变长

享元模式适用场景:

当一下情况成立时使用Flyweight模式:

1 一个应用程序使用了大量的对象

2 完全由于使用大量的对象,造成很大的存储开销

3 对象的大多数状态都可变为外部状态

4 如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象

5 应用程序不依赖于对象标识

享元模式与其它模式:

单例模式(Singleton):客户端要引用享元对象,是通过工厂对象创建或者获得的,客户端每次引用一个享元对象,都是可以通过同一个工厂对象来引用所需要的享元对象。因此,可以将享元工厂设计成单例模式,这样就可以保证客户端只引用一个工厂实例。因为所有的享元对象都是由一个工厂对象统一管理的,所以在客户端没有必要引用多个工厂对象。不管是单纯享元模式还是复合享元模式中的享元工厂角色,都可以设计成为单例模式,对于结果是不会有任何影响的。

Composite模式:复合享元模式实际上是单纯享元模式与合成模式的组合。单纯享元对象可以作为树叶对象来讲,是可以共享的,而复合享元对象可以作为树枝对象,因此在复合享元角色中可以添加聚集管理方法

/**

* 抽象享元角色

*/

abstract class Flyweight{

abstract public function operation($state);

}

/**

* 具体享元角色

*/

class ConcreteFlyweight extends Flyweight{

private $_intrinsicState = null;

/**

* @param $state 内部状态

*/

public function __construct($state){

$this->_intrinsicState = $state;

}

public function operation($state) {

echo 'ConcreteFlyweight operation, Intrinsic State = ' . $this->_intrinsicState

. ' Extrinsic State = ' . $state . '
';

}

}

/**

* 不共享的具体享元,客户端直接调用

*/

class UnsharedConcreteFlyweight extends Flyweight {

private $_intrinsicState = null;

/**

* 构造方法

* @param string $state 内部状态

*/

public function __construct($state) {

$this->_intrinsicState = $state;

}

public function operation($state) {

echo 'UnsharedConcreteFlyweight operation, Intrinsic State = ' . $this->_intrinsicState

. ' Extrinsic State = ' . $state . '
';

}

}

/**

* 享元工厂角色

*/

class FlyweightFactory{

private $_flyweights;

public function __construct(){

$this->_flyweights = array();

}

public function getFlyweight($state){

if(isset($this->_flyweights[$state])){

return $this->_flyweights[$state];

}

return $this->_flyweights[$state] = new ConcreteFlyweight($state);

}

}

/**

* 享元模式

*/

public function actionFlyweight(){

Yii::import('ext.flyweight.*');

$flyweightFactory = new FlyweightFactory();

$flyweightFactory->getFlyweight('state A');

$flyweightFactory->operation('other state A');

$flyweightFactory = new FlyweightFactory();

$flyweightFactory->getFlyweight('state B');

$flyweightFactory->operation('other state B');

$flyweightFactory = new FlyweightFactory();

$flyweightFactory->getFlyweight('state C');

$flyweightFactory->operation('other state C');

/* 不共享的对象,单独调用 */

$uflyweight = new UnsharedConcreteFlyweight('state A');

$uflyweight->operation('other state A');

}

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Discover File Downloads in Laravel with Storage::download Discover File Downloads in Laravel with Storage::download Mar 06, 2025 am 02:22 AM

The Storage::download method of the Laravel framework provides a concise API for safely handling file downloads while managing abstractions of file storage. Here is an example of using Storage::download() in the example controller:

HTTP Method Verification in Laravel HTTP Method Verification in Laravel Mar 05, 2025 pm 04:14 PM

Laravel simplifies HTTP verb handling in incoming requests, streamlining diverse operation management within your applications. The method() and isMethod() methods efficiently identify and validate request types. This feature is crucial for building

See all articles