php设计模式

设计模式

一、工厂模式
<?php
class SimpleFactory
{
    public function createBicycle(): Bicycle
    {
        return new Bicycle();
    }
}
class Bicycle
{
    public function driveTo(string $destination)
    {
        echo 'Factory';
    }
}
$factory = new SimpleFactory();
$bicycle = $factory->createBicycle();
$bicycle->driveTo('Paris');
二、单例模式
<?php 
class Singleton
{
  private static $instance;
  //私有构造方法,禁止使用new创建对象
  private function __construct(){}
  //将克隆方法设为私有,禁止克隆对象
  private function __clone(){}

  public static function getInstance(){
      if (!isset(self::$instance)) {
          self::$instance = new self;
      }
      return self::$instance;
  }

  public function say()
  {
      echo "这是用单例模式创建对象实例 <br>";
  }
  public function operation()
  {
      echo "这里可以添加其他方法和操作 <br>";
  }
}
// $shiyanlou = new Singleton();
$shiyanlou = Singleton::getInstance();
$shiyanlou->say();
$shiyanlou->operation();

$newShiyanlou = Singleton::getInstance();
var_dump($shiyanlou === $newShiyanlou);
三、策略模式
//实现一个简单的计算器 (策略接口类)
interface MathOp{
    public function calculation($num1,$num2);
}
//加法  (策略一  策略具体实现,继承策略接口)
class MathAdd implements MathOp{
    public function calculation($num1,$num2){
        return $num1 + $num2;
    }
}
//减法  (策略二  策略具体实现,继承策略接口)
class MathSub implements MathOp{
    public function calculation($num1,$num2){
        return $num1 - $num2;
    }
}
//乘法  (策略三  策略具体实现,继承策略接口)
class MathMulti implements MathOp{
    public function calculation($num1,$num2){
        return $num1 * $num2;
    }
}
//除法 (策略四  策略具体实现,继承策略接口)
class MathDiv implements MathOp{
    public function calculation($num1,$num2){
        return $num1 / $num2;
    }
}
//环境角色   (调取某个策略就行计算,调用得看客户端按哪个键)
class Op{
    protected $op_class = null;
    public function __construct($op_type){
        $this->op_class = 'Math' . $op_type;
    }
    public function get_result($num1,$num2){
        $cls = new $this->op_class;
        return $cls->calculation($num1,$num2);
    }
}
//具体应用过程
$obj = new Op('Add');
echo $obj->get_result(6,2);   //8
 
$obj = new Op('Sub');
echo $obj->get_result(6,5);   //1
 
$obj = new Op('Multi');
echo $obj->get_result(6,2);   //12
 
$obj = new Op('Div');
echo $obj->get_result(6,2);   //3
四、适配器模式
<?php
interface IDatabase {
    // 定义数据库连接方法
    public function connect($host, $username, $password, $database);
    // 定义数据库查询方法
    public function query($sql);
    // 关闭数据库
    public function close();
}
/**
 * Class Mysql 适配器
 */
class Mysql implements IDatabase {
    protected $connect; // 连接资源
    public function connect($host, $username, $password, $database)
    {
        $connect = mysql_connect($host, $username, $password);
        mysql_select_db($database, $connect);
        $this->connect = $connect;
        //其他操作
    }
    public function query($sql)
    {
        return mysql_query($sql);
    }
    public function close()
    {
        mysql_close();
    }
}
/**
 * Class Mysqli 适配器
 */
class Mysqli implements IDatabase {
    protected $connect; // 连接资源
    public function connect($host, $username, $password, $database)
    {
        $connect = mysqli_connect($host, $username, $password, $database);
        $this->connect = $connect;
        //其他操作
    }
    public function query($sql)
    {
        return mysqli_query($this->connect, $sql);
    }
    public function close()
    {
        mysqli_close($this->connect);
    }
}
$host = 'localhost';
$username = 'root';
$password = 'root';
$database = 'mysql';
//$client = new Mysql();
$client = new Mysqli();
$client->connect($host, $username, $password, $database);
$result = $client->query("select * from db");
while ($rows = mysqli_fetch_array($result)) {
    var_dump($rows);
}
$client->close();
五、注册模式
<?php
class ClassA
{
    public function methodA()
    {
        echo "class A";
    }
}
class Register
{
    protected static $objects = [];
    public static function set($alias, $object)
    {
       self::$objects[$alias] = $object;
    }
    public static function get($alias)
    {
        return self::$objects[$alias];
    }
    public static function _unset($alias)
    {
        unset(self::$objects[$alias]);
    }
}
Register::set('obj', new ClassA());
$obj = Register::get('obj');
$obj->methodA();
六、观察者模式
<?php
/**
 * 观察者接口类
 * Interface ObServer
 */
interface ObServer
{
    public function update($event_info = null);
}
/**
 * 观察者1
 */
class ObServer1 implements ObServer
{
    public function update($event_info = null)
    {
        echo "观察者1 收到执行通知 执行完毕!\n";
    }
}
/**
 * 观察者2
 */
class ObServer2 implements ObServer
{
    public function update($event_info = null)
    {
        echo "观察者2 收到执行通知 执行完毕!\n";
    }
}
/**
 * 事件
 * Class Event
 */
class Event
{
    //增加观察者
    public function add(ObServer $ObServer)
    {
        $this->ObServers[] = $ObServer;
    }
    //事件通知
    public function notify()
    {
        foreach ($this->ObServers as $ObServer) {
            $ObServer->update();
        }
    }
    //触发事件
    public function trigger()
    {
        //通知观察者
        $this->notify();
    }
}
//创建一个事件
$event = new Event();
//为事件增加旁观者
$event->add(new ObServer1());
$event->add(new ObServer2());
//执行事件 通知旁观者
$event->trigger();
七、装饰器模式
<?php
// 短信模板接口
interface MessageTemplate
{
    public function message();
}
// 假设有很多模板实现了上面的短信模板接口
// 下面这个是其中一个优惠券发送的模板实现
class CouponMessageTemplate implements MessageTemplate
{
    public function message()
    {
        return '优惠券信息:我们是全国第一的牛X产品哦,送您十张优惠券!';
    }
}
// 我们来准备好装饰上面那个过时的短信模板
abstract class DecoratorMessageTemplate implements MessageTemplate
{
    public $template;
    public function __construct($template)
    {
        $this->template = $template;
    }
}
// 过滤新广告法中不允许出现的词汇
class AdFilterDecoratorMessage extends DecoratorMessageTemplate
{
    public function message()
    {
        return str_replace('全国第一', '全国第二', $this->template->message());
    }
}
// 使用我们的大数据部门同事自动生成的新词库来过滤敏感词汇,这块过滤不是强制要过滤的内容,可选择使用
class SensitiveFilterDecoratorMessage extends DecoratorMessageTemplate
{
    public $bigDataFilterWords = ['牛X'];
    public $bigDataReplaceWords = ['好用'];
    public function message()
    {
        return str_replace($this->bigDataFilterWords, $this->bigDataReplaceWords, $this->template->message());
    }
}
// 客户端,发送接口,需要使用模板来进行短信发送
class Message
{
    public $msgType = 'old';
    public function send(MessageTemplate $mt)
    {
        // 发送出去咯
        if ($this->msgType == 'old') {
            echo '面向内网用户发送' . $mt->message() . PHP_EOL;
        } else if ($this->msgType == 'new') {
            echo '面向全网用户发送' . $mt->message() . PHP_EOL;
        }
    }
}
$template = new CouponMessageTemplate();
$message = new Message();
// 老系统,用不着过滤,只有内部用户才看得到
$message->send($template);
// 新系统,面向全网发布的,需要过滤一下内容哦
$message->msgType = 'new';
$template = new AdFilterDecoratorMessage($template);
$template = new SensitiveFilterDecoratorMessage($template);
// 过滤完了,发送吧
$message->send($template);
八、责任链模式
// 词汇过滤链条
abstract class FilterChain
{
    protected $next;
    public function setNext($next)
    {
        $this->next = $next;
    }
    abstract public function filter($message);
}
// 严禁词汇
class FilterStrict extends FilterChain
{
    public function filter($message)
    {
        foreach (['枪X', '弹X', '毒X'] as $v) {
            if (strpos($message, $v) !== false) {
                throw new \Exception('该信息包含敏感词汇!');
            }
        }
        if ($this->next) {
            return $this->next->filter($message);
        } else {
            return $message;
        }
    }
}
// 警告词汇
class FilterWarning extends FilterChain
{
    public function filter($message)
    {
        $message = str_replace(['打架', '丰胸', '偷税'], '*', $message);
        if ($this->next) {
            return $this->next->filter($message);
        } else {
            return $message;
        }
    }
}
// 手机号加星
class FilterMobile extends FilterChain
{
    public function filter($message)
    {
        $message = preg_replace("/(1[3|5|7|8]\d)\d{4}(\d{4})/i", "$1****$2", $message);
        if ($this->next) {
            return $this->next->filter($message);
        } else {
            return $message;
        }
    }
}
$f1 = new FilterStrict();
$f2 = new FilterWarning();
$f3 = new FilterMobile();
$f1->setNext($f2);
$f2->setNext($f3);
$m1 = "现在开始测试链条1:语句中不包含敏感词,需要替换掉打架这种词,然后给手机号加上星:13333333333,这样的数据才可以对外展示哦";
echo $f1->filter($m1);
echo PHP_EOL;
$m2 = "现在开始测试链条2:这条语句走不到后面,因为包含了毒X,直接就报错了!!!语句中不包含敏感词,需要替换掉打架这种词,然后给手机号加上星:13333333333,这样的数据才可以对外展示哦";
echo $f1->filter($m2);
echo PHP_EOL;
九、桥接模式
<?php
interface MessageTemplate
{
    public function GetTemplate();
}
class LoginMessage implements MessageTemplate
{
    public function GetTemplate()
    {
        echo '您的登录验证码是【AAA】,请不要泄露给他人【XXX公司】!', PHP_EOL;
    }
}
class RegisterMessage implements MessageTemplate
{
    public function GetTemplate()
    {
        echo '您的注册验证码是【BBB】,请不要泄露给他人【XXX公司】!', PHP_EOL;
    }
}
class FindPasswordMessage implements MessageTemplate
{
    public function GetTemplate()
    {
        echo '您的找回密码验证码是【CCC】,请不要泄露给他人【XXX公司】!', PHP_EOL;
    }
}
abstract class MessageService
{
    protected $template;
    public function SetTemplate($template)
    {
        $this->template = $template;
    }
    abstract public function Send();
}
class AliYunService extends MessageService
{
    public function Send()
    {
        echo '阿里云开始发送短信:';
        $this->template->GetTemplate();
    }
}
class JiGuangService extends MessageService
{
    public function Send()
    {
        echo '极光开始发送短信:';
        $this->template->GetTemplate();
    }
}
// 三个短信模板
$loginTemplate = new LoginMessage();
$registerTemplate = new RegisterMessage();
$findPwTemplate = new FindPasswordMessage();
// 两个短信服务商
$aliYun = new AliYunService();
$jg = new JiGuangService();
// 随意组合
// 极光发注册短信
$jg->SetTemplate($registerTemplate);
$jg->Send();
// 阿里云发登录短信
$aliYun->SetTemplate($loginTemplate);
$aliYun->Send();
// 阿里云发找回密码短信
$aliYun->SetTemplate($findPwTemplate);
$aliYun->Send();
// 极光发登录短信
$jg->SetTemplate($loginTemplate);
$jg->Send();
// ......

十、中介者模式

<?php
abstract class Mediator
{
    abstract public function Send($message, $user);
}
class ChatMediator extends Mediator
{
    public $users = [];
    public function Attach($user)
    {
        if (!in_array($user, $this->users)) {
            $this->users[] = $user;
        }
    }
    public function Detach($user)
    {
        $position = 0;
        foreach ($this->users as $u) {
            if ($u == $user) {
                unset($this->users[$position]);
            }
            $position++;
        }
    }
    public function Send($message, $user)
    {
        foreach ($this->users as $u) {
            if ($u == $user) {
                continue;
            }
            $u->Notify($message);
        }
    }
}
abstract class User
{
    public $mediator;
    public $name;
    public function __construct($mediator, $name)
    {
        $this->mediator = $mediator;
        $this->name = $name;
    }
}
class ChatUser extends User
{
    public function Send($message)
    {
        $this->mediator->Send($message . '(' . $this->name . '发送)', $this);
    }
    public function Notify($message)
    {
        echo $this->name . '收到消息:' . $message, PHP_EOL;
    }
}
$m = new ChatMediator();
$u1 = new ChatUser($m, '用户1');
$u2 = new ChatUser($m, '用户2');
$u3 = new ChatUser($m, '用户3');
$m->Attach($u1);
$m->Attach($u3);
$m->Attach($u2);
$u1->Send('Hello, 大家好呀!'); // 用户2、用户3收到消息
$u2->Send('你好呀!'); // 用户1、用户3收到消息
$m->Detach($u2); // 用户2退出聊天室
$u3->Send('欢迎欢迎!'); // 用户1收到消息

十一、原型模式

<?php 
class Canvas {
    private $data;
    public function init($width = 20, $height = 10) {
        $data = [];
        for($i = 0; $i < $height; $i++) {
            for($j = 0; $j < $width; $j++) {
                $data[$i][$j] = '*';
            }
        }
        $this->data = $data;
    }
    public function rect($x1, $y1, $x2, $y2) {
        foreach($this->data as $k1 => $line) {
            if ($x1 > $k1 or $x2 < $k1) {
                continue;
            }
            foreach($line as $k2 => $char) {
                if ($y1>$k2 or $y2<$k2) {
                    continue;
                }
                $this->data[$k1][$k2] = '#';
            }
        }
    }
    public function draw() {
        foreach ($this->data as $line){
            foreach ($line as $char){
                echo $char;
            }
            echo "<br>;";
        }
    }
}
$c = new Canvas();
$c->init();
// / $canvas1 = new Canvas();
// $canvas1->init();
$canvas1 = clone $c;//通过克隆,可以省去init()方法
$canvas1->rect(2, 2, 8, 8);
$canvas1->draw();
echo "-----------------------------------------<br>";
$canvas2 = clone $c;
$canvas2->rect(1, 4, 8, 8);
$canvas2->draw();
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_35855719

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值