51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

PHP 中的设计模式

本文主要讨论下Web开发中,准确而言,是PHP开发中的相关的设计模式及其应用。有经验的开发者肯定对于设计模式非常熟悉,但是本文主要是针对那 些初级的开发者。首先我们要搞清楚到底什么是设计模式,设计模式并不是一种用来解释的模式,它们并不是像链表那样的常见的数据结构,也不是某种特殊的应用 或者框架设计。事实上,设计模式的解释如下:

    descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context.

另一方面,设计模式提供了一种广泛的可重用的方式来解决我们日常编程中常常遇见的问题。设计模式并不一定就是一个类库或者第三方框架,它们更多的表 现为一种思想并且广泛地应用在系统中。它们也表现为一种模式或者模板,可以在多个不同的场景下用于解决问题。设计模式可以用于加速开发,并且将很多大的想 法或者设计以一种简单地方式实现。当然,虽然设计模式在开发中很有作用,但是千万要避免在不适当的场景误用它们。

目前常见的设计模式主要有23种,根据使用目标的不同可以分为以下三大类:

创建模式:用于创建对象从而将某个对象从实现中解耦合。
架构模式:用于在不同的对象之间构造大的对象结构。
行为模式:用于在不同的对象之间管理算法、关系以及职责。

Creational Patterns
Singleton(单例模式)
单例模式是最常见的模式之一,在Web应用的开发中,常常用于允许在运行时为某个特定的类创建一个可访问的实例。

<?php
/**
 * Singleton class
 */
final class Product
{
    /**
     * @ var self
     */
    private static $instance;
    /**
     * @ var mixed
     */
    public $mix;

    /**
     * Return self instance
     *
     * @return self
     */
    public static function getInstance() {
        if (!(self::$instance instanceof self)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    private function __construct() {
    }
    private function __clone() {
    }
}
$firstProduct = Product::getInstance();
$secondProduct = Product::getInstance();
$firstProduct->mix = 'test';
$secondProduct->mix = 'example';
print_r($firstProduct->mix);
// example
print_r($secondProduct->mix);
// example
<?php
/**
 * Singleton class
 */
final class Product
{
 
    /**
     * @ var self
     */
    private static $instance;
 
    /**
     * @ var mixed
     */
    public $mix;
 
 
    /**
     * Return self instance
     *
     * @return self
     */
    public static function getInstance() {
        if (!(self::$instance instanceof self)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
 
    private function __construct() {
    }
 
    private function __clone() {
    }
}
 
$firstProduct = Product::getInstance();
$secondProduct = Product::getInstance();
 
$firstProduct->mix = 'test';
$secondProduct->mix = 'example';
 
print_r($firstProduct->mix);
// example
print_r($secondProduct->mix);
// example

在很多情况下,需要为系统中的多个类创建单例的构造方式,这样,可以建立一个通用的抽象父工厂方法:

<?php
abstract class FactoryAbstract {
    protected static $instances = array();
    public static function getInstance() {
        $className = static::getClassName();
        if (!(self::$instances[$className] instanceof $className)) {
            self::$instances[$className] = new $className();
        }
        return self::$instances[$className];
    }
    public static function removeInstance() {
        $className = static::getClassName();
        if (array_key_exists($className, self::$instances)) {
            unset(self::$instances[$className]);
        }
    }
    final protected static function getClassName() {
        return get_called_class();
    }
    protected function __construct() { }
    final protected function __clone() { }
}
abstract class Factory extends FactoryAbstract {
    final public static function getInstance() {
        return parent::getInstance();
    }
    final public static function removeInstance() {
        parent::removeInstance();
    }
}
// using:
class FirstProduct extends Factory {
    public $a = [];
}
class SecondProduct extends FirstProduct {
}
FirstProduct::getInstance()->a[] = 1;
SecondProduct::getInstance()->a[] = 2;
FirstProduct::getInstance()->a[] = 3;
SecondProduct::getInstance()->a[] = 4;
print_r(FirstProduct::getInstance()->a);
// array(1, 3)
print_r(SecondProduct::getInstance()->a);
// array(2, 4)
<?php
 
abstract class FactoryAbstract {
 
    protected static $instances = array();
 
    public static function getInstance() {
        $className = static::getClassName();
        if (!(self::$instances[$className] instanceof $className)) {
            self::$instances[$className] = new $className();
        }
        return self::$instances[$className];
    }
 
    public static function removeInstance() {
        $className = static::getClassName();
        if (array_key_exists($className, self::$instances)) {
            unset(self::$instances[$className]);
        }
    }
 
    final protected static function getClassName() {
        return get_called_class();
    }
 
    protected function __construct() { }
 
    final protected function __clone() { }
}
 
abstract class Factory extends FactoryAbstract {
 
    final public static function getInstance() {
        return parent::getInstance();
    }
 
    final public static function removeInstance() {
        parent::removeInstance();
    }
}
// using:
 
class FirstProduct extends Factory {
    public $a = [];
}
class SecondProduct extends FirstProduct {
}
 
FirstProduct::getInstance()->a[] = 1;
SecondProduct::getInstance()->a[] = 2;
FirstProduct::getInstance()->a[] = 3;
SecondProduct::getInstance()->a[] = 4;
 
print_r(FirstProduct::getInstance()->a);
// array(1, 3)
print_r(SecondProduct::getInstance()->a);
// array(2, 4)

Registry
注册台模式并不是很常见,它也不是一个典型的创建模式,只是为了利用静态方法更方便的存取数据。

<?php
/**
* Registry class
*/
class Package {
    protected static $data = array();
    public static function set($key, $value) {
        self::$data[$key] = $value;
    }
    public static function get($key) {
        return isset(self::$data[$key]) ? self::$data[$key] : null;
    }
    final public static function removeObject($key) {
        if (array_key_exists($key, self::$data)) {
            unset(self::$data[$key]);
        }
    }
}

Package::set('name', 'Package name');
print_r(Package::get('name'));
// Package name
<?php
/**
* Registry class
*/
class Package {
 
    protected static $data = array();
 
    public static function set($key, $value) {
        self::$data[$key] = $value;
    }
 
    public static function get($key) {
        return isset(self::$data[$key]) ? self::$data[$key] : null;
    }
 
    final public static function removeObject($key) {
        if (array_key_exists($key, self::$data)) {
            unset(self::$data[$key]);
        }
    }
}
 
 
Package::set('name', 'Package name');
 
print_r(Package::get('name'));
// Package name

Factory(工厂模式)
工厂模式是另一种非常常用的模式,正如其名字所示:确实是对象实例的生产工厂。某些意义上,工厂模式提供了通用的方法有助于我们去获取对象,而不需要关心其具体的内在的实现。

<?php
interface Factory {
    public function getProduct();
}
interface Product {
    public function getName();
}
class FirstFactory implements Factory {
    public function getProduct() {
        return new FirstProduct();
    }
}
class SecondFactory implements Factory {
    public function getProduct() {
        return new SecondProduct();
    }
}
class FirstProduct implements Product {
    public function getName() {
        return 'The first product';
    }
}
class SecondProduct implements Product {
    public function getName() {
        return 'Second product';
    }
}
$factory = new FirstFactory();
$firstProduct = $factory->getProduct();
$factory = new SecondFactory();
$secondProduct = $factory->getProduct();
print_r($firstProduct->getName());
// The first product
print_r($secondProduct->getName());
// Second product
<?php
 
interface Factory {
    public function getProduct();
}
 
interface Product {
    public function getName();
}
 
class FirstFactory implements Factory {
 
    public function getProduct() {
        return new FirstProduct();
    }
}
 
class SecondFactory implements Factory {
 
    public function getProduct() {
        return new SecondProduct();
    }
}
 
class FirstProduct implements Product {
 
    public function getName() {
        return 'The first product';
    }
}
 
class SecondProduct implements Product {
 
    public function getName() {
        return 'Second product';
    }
}
 
$factory = new FirstFactory();
$firstProduct = $factory->getProduct();
$factory = new SecondFactory();
$secondProduct = $factory->getProduct();
 
print_r($firstProduct->getName());
// The first product
print_r($secondProduct->getName());
// Second product

AbstractFactory(抽象工厂模式)
有些情况下我们需要根据不同的选择逻辑提供不同的构造工厂,而对于多个工厂而言需要一个统一的抽象工厂:

<?php
class Config {
    public static $factory = 1;
}
interface Product {
    public function getName();
}
abstract class AbstractFactory {
    public static function getFactory() {
        switch (Config::$factory) {
            case 1:
                return new FirstFactory();
            case 2:
                return new SecondFactory();
        }
        throw new Exception('Bad config');
    }
    abstract public function getProduct();
}
class FirstFactory extends AbstractFactory {
    public function getProduct() {
        return new FirstProduct();
    }
}
class FirstProduct implements Product {
    public function getName() {
        return 'The product from the first factory';
    }
}
class SecondFactory extends AbstractFactory {
    public function getProduct() {
        return new SecondProduct();
    }
}
class SecondProduct implements Product {
    public function getName() {
        return 'The product from second factory';
    }
}
$firstProduct = AbstractFactory::getFactory()->getProduct();
Config::$factory = 2;
$secondProduct = AbstractFactory::getFactory()->getProduct();
print_r($firstProduct->getName());
// The first product from the first factory
print_r($secondProduct->getName());
// Second product from second factory
<?php
 
class Config {
    public static $factory = 1;
}
 
interface Product {
    public function getName();
}
 
abstract class AbstractFactory {
 
    public static function getFactory() {
        switch (Config::$factory) {
            case 1:
                return new FirstFactory();
            case 2:
                return new SecondFactory();
        }
        throw new Exception('Bad config');
    }
 
    abstract public function getProduct();
}
 
class FirstFactory extends AbstractFactory {
    public function getProduct() {
        return new FirstProduct();
    }
}
class FirstProduct implements Product {
    public function getName() {
        return 'The product from the first factory';
    }
}
 
class SecondFactory extends AbstractFactory {
    public function getProduct() {
        return new SecondProduct();
    }
}
class SecondProduct implements Product {
    public function getName() {
        return 'The product from second factory';
    }
}
 
$firstProduct = AbstractFactory::getFactory()->getProduct();
Config::$factory = 2;
$secondProduct = AbstractFactory::getFactory()->getProduct();
 
print_r($firstProduct->getName());
// The first product from the first factory
print_r($secondProduct->getName());
// Second product from second factory
赞(2)
未经允许不得转载:工具盒子 » PHP 中的设计模式