编程知识 cdmana.com

Sharing meta model of PHP design pattern

The flyweight pattern ,“ Enjoying yuan ” These two words have no special meaning in Chinese , So we're going to split it up and see .“ enjoy ” It's sharing ,“ element ” Is the element , So it seems easy to understand , Share some elements .

Gof Class diagram and explanation

GoF Definition : Using sharing technology to effectively support a large number of fine-grained objects

GoF Class diagram

 The flyweight pattern

Code implementation

interface Flyweight
{
    public function operation($extrinsicState) : void;
}

class ConcreteFlyweight implements Flyweight
{
    private $intrinsicState = 101;
    function operation($extrinsicState) : void
    {
        echo ' Shared share object ' . ($extrinsicState + $this->intrinsicState) . PHP_EOL;
    }
}

class UnsharedConcreteFlyweight implements Flyweight
{
    private $allState = 1000;
    public function operation($extrinsicState) : void
    {
        echo ' Nonshared shared metaobjects :' . ($extrinsicState + $this->allState) . PHP_EOL;
    }
}

Define the shared interface and its implementation , Notice here are two implementations ,ConcreteFlyweigh Share state ,UnsharedConcreteFlyweight Don't share, or his state doesn't need to be shared

class FlyweightFactory
{
    private $flyweights = [];

    public function getFlyweight($key) : Flyweight
    {
        if (!array_key_exists($key, $this->flyweights)) {
            $this->flyweights[$key] = new ConcreteFlyweight();
        }
        return $this->flyweights[$key];
    }
}

Save objects that need to be shared , As a factory to create the required shared objects , Ensure that there will be only one object under the same key value , Save the cost of creating the same object

$factory = new FlyweightFactory();

$extrinsicState = 100;
$flA = $factory->getFlyweight('a');
$flA->operation(--$extrinsicState);

$flB = $factory->getFlyweight('b');
$flB->operation(--$extrinsicState);

$flC = $factory->getFlyweight('c');
$flC->operation(--$extrinsicState);

$flD = new UnsharedConcreteFlyweight();
$flD->operation(--$extrinsicState);

Client call , Let the external state $extrinsicState Be able to share between objects

  • It's kind of interesting , This model has a lot of code
  • When an application uses a large number of very similar objects , When most of the states of an object become external states , It's very suitable for Xiangyuan mode
  • The factory here stores the list of objects , It's not like factory methods or abstract factories to create objects , Although it was created here , But if the object exists , Will return directly to , And lists are always maintained
  • In reality, Xiangyuan mode , You must have used , Various pool technologies are typical applications : Thread pool 、 Connection pools and so on , Two other identical strings String Type in the php or Java All of them can be === Of , This also applies to the Xiangyuan model , They even have the same memory address , This is a kind of sharing
  • About the Heyuan model , There's a very classic example , Much better than my next example , That's the board of go . Go is only black and white , So two objects are enough , The next? ? Just change their position and state ! Interested friends can search ha !
  • Laravel Medium IoC The container can be seen as an implementation of the sharing pattern . Save it in an array , Access through closure mechanism when necessary , There are also classes that share some state properties . You can look at the code to understand .

Or when it comes to the fact that technology is based on changing shells . After all , We all like mobile phones of various colors to show our personality . I said before , If we have to build a production line for each color, it's not a huge investment . not so bad , Our factory for each model ( The flyweight factory ) Only the most basic background shell ( object ), And then through a special printing line ( State change ) It's better to paint ! Um. , The next one Iphone Sooner or later, they will imitate us , It seems that we have to take all kinds of gold first 、 All kinds of local color can be collected , Maybe we can summon the dragon !!

Complete code :https://github.com/zhangyue0503/designpatterns-php/blob/master/13.flyweights/source/flyweights.php

example

Sure enough, we're still texting , This time, the text messages are still sent by alicloud and aurora , However, this time, we use the share mode to implement it , We have two different types of objects in Xiangyuan factory , Let them change through internal and external states !

SMS sending class diagram

 SMS sending enjoys yuan mode version

Complete source code :https://github.com/zhangyue0503/designpatterns-php/blob/master/13.flyweights/source/flyweights-message.php


<?php

interface Message
{
    public function send(User $user);
}

class AliYunMessage implements Message
{
    private $template;
    public function __construct($template)
    {
        $this->template = $template;
    }
    public function send(User $user)
    {
        echo ' Use alicloud SMS to ' . $user->GetName() . ' send out :';
        echo $this->template->GetTemplate(), PHP_EOL;
    }
}

class JiGuangMessage implements Message
{
    private $template;
    public function __construct($template)
    {
        $this->template = $template;
    }
    public function send(User $user)
    {
        echo ' Use Aurora text messages to ' . $user->GetName() . ' send out :';
        echo $this->template->GetTemplate(), PHP_EOL;
    }
}

class MessageFactory
{
    private $messages = [];
    public function GetMessage(Template $template, $type = 'ali')
    {
        $key = md5($template->GetTemplate() . $type);
        if (!key_exists($key, $this->messages)) {
            if ($type == 'ali') {
                $this->messages[$key] = new AliYunMessage($template);
            } else {
                $this->messages[$key] = new JiGuangMessage($template);
            }
        }
        return $this->messages[$key];
    }

    public function GetMessageCount()
    {
        echo count($this->messages);
    }
}

class User
{
    public $name;
    public function GetName()
    {
        return $this->name;
    }
}

class Template
{
    public $template;
    public function GetTemplate()
    {
        return $this->template;
    }
}

//  Internal state 
$t1 = new Template();
$t1->template = ' Templates 1, Not bad !';

$t2 = new Template();
$t2->template = ' Templates 2, It's not bad !';

//  External state 
$u1 = new User();
$u1->name = ' Zhang San ';

$u2 = new User();
$u2->name = ' Li Si ';

$u3 = new User();
$u3->name = ' Wang Wu ';

$u4 = new User();
$u4->name = ' Zhao Liu ';

$u5 = new User();
$u5->name = ' Panax notoginseng ';

//  The flyweight factory 
$factory = new MessageFactory();

//  Alibaba cloud sends 
$m1 = $factory->GetMessage($t1);
$m1->send($u1);

$m2 = $factory->GetMessage($t1);
$m2->send($u2);

echo $factory->GetMessageCount(), PHP_EOL; // 1

$m3 = $factory->GetMessage($t2);
$m3->send($u2);

$m4 = $factory->GetMessage($t2);
$m4->send($u3);

echo $factory->GetMessageCount(), PHP_EOL; // 2

$m5 = $factory->GetMessage($t1);
$m5->send($u4);

$m6 = $factory->GetMessage($t2);
$m6->send($u5);

echo $factory->GetMessageCount(), PHP_EOL; // 2

//  Add Aurora 
$m1 = $factory->GetMessage($t1, 'jg');
$m1->send($u1);

$m2 = $factory->GetMessage($t1);
$m2->send($u2);

echo $factory->GetMessageCount(), PHP_EOL; // 3

$m3 = $factory->GetMessage($t2);
$m3->send($u2);

$m4 = $factory->GetMessage($t2, 'jg');
$m4->send($u3);

echo $factory->GetMessageCount(), PHP_EOL; // 4

$m5 = $factory->GetMessage($t1, 'jg');
$m5->send($u4);

$m6 = $factory->GetMessage($t2, 'jg');
$m6->send($u5);

echo $factory->GetMessageCount(), PHP_EOL; // 4


explain

  • A little bit of code , But there are actually two types of classes , Four kinds of objects are generated . The different objects of each class are distinguished according to the template
  • This combination is more convenient , Combine with other models to optimize the factory here , Um. , The future is limitless , Think about it. You can !
  • The Heyuan mode is suitable for scenarios where there are a large number of similar objects in the system and buffer pools are needed , Can reduce memory footprint , Increase of efficiency , But it increases the complexity , Need to share internal and external state
  • The main feature is that there is a unique identifier , When the object already exists in memory , Return the object directly , No more creation

Next time, we'll see

The example of Xiangyuan model is a little far fetched , But it is true that this kind of design pattern is not used much in our daily development , On the other hand, typical examples are too classic , Anyway, just remember its characteristics , I can't tell you when I write the code. When I look back, you will find that this is the sharing pattern I have learned ! Okay , In the next chapter, we will learn a less used and more complex pattern , But maybe you can see it often ! Portfolio model

Official account :【 Hard core project manager 】 Get the latest article

Add wechat /QQ Good friends :【xiaoyuezigonggong/149844827】 Free PHP、 Project management learning materials

You know 、 official account 、 Tiktok 、 Headline search 【 Hard core project manager 】

B standing ID:482780532

版权声明
本文为[Hard core project manager]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224115213702T.html

Scroll to Top