search
HomeBackend DevelopmentPHP TutorialPHP设计模式——享元模式_PHP教程

PHP设计模式——享元模式

声明:本系列博客参考资料《大话设计模式》,作者程杰。

享元模式使用共享物件,用来尽可能减少内存使用量以及分享资讯给尽可能多的相似物件;它适合用于只是因重复而导致使用无法令人接受的大量内存的大量物件。通常物件中的部分状态是可以分享。常见做法是把它们放在外部数据结构,当需要使用时再将它们传递给享元。

 

UML类图:

\

 

角色分析:

享元工厂角色(FWFactory):创建并管理BlogModel对象。

所有具体享元父接口角色(BolgModel):接受并作用与外部状态。

具体享元角色(JobsBlog):具体变化点,为内部对象增加储存空间。

 

代码实现:

 

<!--?php
/**
 * Created by PhpStorm.
 * User: LYL
 * Date: 2015/5/16
 * Time: 12:00
 */

/**所有享元父接口角色
 * Interface IBlogModel
 */
interface IBlogModel
{
    function showTime();
    function showColor();
}

/**乔布斯的博客模板
 * Class JobsBlog
 */
class JobsBlog implements IBlogModel
{
    function showTime()
    {
        echo 纽约时间:5点整<br/-->;
    }

    function showColor()
    {
        echo 
Jobs
; } } /**雷军博客模板 * Class LeiJunBlog */ class LeiJunBlog implements IBlogModel { function showTime() { echo 北京时间:17点整
; } function showColor() { echo
雷军
; } } /**博客模板工厂 * Class BlogFactory */ class BlogFactory { private $model=array(); function getBlogModel($name) { if(isset($this->model[$name])) { echo 我是缓存里的
; return $this->model[$name]; } else { try { echo 我是新创建的
; $class=new ReflectionClass($name); $this->model[$name]=$class->newInstance(); return $this->model[$name]; } catch(ReflectionException $e) { echo 你要求的对象我不能创建哦。
; return null; } } } }
客户端调用代码:

 

 

header(Content-Type:text/html;charset=utf-8);
//------------------------门面模式测试代码------------------
require_once ./Flyweight/Flyweight.php;
$factory=new BlogFactory();
$jobs=$factory->getBlogModel(JobsBlog);
if($jobs)
{
    $jobs->showTime();
    $jobs->showColor();
}


$jobs1=$factory->getBlogModel(JobsBlog);
if($jobs1)
{
    $jobs1->showTime();
    $jobs1->showColor();
}


$leijun=$factory->getBlogModel(LeiJunBlog);
if($leijun)
{
    $leijun->showTime();
    $leijun->showColor();
}


$leijun1=$factory->getBlogModel(LeiJunBlog);
if($leijun1)
{
    $leijun1->showTime();
    $leijun1->showColor();
}

$aFanda=$factory->getBlogModel(aFanda);
if($aFanda)
{
    $aFanda->showTime();
    $aFanda->showColor();
}

 

优点:

1.减少运行时对象实例的个数,节省内存

2.将许多“虚拟”对象的状态集中管理

缺点:

一旦被实现,单个的逻辑实现将无法拥有独立而不同的行为

 

适用场景:

当一个类有许多的实例,而这些实例能被同一方法控制的时候,我们就可以使用享元模式。


 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1000540.htmlTechArticlePHP设计模式——享元模式 声明:本系列博客参考资料《大话设计模式》,作者程杰。 享元模式使用共享物件,用来尽可能减少内存使用量...
Statement
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools