PHP Strategy Pattern
The content shared with you in this article is about PHP strategy model, which has certain reference value. Friends in need can refer to it
For example: an e-commerce website system, targeting men and women Users need to jump to different product categories, and all advertising slots display different ads
6 Project Application
6.1 Requirements Description
Implement a shopping mall cashier system. Products can have normal charging, discount charging, rebate charging and other modes (from "Dahua Design Pattern")
6.2 Requirements Analysis
According to the requirements, the charging operation can be designed as an interface algorithm. Normal charging, discount charging, and rebate charging all inherit this interface to implement different strategies. algorithm. Then design an environment class to maintain instances of the policy.
6.3 Design architecture diagram
6.4 Program source code download
http://download.csdn.net/detail/clevercode/8700009
6.5 Program Description
1) strategy.php
[php] view plain copy
<?php /** * strategy.php * * 策略类:定义了一系列的算法,这些算法都是完成的相同工作,但是实现不同。 * * 特别声明:本源代码是根据《大话设计模式》一书中的C#案例改成成PHP代码,和书中的 * 代码会有改变和优化。 * * Copyright (c) 2015 http://blog.csdn.net/CleverCode * * modification history: * -------------------- * 2015/5/5, by CleverCode, Create * */ // 定义接口现金策略,每种策略都是具体实现acceptCash,但都是实现收取现金功能 interface ICashStrategy{ // 收取现金 public function acceptCash($money); } // 正常收取策略 class NormalStrategy implements ICashStrategy{ /** * 返回正常金额 * * @param double $money 金额 * @return double 金额 */ public function acceptCash($money){ return $money; } } // 打折策略 class RebateStrategy implements ICashStrategy{ // 打折比例 private $_moneyRebate = 1; /** * 构造函数 * * @param double $rebate 比例 * @return void */ public function __construct($rebate){ $this->_moneyRebate = $rebate; } /** * 返回正常金额 * * @param double $money 金额 * @return double 金额 */ public function acceptCash($money){ return $this->_moneyRebate * $money; } } // 返利策略 class ReturnStrategy implements ICashStrategy{ // 返利条件 private $_moneyCondition = null; // 返利多少 private $_moneyReturn = null; /** * 构造函数 * * @param double $moneyCondition 返利条件 * @return double $moneyReturn 返利多少 * @return void */ public function __construct($moneyCondition, $moneyReturn){ $this->_moneyCondition = $moneyCondition; $this->_moneyReturn = $moneyReturn; } /** * 返回正常金额 * * @param double $money 金额 * @return double 金额 */ public function acceptCash($money){ if (!isset($this->_moneyCondition) || !isset($this->_moneyReturn) || $this->_moneyCondition == 0) { return $money; } return $money - floor($money / $this->_moneyCondition) * $this->_moneyReturn; } }
2) strategyPattern.php
view plain copy
<?php /** * strategyPattern.php * * 设计模式:策略模式 * * 模式简介: * 它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化, * 不会影响到使用算法的客户。 * 策略模式是一种定义一些列算法的方法,从概念上来看,所有这些算法完成的都是 * 相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类 * 与使用算法类的耦合。 * 本源码中的各种结账方式,其实都是在结账,但是具体的实现确实不同的。策略模式与 * 命令模式不同的是,命令模式的算法是相互独立的,每个命令做的工作是不同的。而策略模式 * 却是在做通一种工作。 * * 特别声明:本源代码是根据《大话设计模式》一书中的C#案例改成成PHP代码,和书中的 * 代码会有改变和优化。 * * Copyright (c) 2015 http://blog.csdn.net/CleverCode * * modification history: * -------------------- * 2015/5/14, by CleverCode, Create * */ // 加载所有的策略 include_once ('strategy.php'); // 创建一个环境类,根据不同的需求调用不同策略 class CashContext{ // 策略 private $_strategy = null; /** * 构造函数 * * @param string $type 类型 * @return void */ public function __construct($type = null){ if (!isset($type)) { return; } $this->setCashStrategy($type); } /** * 设置策略(简单工厂与策略模式混合使用) * * @param string $type 类型 * @return void */ public function setCashStrategy($type){ $cs = null; switch ($type) { // 正常策略 case 'normal' : $cs = new NormalStrategy(); break; // 打折策略 case 'rebate8' : $cs = new RebateStrategy(0.8); break; // 返利策略 case 'return300to100' : $cs = new ReturnStrategy(300, 100); break; } $this->_strategy = $cs; } /** * 获取结果 * * @param double $money 金额 * @return double */ public function getResult($money){ return $this->_strategy->acceptCash($money); } /** * 获取结果 * * @param string $type 类型 * @param int $num 数量 * @param double $price 单价 * @return double */ public function getResultAll($type, $num, $price){ $this->setCashStrategy($type); return $this->getResult($num * $price); } } /* * 客户端类 * 让客户端和业务逻辑尽可能的分离,降低客户端和业务逻辑算法的耦合, * 使业务逻辑的算法更具有可移植性 */ class Client{ public function main(){ $total = 0; $cashContext = new CashContext(); // 购买数量 $numA = 10; // 单价 $priceA = 100; // 策略模式获取结果 $totalA = $cashContext->getResultAll('normal', $numA, $priceA); $this->display('A', 'normal', $numA, $priceA, $totalA); // 购买数量 $numB = 5; // 单价 $priceB = 100; // 打折策略获取结果 $totalB = $cashContext->getResultAll('rebate8', $numB, $priceB); $this->display('B', 'rebate8', $numB, $priceB, $totalB); // 购买数量 $numC = 10; // 单价 $priceC = 100; // 返利策略获取结果 $totalC = $cashContext->getResultAll('return300to100', $numC, $priceC); $this->display('C', 'return300to100', $numC, $priceC, $totalC); } /** * 打印 * * @param string $name 商品名 * @param string $type 类型 * @param int $num 数量 * @param double $price 单价 * @return double */ public function display($name, $type, $num, $price, $total){ echo date('Y-m-d H:i:s') . ",$name,[$type],num:$num,price:$price,total:$total\r\n"; } } /** * 程序入口 */ function start(){ $client = new Client(); $client->main(); } start(); ?>
- Related recommendations:
The above is the detailed content of PHP Strategy Pattern. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
