Advantages of using strategy pattern in php

前端 未结 6 815
耶瑟儿~
耶瑟儿~ 2021-02-02 13:42

I can\'t seem to get my head around what advantages the strategy pattern offer. See the example below.

//Implementation without the strategy pattern
class Regist         


        
6条回答
  •  悲&欢浪女
    2021-02-02 14:27

    Basically Strategy is for grouping functionality across multiple classes. Oh and you have a typo in your code

    class context {
    
          public function printMsg(registry $class){
              $class->printMsg();
          }
    }
    

    With the name of the interface of the type hinting. To be more clear let me show you a small example. Imagine you have an Iphone and an Android What's their common point? One is They are both phones. you could create an interface like this

    interface Telephone {
        public function enterNumber();
        public function call();
        public function sentTextMessage();
    }
    

    and implement the interface in each of your telephones:

    class Iphone implements Telephone {
         // implement interface methods
    }
    
    class Android implement Telephone {
    
    }
    

    and you can have a service attached to all phones like a GPS on you car: and be sure that if you plug a telephone (usually with the interface BlueTooth). you could do something like this:

    class carGps{
       public function handFreeCall(Telephone $tel){
           $this->amplifyVolume($tel->call());
       }
    }
    
    
    $tomtom = new CarGps();
    $tomtom->handFreeCall(new Iphone());
    //or if you like to:
    $tomtom->handFreeCall(new Android());
    

    as an application developer, you'll be able to use your handFreeCall on every phones that implements the Telephone interface without breaking your code, because you'll know that the telephone is capable of calling.

    Hope I helped.

提交回复
热议问题