1: Factory mode

For example: Auth: : the user ()

Here the Auth class is the method in the factory, and Auth is the alias in the registry tree.

Benefits:

Similar to function encapsulation, objects have a unified generation (instantiation) entry point. When the name of our object’s corresponding class changes, we just need to change the instantiation method in the factory class.

2: singleton mode

Benefits:

Objects cannot be instantiated externally and can only be instantiated once, saving resources.

Implementation method:

private static $ins = null;                                                //设置私有的属性

private function __construct() {}                                       //使外部无法new这个类

public static function getIns() {                                        //暴露给外部的调用方法

        if(self::$ins instanceof self) {

                return self::$ins;

        } else {

                self::$ins = new self();

                return self::$ins;

        }

}
Copy the code

A static variable that declares a class private or protected. The constructor is declared private (no external new operations are allowed), instantiated if it does not exist, and returned if it does.

3: register tree mode

Use:

The aliases array in config/app is a registration tree

Benefits:

The registration tree pattern uses an array structure to access objects. Factory methods need to be called only once (in a place such as initialization in the system environment), and can be pulled directly from the registration tree when the object needs to be called, without the need to call factory methods and singletons.

Implementation method:

Class Register {protected static $objects function set($alias,$object) {self::$objects[$alias]=$object; } static function get($name) {return self::$objects[$name]; } function _unset($alias) {// Remove object unset(self::$onjects[$alias]); }}Copy the code

$alias Indicates an alias

Add in factory mode

Register: : set (db1, $db);

Calling anywhere else just calls the registrar to read

Register: : $objects (” db1 “),

4: Adapter mode

Encapsulate different function interfaces of different tools into a unified API for easy call. For example: mysql, mysqli, PDO.

Implementation: declare a uniform method body in an interface class, then let different classes implement the interface and override its abstract methods.

interface Database {                                                  

        function connect($host,$user,$password,$dbname);

        function query($sql);

        function close();

}
Copy the code

Then use different utility functions to implement the same interface.

5: Policy mode

Benefits:

It encapsulates a set of specific behaviors and algorithms into classes to adapt to some specific context, separates logical judgment from concrete implementation, realizes hard coding to decoupling, and realizes IOC, dependency inversion and inversion control.

Implementation:

1. Define a policy interface file (userstrategy.php) to define the policy interface and declare the policy

2. Define concrete classes (femaleUserStrategy.php, maleUserStrategy.php), implement the policy interface, and rewrite the policy methods

class Page { protected $strategy; function index() { if($request->get('female')) { $strategy=new FemaleUserStrategy(); } else { $strategy=new MaleUserStrategy(); } $this->strategy->method(); } public function __construct(UserStrategy $strategy) { $this->strategy=$strategy; }}Copy the code

6: Data object mapping mode

Benefits: By mapping objects to datastores, operations on one object are mapped to operations on the datastore, which is how ORM works.

class Model { public $id; public $name; public $email; ... // construct($id) {function __construct($id) {// Constructor, executed automatically when class is called, used for initialization. // query logic} function __destruct() {// The destruct function, which is automatically executed after the class call, is used to destroy instances and free resources. // add/delete logic}}Copy the code

7: Observer mode

Use:

Trigger a type of Event

<? php namespace App\Events; Abstract class Event {// logical code}Copy the code

Listening class EventListener

<? php namespace App\Listeners; use App\Events\SomeEvent; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; class EventListener { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param SomeEvent $event * @return void */ public function handle(SomeEvent $event) { // } }Copy the code

Benefits:

When the state of an object changes, all dependent objects will be notified and automatically updated, realizing a low-coupling, non-invasive notification and update mechanism.

8: Prototype mode

Similar to factory mode, it is used to create objects, but the difference is that in prototype mode, a prototype object is first created and then cloned to create new objects. Prototype mode is suitable for creating large objects, and only memory copy is required.

$Object = new Object();
$object_1 = clone $Object;
$object_2 = clone $Object;
Copy the code

9: Decorator mode

The traditional way to modify or add functionality to a class is to write a subclass that inherits it and reimplements the class’s methods. Decorator mode dynamically adds or modifies the functionality of a class simply by adding a decorator object at run time.

Traditional methods:

class Method2 extends Method { function doSomething() { echo "<div style='color:red'>" parent::doSomething(); echo "</div>"; }} Interfa Decorator {// Define Decorator interface function beforeAction(); function afterAction(); / / more decoratorMethod... } class SomeClass { protected $decorators = []; function addDecorator(Decorator $decorator) { $this->decorators[] = $decorator; } function beforeMethod() { foreach ($this->decorators as $row) { $row->beforeAction(); } } function afterMethod() { $decorators = array_reverse($this->decorators); Foreach ($this->decorators as $row) {$row->afterAction(); } } function action() { $this->beforeMethod(); //method; $this->afterMethod(); } } class OneDecorator implements Decorator { protected $datas; function __construct($datas = 'request') { $this->datas = $datas; } function beforeAction() { echo "<div style='color:{$this->datas}; '> "; } function afterAction() { echo "</div>"; } } $Object = new \SomeClass(); $Object->addDecorator(new \OneDecorator('blue')); //Add other decorator... $Object->action();Copy the code

10: Iterator pattern

Iterating through the internal elements of an aggregate object, without knowing the internal implementation, allows you to iterate over the required operations of the elements compared to traditional programming.

Such as:

Object::all() Iterator extends Traversable {abstract public mixed current (void) abstract public scalar key (void) abstract public void next (void) abstract public void rewind (void) abstract public boolean valid (void) } class ObjectAll implements \Iterator { protected $ids; // The id of all objects protected $index; Protected $data = array(); Function __construct() {$ids} function current() {$ids} function current() { $id = $this->ids[$this->index]['id']; return Object::find($id); } function next() {$this->index ++; $this->index < count($this->$ids); $this-> count($this->$ids); } function rewind() {$this->index = 0; $this->index = 0; } function key() {return $this->index; } } $objects = new \ObjectAll(); foreach ($objects as $row) { dump($row->field); // add, delete, change, checkCopy the code

11: proxy mode

A proxy object is set up between the client and the entity, and all the operations of the client on the entity are delegated to the proxy object, hiding the implementation details of the entity (the slave read library is separated from the master write library). Proxy objects can also be deployed to separate servers from business code, where tasks are delegated through PRC.

interface DBproxy { function getInfo($id); function setInfo($id, $value); \ } class Proxy implements DBproxy { function get() { //DB::('slave'); query } function set() { //DB::('master'); query } } $proxy = new Proxy(); $proxy->get($id); $proxy->set($id, $value);Copy the code

! [](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/2da0e965382c4aa98edb2fce0887788d~tplv-k3u1fbpfcp-zoom-1.image)