ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

php设计模式,自己理解和代码开发

2021-09-14 14:00:58  阅读:142  来源: 互联网

标签:function php 代码 模式 echo cost new 设计模式


目前先介绍5种模式:单例模式,工厂模式,注册模式,策略模式,观察者模式,装饰器模式

1,单例模式

简单理解一切私有化,只对外开放静态方法,用来调用本类其他方法

<?php
//单例
class Uni{
        //创建静态私有的变量保存该类对象
    static private $instance;
        //参数
    private $config;
        //防止直接创建对象
    private function __construct($config){
        $this -> config = $config;
                echo "我被实例化了";
    }
        //防止克隆对象
    private function __clone(){

    }
    static public function getInstance($config){
                //判断$instance是否是Uni的对象
                //没有则创建
        if (!self::$instance instanceof self) {
            self::$instance = new self($config);
        }
        return self::$instance;

    }
    public function getName(){
        echo $this -> config;
    }
}
$db1 = Uni::getInstance(1);
$db1 -> getName();
echo "<br>";
$db2 = Uni::getInstance(4);
$db2 -> getName();
?>

2,工厂模式

工厂模式,工厂方法或者类生成对象,而不是在代码中直接new。
使用工厂模式,可以避免当改变某个类的名字或者方法之后,在调用这个类的所有的代码中都修改它的名字或者参数,其实和单类有同取之意

Test1.php
<?php
class Test1{
    static function test(){
        echo __FILE__;
    }
}

Factory.php
<?php
class Factory{
    /*
     * 如果某个类在很多的文件中都new ClassName(),那么万一这个类的名字
     * 发生变更或者参数发生变化,如果不使用工厂模式,就需要修改每一个PHP
     * 代码,使用了工厂模式之后,只需要修改工厂类或者方法就可以了。
     */
    static function createDatabase(){
        $test = new Test1();
        return $test;
    }
}

Test.php
<?php
spl_autoload_register('autoload1');

$test = Factory::createDatabase();
$test->test();
function autoload1($class){
    $dir  = __DIR__;
    $requireFile = $dir."\\".$class.".php";
    require $requireFile;
}
Test1.php
<?php
class Test1{
    protected static  $tt;
    private function __construct(){}
    static function getInstance(){
        if(self::$tt){
            echo "对象已经创建<br>";
            return self::$tt;
        }else {
            self::$tt = new Test1();
            echo "创建对象<br>";
            return self::$tt;
        }
    }
     function echoHello(){
        echo "Hello<br>";
    }
}
Test.php
<?php
spl_autoload_register('autoload1');

$test = Test1::getInstance();
$test->echoHello();
$test = Test1::getInstance();
$test->echoHello();
$test = Test1::getInstance();
$test->echoHello();
$test = Test1::getInstance();
$test->echoHello();
function autoload1($class){
    $dir  = __DIR__;
    $requireFile = $dir."\\".$class.".php";
    require $requireFile;
}

3,注册模式

注册模式,解决全局共享和交换对象。已经创建好的对象,挂在到某个全局可以使用的数组上,在需要使用的时候,直接从该数组上获取即可。将对象注册到全局的树上。任何地方直接去访问。

<?php

class Register
{
    protected static  $objects;
    function set($alias,$object)//将对象注册到全局的树上
    {
        self::$objects[$alias]=$object;//将对象放到树上
    }
    static function get($name){
        return self::$objects[$name];//获取某个注册到树上的对象
    }
    function _unset($alias)
    {
        unset(self::$objects[$alias]);//移除某个注册到树上的对象。
    }
}

4,策略模式

策略模式,将一组特定的行为和算法封装成类,以适应某些特定的上下文环境。
eg:假如有一个电商网站系统,针对男性女性用户要各自跳转到不同的商品类目,并且所有的广告位展示不同的广告。在传统的代码中,都是在系统中加入各种if else的判断,硬编码的方式。如果有一天增加了一种用户,就需要改写代码。使用策略模式,如果新增加一种用户类型,只需要增加一种策略就可以。其他所有的地方只需要使用不同的策略就可以。
首先声明策略的接口文件,约定了策略的包含的行为。然后,定义各个具体的策略实现类。

UserStrategy.php
<?php
/*
 * 声明策略文件的接口,约定策略包含的行为。
 */
interface UserStrategy
{
    function showAd();
    function showCategory();
}
FemaleUser.php
<?php
require_once 'Loader.php';
class FemaleUser implements UserStrategy
{
    function showAd(){
        echo "2016冬季女装";
    }
    function showCategory(){
        echo "女装";
    }
}
MaleUser.php
<?php
require_once 'Loader.php';
class MaleUser implements UserStrategy
{
    function showAd(){
        echo "IPhone6s";
    }
    function showCategory(){
        echo "电子产品";
    }
}
Page.php//执行文件
<?php
require_once 'Loader.php';
class Page
{
    protected $strategy;
    function index(){
        echo "AD";
        $this->strategy->showAd();
        echo "<br>";
        echo "Category";
        $this->strategy->showCategory();
        echo "<br>";
    }
    function setStrategy(UserStrategy $strategy){
        $this->strategy=$strategy;
    }
}

$page = new Page();
if(isset($_GET['male'])){
    $strategy = new MaleUser();
}else {
    $strategy = new FemaleUser();
}
$page->setStrategy($strategy);
$page->index();

总结:
通过以上方式,可以发现,在不同用户登录时显示不同的内容,但是解决了在显示时的硬编码的问题。如果要增加一种策略,只需要增加一种策略实现类,然后在入口文件中执行判断,传入这个类即可。实现了解耦。
实现依赖倒置和控制反转 (有待理解)
通过接口的方式,使得类和类之间不直接依赖。在使用该类的时候,才动态的传入该接口的一个实现类。如果要替换某个类,只需要提供一个实现了该接口的实现类,通过修改一行代码即可完成替换。

5,观察者模式

1:观察者模式(Observer),当一个对象状态发生变化时,依赖它的对象全部会收到通知,并自动更新。
2:场景:一个事件发生后,要执行一连串更新操作。传统的编程方式,就是在事件的代码之后直接加入处理的逻辑。当更新的逻辑增多之后,代码会变得难以维护。这种方式是耦合的,侵入式的,增加新的逻辑需要修改事件的主体代码。
3:观察者模式实现了低耦合,非侵入式的通知与更新机制。
定义一个事件触发抽象类。

EventGenerator.php
<?php
require_once 'Loader.php';
abstract class EventGenerator{
    private $observers = array();
    function addObserver(Observer $observer){
        $this->observers[]=$observer;
    }
    function notify(){
        foreach ($this->observers as $observer){
            $observer->update();
        }
    }
}
Observer.php
<?php
require_once 'Loader.php';
interface Observer{
    function update();//这里就是在事件发生后要执行的逻辑
}
<?php
//一个实现了EventGenerator抽象类的类,用于具体定义某个发生的事件
require 'Loader.php';
class Event extends EventGenerator{
    function triger(){
        echo "Event<br>";
    }
}
class Observer1 implements Observer{
    function update(){
        echo "逻辑1<br>";
    }
}
class Observer2 implements Observer{
    function update(){
        echo "逻辑2<br>";
    }
}
$event = new Event();
$event->addObserver(new Observer1());
$event->addObserver(new Observer2());
$event->triger();
$event->notify();

6,装饰器模式

装饰器模式又叫做装饰者模式,是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。传统的编程模式都是子类继承父类实现方法的重载,使用装饰器模式,只需添加一个新的装饰器对象,更加灵活,避免类数目和层次过多。

<?php
namespace Libs;
/**
 * 被装饰对象基类
 * */
interface Component
{
    /**
     * 计算所需费用
     * */
    public function cost();
}
<?php
namespace Libs;

/**
 * 定义具体被装饰对象,这里是主食之包子
 * */
class ConcreteComponentBun implements Component
{
    public function __construct()
    {
        echo "Oh,There is the construct of ConcreteComponentBun.</br>";
    }
    public function cost()
    {
        echo "There is the function of ConcreteComponentBun named cost. <br/>";
        return 15.00;
    }
}
<?php
namespace  Libs;
/**
 * 装饰器接口
 * */
class Decorator implements Component
{
    public function __construct()
    {
        $this->_name = 'Decorator';
    }
    public function cost()
    {
        return 1.00;
    }

}
<?php
namespace Libs;

class ConcreteDecoratorSalad extends Decorator
{
    public $_component;
    public function __construct($component)
    {
        echo "Oh,There is the construct of ConcreteDecoratorSalad.</br>";
        
        if($component instanceof Component){
            $this->_component = $component;
        } else {
            exit('Failure');
        }
    }
    public function cost()
    {
        echo "There is the function of ConcreteDecoratorSalad named cost. <br/>";
        return $this->_component->cost()+10.00;
    }
}
<?php
namespace Libs;

class ConcreteDecoratorSoup extends Decorator
{
    public $_component;
    public function __construct($component)
    {
        echo "Oh,There is the construct of ConcreteDecoratorSoup.</br>";
        if($component instanceof Component){
            $this->_component = $component;
        } else {
            exit('Failure');
        }
    }
    public function cost()
    {
        echo "There is the function of ConcreteDecoratorSoup named cost. <br/>";
        return $this->_component->cost()+5.00;
    }

}
<?php
namespace Libs;

class UseDecorator
{
    public static function index()
    {
        
        $bun = new ConcreteComponentBun();
        $cost = $bun->cost();
        echo "The cost is {$cost} <br>";
        echo "_________________________________________________</br>";
        
        $salad_bun = new ConcreteDecoratorSalad($bun);
        $cost = $salad_bun->cost();
        echo "The cost is {$cost} <br>";
        echo "_________________________________________________</br>";
        
        $soup_bun = new ConcreteDecoratorSoup($bun);
        $cost = $soup_bun->cost();
        echo "The cost is {$cost} <br>";
        echo "_________________________________________________</br>";
        
    }
}

优点:
    1). Decorator模式与继承关系的目的都是要扩展对象的功能,但是Decorator可以提供比继承更多的灵活性。
    2). 通过使用不同的具体装饰类以及这些装饰类的排列组合,设计师可以创造出很多不同行为的组合。

缺点:
    1). 这种比继承更加灵活机动的特性,也同时意味着更加多的复杂性。
    2). 装饰模式会导致设计中出现许多小类,如果过度使用,会使程序变得很复杂。
    3). 装饰模式是针对抽象组件(Component)类型编程。但是,如果你要针对具体组件编程时,就应该重新思考你的应用架构,以及装饰者是否合适。当然也可以改变Component接口,增加新的公开的行为,实现“半透明”的装饰者模式。在实际项目中要做出最佳选择。

标签:function,php,代码,模式,echo,cost,new,设计模式
来源: https://blog.csdn.net/qq_23009739/article/details/120284496

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有