Home  >  Article  >  Backend Development  >  PHP design pattern (creative)

PHP design pattern (creative)

藏色散人
藏色散人forward
2019-09-04 13:18:122667browse

Preface

As the experience of programming projects increases, from serving business logic to overall design for the project. Recognize the importance of design patterns in the development process and follow the five benchmark principles of S.O.L.I.D. It expands my horizons, makes the code more flexible, and looks more beautiful.\Beauty is the philosophical idea of ​​​​building all things.

The design patterns we learn are divided into three categories: creator pattern and structural pattern , behavioral pattern; creational pattern is related to the creation of objects; structural pattern deals with the combination of classes or objects; and behavioral pattern describes how classes or objects interact and how to assign responsibilities;

Content: This article introduces the creation of PHP design patterns. Including: Singleton mode, Multiton mode, Factory Method mode, Abstract Factory mode, Simple Factory mode, Prototype mode, Object pool mode ( Pool), Builder Pattern (Builder)

Recommended: "PHP Tutorial"

(1) Singleton Pattern (Singleton)

● Definition

Ensure that a class has only one instance and provide a global access point to access it. There is only one object of this class in the system memory, which saves system resources. For some objects that need to be frequently created and destroyed, using the singleton mode can improve system performance.

● Code example

class Singleton
{
    /**
    * @var Singleton
    */
    private static $instance;
    /**
    * 不允许从外部调用以防止创建多个实例
    * 要使用单例,必须通过 Singleton::getInstance() 方法获取实例
    */
    private function __construct()
    {
    }
    /**
    * 通过懒加载获得实例(在第一次使用的时候创建)
    */
    public static function getInstance(): Singleton
    {
        if (null === static::$instance) {
            static::$instance = new static();
        }
        return static::$instance;
    }
    /**
    * 防止实例被克隆(这会创建实例的副本)
    */
    private function __clone()
    {
    }
    /**
    * 防止反序列化(这将创建它的副本)
    */
    private function __wakeup()
    {
    }
}

(2) Multiple instance mode (Multiton)

● Definition

in the multi-instance mode , a multi-instance class can have multiple instances, and the multi-instance class must create and manage its own instances, and provide its own instances to the outside world. 1. Save the container via an instance container. 2. Use private construction to prevent external construction. 3. Provide the getInstantce() method to obtain the instance.

● Code example Two objects are instantiated multiple times through one class

abstract class Multiton { 
    private static $instances = array(); 
    public static function getInstance() { 
        $key = get_called_class() . serialize(func_get_args());
        if (!isset(self::$instances[$key])) { 
            $rc = new ReflectionClass(get_called_class());
            self::$instances[$key] = $rc->newInstanceArgs(func_get_args());
        }
        return self::$instances[$key]; 
    }
    /**
     * 该私有对象阻止实例被克隆
     */
    private function __clone()
    {
    }
    /**
     * 该私有方法阻止实例被序列化
     */
    private function __wakeup()
    {
    }
} 
class Hello extends Multiton { 
    public function __construct($string = 'World') { 
        echo "Hello $string\n"; 
    } 
} 
class GoodBye extends Multiton { 
    public function __construct($string = 'my', $string2 = 'darling') { 
        echo "Goodbye $string $string2\n"; 
    }
}
$a = Hello::getInstance('World'); 
$b = Hello::getInstance('bob'); 
// $a !== $b 
$c = Hello::getInstance('World'); 
// $a === $c 
$d = GoodBye::getInstance(); 
$e = GoodBye::getInstance();
// $d === $e 
$f = GoodBye::getInstance('your'); 
// $d !== $f

(3) Factory Method Pattern (Factory Method)

● Definition

Delays the instantiation of the class (the creation of specific products) to the subclass of the factory class (specific factory), that is, the subclass decides which instance should be Which class to change (create)

● Code example: Xiaocheng has a plastic processing factory (only produces Class A products); as customer needs change, the customer needs to produce Class B products. It is very difficult to change the configuration and changes of the original plastic processing plant. Assuming that the customer needs change next time, changing again will increase the cost very much; Xiaocheng decided to purchase a plastic branch factory B to produce Class B products.

abstract class Product{
    public abstract function Show();
}
//具体产品A类
class  ProductA extends  Product{
    public function Show() {
        echo "生产出了产品A";
    }
}
//具体产品B类
class  ProductB extends  Product{
    public function Show() {
        echo "生产出了产品B";
    }
}
abstract class Factory{
    public abstract function Manufacture();
}
//工厂A类 - 生产A类产品
class  FactoryA extends Factory{
    public function Manufacture() {
        return new ProductA();
    }
}
//工厂B类 - 生产B类产品
class  FactoryB extends Factory{
    public function Manufacture() {
        return new ProductB();
    }
}

(4) Abstract Factory Pattern (Abstract Factory)

● Definition

Create a series of related or Dependent objects. Usually classes are created that implement the same interface. The client of the abstract factory doesn't care how the objects are created, it just knows how they function together.

● Code example: There are two factories, Factory A is responsible for transportation, and Factory B produces digital products.

interface Product
{
    public function calculatePrice(): int;
}
class ShippableProduct implements Product
{
    /**
     * @var float
     */
    private $productPrice;
    /**
     * @var float
     */
    private $shippingCosts;
    public function __construct(int $productPrice, int $shippingCosts)
    {
        $this->productPrice = $productPrice;
        $this->shippingCosts = $shippingCosts;
    }
    public function calculatePrice(): int
    {
        return $this->productPrice + $this->shippingCosts;
    }
}
class DigitalProduct implements Product
{
    /**
     * @var int
     */
    private $price;
    public function __construct(int $price)
    {
        $this->price = $price;
    }
    public function calculatePrice(): int
    {
        return $this->price;
    }
}
class ProductFactory
{
    const SHIPPING_COSTS = 50;
    public function createShippableProduct(int $price): Product
    {
        return new ShippableProduct($price, self::SHIPPING_COSTS);
    }
    public function createDigitalProduct(int $price): Product
    {
        return new DigitalProduct($price);
    }
}

(5) Simple Factory Mode (Simple Factory)

● Definition

The simple factory pattern is a streamlined version of the factory pattern. Factory role - concrete product - abstract product

● Code example:

A farm wants to sell fruits to the market. There are three kinds of fruits on the farm, apples and grapes. We imagine: 1. Fruits have multiple attributes, each attribute is different, but they have something in common | growing, planting, harvesting, and eating. New fruits may be added in the future, and we need to define an interface to standardize the methods they must implement.

interface fruit{
    /**
     * 生长
     */
    public function grow();
    /**
     * 种植
     */
    public function plant();
    /**
     * 收获
     */
    public function harvest();
    /**
     * 吃
     */
    public function eat();
}
class apple implements fruit{
    //苹果树有年龄
    private $treeAge;
    //苹果有颜色
    private $color;
    public function grow(){
        echo "grape grow";
    }
    public function plant(){
        echo "grape plant";
    }
    public function harvest(){
        echo "grape harvest";
    }
    public function eat(){
        echo "grape eat";
    }
    //取苹果树的年龄
    public function getTreeAge(){
        return $this->treeAge;
    }
    //设置苹果树的年龄
    public function setTreeAge($age){
        $this->treeAge = $age;
        return true;
    }
}
class grape implements fruit{
    //葡萄是否有籽
    private $seedLess;
    public function grow(){
        echo "apple grow";
    }
    public function plant(){
        echo "apple plant";
    }
    public function harvest(){
        echo "apple harvest";
    }
    public function eat(){
        echo "apple eat";
    }
    //有无籽取值
    public function getSeedLess(){
        return $this->seedLess;
    }
    //设置有籽无籽
    public function setSeedLess($seed){
        $this->seedLess = $seed;
        return true;
    }
}
class farmer
{
    //定义个静态工厂方法
    public static function factory($fruitName){
        switch ($fruitName) {
            case 'apple':
                return new apple();
                break;
            case 'grape':
                return new grape();
                break;
            default:
                throw new badFruitException("Error no the fruit", 1);
                break;
        }
    }
}
class badFruitException extends Exception
{
    public $msg;
    public $errType;
    public function __construct($msg = '' , $errType = 1){
        $this->msg = $msg;
        $this->errType = $errType;
    }  
}
/**
 * 获取水果实例化的方法
 */
try{
    $appleInstance = farmer::factory('apple');
    var_dump($appleInstance);
}catch(badFruitException $err){
    echo $err->msg . "_______" . $err->errType;
}

(6) Prototype Pattern

● Definition

Compared with creating an object normally (new Foo ()), it is more cost-effective to first create a prototype and then clone it.

● Code example: Set the title for each book

abstract class BookPrototype
{
    /**
    * @var string
    */
    protected $title = 0;
    /**
    * @var string
    */
    protected $category;
    abstract public function __clone();
    public function getTitle(): string
    {
        return $this->title;
    }
    public function setTitle($title)
    {
       $this->title = $title;
    }
}
class BarBookPrototype extends BookPrototype
{
    /**
    * @var string
    */
    protected $category = 'Bar';
    public function __clone()
    {
    }
}
class FooBookPrototype extends BookPrototype
{
    /**
    * @var string
    */
    protected $category = 'Foo';
    public function __clone()
    {
    }
}
$fooPrototype = new FooBookPrototype();
$barPrototype = new BarBookPrototype();
for ($i = 5; $i < 10; $i++) {
    $book = clone $fooPrototype;
    $book->setTitle(&#39;Foo Book No &#39; . $i);
    var_dump(new FooBookPrototype == $book);
}
for ($i = 0; $i < 5; $i++) {
    $book = clone $barPrototype;
    $book->setTitle(&#39;Bar Book No &#39; . $i);
    var_dump(new BarBookPrototype == $book);
}

(7) Object pool mode (Pool)

● Definition

The object pool can be used to construct and store a series of objects and obtain calls when needed. In situations where the cost of initializing instances is high, the instantiation rate is high, and the available instances are insufficient, object pools can greatly improve performance. In situations where the time required to create objects (especially over the network) is uncertain, the required objects can be obtained in a short period of time through an object pool.

● Code Example

class Factory {
    protected static $products = array();
    public static function pushProduct(Product $product) {
        self::$products[$product->getId()] = $product;
    }
    public static function getProduct($id) {
        return isset(self::$products[$id]) ? self::$products[$id] : null;
    }
    public static function removeProduct($id) {
        if (array_key_exists($id, self::$products)) {
            unset(self::$products[$id]);
        }
    }
}
Factory::pushProduct(new Product(&#39;first&#39;));
Factory::pushProduct(new Product(&#39;second&#39;));
print_r(Factory::getProduct(&#39;first&#39;)->getId());
// first
print_r(Factory::getProduct(&#39;second&#39;)->getId());
// second

(8) Builder Pattern (Builder)

● Definition

Convert a complex object The build is separated from its representation so that the same build process can create different representations

● 2) Code example Build trucks and cars of the same standard. Similar to Transformers, the same parts can be combined in different ways.

● It is divided into Director, which is responsible for building, BuilderInterface, which builds interfaces and standardizes construction standards, and TruckBuilder, which builds truck classes. CarBuilder builds car classes.

Vehicle parts public class, Truck Car Engine Wheel Door parts class, DirectorTest test class

class Director
{
    public function build(BuilderInterface $builder): Vehicle
    {
        $builder->createVehicle();
        $builder->addDoors();
        $builder->addEngine();
        $builder->addWheel();
        return $builder->getVehicle();
    }
}
interface BuilderInterface
{
    public function createVehicle();
    public function addWheel();
    public function addEngine();
    public function addDoors();
    public function getVehicle(): Vehicle;
}
class TruckBuilder implements BuilderInterface
{
    /**
    * @var Truck
    */
    private $truck;
    public function addDoors()
    {
        $this->truck->setPart(&#39;rightDoor&#39;, new Door());
        $this->truck->setPart(&#39;leftDoor&#39;, new Door());
    }
    public function addEngine()
    {
        $this->truck->setPart(&#39;truckEngine&#39;, new Engine());
    }
    public function addWheel()
    {
        $this->truck->setPart(&#39;wheel1&#39;, new Wheel());
        $this->truck->setPart(&#39;wheel2&#39;, new Wheel());
        $this->truck->setPart(&#39;wheel3&#39;, new Wheel());
        $this->truck->setPart(&#39;wheel4&#39;, new Wheel());
        $this->truck->setPart(&#39;wheel5&#39;, new Wheel());
        $this->truck->setPart(&#39;wheel6&#39;, new Wheel());
    }
    public function createVehicle()
    {
        $this->truck = new Truck();
    }
    public function getVehicle(): Vehicle
    {
        return $this->truck;
    }
}
class CarBuilder implements BuilderInterface
{
    /**
    * @var Car
    */
    private $car;
    public function addDoors()
    {
        $this->car->setPart(&#39;rightDoor&#39;, new Door());
        $this->car->setPart(&#39;leftDoor&#39;, new Door());
        $this->car->setPart(&#39;trunkLid&#39;, new Door());
    }
    public function addEngine()
    {
        $this->car->setPart(&#39;engine&#39;, new Engine());
    }
    public function addWheel()
    {
        $this->car->setPart(&#39;wheelLF&#39;, new Wheel());
        $this->car->setPart(&#39;wheelRF&#39;, new Wheel());
        $this->car->setPart(&#39;wheelLR&#39;, new Wheel());
        $this->car->setPart(&#39;wheelRR&#39;, new Wheel());
    }
    public function createVehicle()
    {
        $this->car = new Car();
    }
    public function getVehicle(): Vehicle
    {
        return $this->car;
    }
}
abstract class Vehicle
{
    /**
    * @var object[]
    */
    private $data = [];
    /**
    * @param string $key
    * @param object $value
    */
    public function setPart($key, $value)
    {
        $this->data[$key] = $value;
    }
}
class Truck extends Vehicle
{
}
class Car extends Vehicle
{
}
class Engine extends Vehicle
{
}
class Wheel extends Vehicle
{
}
class Door extends Vehicle
{
}
class DirectorTest
{
    public function testCanBuildTruck()
    {
        $truckBuilder = new TruckBuilder();
        return (new Director())->build($truckBuilder);
    }
    public function testCanBuildCar()
    {
        $carBuilder = new CarBuilder();
        return (new Director())->build($carBuilder);
    }
}
$directorTest = new DirectorTest();
var_dump($directorTest->testCanBuildTruck());
var_dump($directorTest->testCanBuildCar());

The above is the detailed content of PHP design pattern (creative). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete