这篇文章主要介绍了PHP策略模式定义与用法,结合实例形式简单分析了php策略模式的原理、实现与使用方法,需要的朋友可以参考下
本文实例讲述了PHP策略模式定义与用法。分享给大家供大家参考,具体如下:
概述
策略模式属于对象的行为模式。其用意是针对一组算法,将每个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化
UML图
策略模式中主要角色
这个模式设计到三个角色:
环境角色(Context):持有一个Strategy的引用
抽象策略(Strategy)角色:这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体的策略类所需的接口
具体策略(ConcreateStrategy)角色:包装了相关的算法或行为
使用场景
假设现在要设计一个购物车系统,一个最简单的情况就是把所有货品的单价乘上数量,但是实际情况肯定比这个复杂。例如:对普通会员无折扣,对中级会员提供8折优惠,对高级会员提供7折优惠。
根据上述描述,货品价格是根据以下几个算法中的一个进行的:
对普通会员无折扣
对中级会员8折
对高级会员7折
UML图
实现代码:
<?php /** * 策略抽象类 * @author wzy * */ interface Strategy { public function calPrice ($price); } /** * 普通会员策略类 * * @author wzy * */ class PrimaryStrategy implements Strategy { public function calPrice ($price) { echo "普通会员无折扣"; return $price; } } /** * 中级会员策略类 * * @author wzy * */ class MiddleStrategy implements Strategy { public function calPrice ($price) { echo "中级会员8折优惠"; return $price * 0.8; } } /** * 高级会员策略类 * * @author wzy * */ class HighStrategy implements Strategy { public function calPrice ($price) { echo "高级会员7折优惠"; return $price * 0.7; } } /** * Context实现类 * * @author wzy * */ class Price { /** * 具体的策略类对象 * * @var object */ private $strategyInstance; /** * 构造函数,传入一个具体的策略对象 * * @param object $instance */ public function __construct ($instance) { $this->strategyInstance = $instance; } /** * 计算货品的价格 * * @param double $price */ public function quote ($price) { return $this->strategyInstance->calPrice($price); } } /** * 客户端操作 */ $high = new HighStrategy(); $priceClass = new Price($high); $price = $priceClass->quote(400); echo $price; ?>
回顾策略模式
策略模式的重心不是如何实现算法,而是如何组织、调用这些算法,从而让程序结构更灵活,具有更好的扩展性和维护性
算法的平等性
策略模式一个很大的特点就是各个策略算法的平等性。对于一系列具体的策略算法,大家的地位是一样的,这样才能实现算法之间的互相转换
运行时策略的唯一性
运行期间,策略模式在每一个时刻只能使用一个具体的策略实现对象,虽然可以动态地在不同的策略实现中切换,但是同时只有一个
Atas ialah kandungan terperinci PHP策略模式定义与用法实例详解. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

AphpdependencyInjectionContainerisatoLthatMatagesClassDependencies, EnhancingCodeModularity, Testability, andMaintainability.itactsascentralHubforcreatingandinjectingdependencies, sheReducingTightCouplingandeaseaseaseSunittesting.

Pilih DependencyInjection (DI) Untuk aplikasi besar, servicelocator sesuai untuk projek kecil atau prototaip. 1) DI meningkatkan kesesuaian dan modulariti kod melalui suntikan pembina. 2) ServiceLocator memperoleh perkhidmatan melalui pendaftaran pusat, yang mudah tetapi boleh menyebabkan peningkatan gandingan kod.

Phpapplicationscanbeoptimizedforspeedandeficiencyby: 1) enablingopcacheinphp.ini, 2) menggunakan preparedSwithpdofordatabasequeries, 3) menggantikanloopswitharray_filterandarray_mapfordataprocessing, 4) configuringnginywinginywinyvinyvinginy

PhpeMailvalidationInvolvestHreesteps: 1) formatValidationingRegularExpressionStocheckTheemailFormat; 2) dnsvalidationtoensurethedomainhasavalidmxrecord;

Tomakephpapplicationsfaster, ikutiTheseSteps: 1) UseopcodecachinglikeopcachetostorePrecompiledscriptbytecode.2) minimizedatabasequeriesbyusingquerycachingandeficientindexing.3)

ToimprovePhpapPlicationspeed, ikutiTheSesteps: 1) EnableopCodeCachingWithApcutoreduceScriptExecutionTime.2) pelaksanaanDatabasequerycachingingPdotominimizedataBaseHits.3)

Suntikan ketergantungan (DI) dengan ketara meningkatkan kesesuaian kod PHP oleh kebergantungan transitif secara eksplisit. 1) Kelas Decoupling dan pelaksanaan khusus menjadikan ujian dan penyelenggaraan lebih fleksibel. 2) Di antara tiga jenis, pembina menyuntik kebergantungan ekspresi eksplisit untuk memastikan keadaan konsisten. 3) Gunakan bekas DI untuk menguruskan kebergantungan kompleks untuk meningkatkan kualiti kod dan kecekapan pembangunan.

DatabaseQueryoptimizationInpinvolvesseverSlegatiesToenhancePratePratePratePratePratePregiesToRperformance.1) selectOnlynessaryColumnStoReducedatatatransfer.2) UseIndexingTospeedupdatareTrieval.3) PrevancequerycachingToStoreresultSoffReFfeFfffffffffffffffffffffffffffffffffffffffffffferseprewfffffffffffersepresseprespersepresperseprespersepresperseprespersepresperseprespers


Alat AI Hot

Undresser.AI Undress
Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover
Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool
Gambar buka pakaian secara percuma

Clothoff.io
Penyingkiran pakaian AI

Video Face Swap
Tukar muka dalam mana-mana video dengan mudah menggunakan alat tukar muka AI percuma kami!

Artikel Panas

Alat panas

Muat turun versi mac editor Atom
Editor sumber terbuka yang paling popular

Versi Mac WebStorm
Alat pembangunan JavaScript yang berguna

MinGW - GNU Minimalis untuk Windows
Projek ini dalam proses untuk dipindahkan ke osdn.net/projects/mingw, anda boleh terus mengikuti kami di sana. MinGW: Port Windows asli bagi GNU Compiler Collection (GCC), perpustakaan import yang boleh diedarkan secara bebas dan fail pengepala untuk membina aplikasi Windows asli termasuk sambungan kepada masa jalan MSVC untuk menyokong fungsi C99. Semua perisian MinGW boleh dijalankan pada platform Windows 64-bit.

Penyesuai Pelayan SAP NetWeaver untuk Eclipse
Integrasikan Eclipse dengan pelayan aplikasi SAP NetWeaver.

VSCode Windows 64-bit Muat Turun
Editor IDE percuma dan berkuasa yang dilancarkan oleh Microsoft
