The difference between strategy and state design patterm, How a state is aware of its predecessor?












0















I read about state and strategy design patterns in refactoring.guru web site in pages State and Strategy. The author says




This structure may look similar to the Strategy pattern, but there’s one key difference. In the State pattern, the particular states may be aware of each other and initiate transitions from one state to another, whereas strategies almost never know about each other.




The author also says, the ConcereteState classes, store a variable context which is an object to Context class and by this variable, states may aware of each other.



There are two things I can't understand:




  1. How a state is aware of its predecessor?

  2. Where should I implement the logic of transition between states? For example state1 by input a moves to state2 and by b moves to state4, where exactly this logic must be implemented?


This is a simple implementation of strategy I implemented in php language



<?php
class Algorithms{
public $algorithm;
function __construct(AlgorithmsInterface $algorithm){
$this->algorithm = $algorithm;
}

public function run(){
$this->algorithm->run();
}
}

interface AlgorithmsInterface{
public function run();
}

class Algorithm1 implements AlgorithmsInterface{
public function run(){
print "Algorithm1";
}
}

class Algorithm2 implements AlgorithmsInterface{
public function run(){
print "Algorithm2";
}
}


$payment = new Algorithms(new Algorithm2());
$payment->run();


and this is a simple implementation of State design pattern I implemented



<?php
interface State{
public function execute();
}

class Context{

public $state;

public function __construct(State $initialState){
$this->state = $initialState;
}

public function changeState(State $state){
$this->state = $state;
}

public function execute(){
$this->state->execute();
}
}

class State1 implements State{
public function execute(){
print "This is State1";
}
}

class State2 implements State{
public function execute(){
print "This is State2";
}
}

$initialState = new State1();
$state2 = new State2();
$context = new Context($initialState);
$context->execute();
$context->changeState($state2);
$context->execute();

?>


I can't see much difference between state and strategy while I know exactly what the intents of these strategies are. Besides that, the logic of movement between states and the way a state should be aware of its parent are missed from the code.










share|improve this question





























    0















    I read about state and strategy design patterns in refactoring.guru web site in pages State and Strategy. The author says




    This structure may look similar to the Strategy pattern, but there’s one key difference. In the State pattern, the particular states may be aware of each other and initiate transitions from one state to another, whereas strategies almost never know about each other.




    The author also says, the ConcereteState classes, store a variable context which is an object to Context class and by this variable, states may aware of each other.



    There are two things I can't understand:




    1. How a state is aware of its predecessor?

    2. Where should I implement the logic of transition between states? For example state1 by input a moves to state2 and by b moves to state4, where exactly this logic must be implemented?


    This is a simple implementation of strategy I implemented in php language



    <?php
    class Algorithms{
    public $algorithm;
    function __construct(AlgorithmsInterface $algorithm){
    $this->algorithm = $algorithm;
    }

    public function run(){
    $this->algorithm->run();
    }
    }

    interface AlgorithmsInterface{
    public function run();
    }

    class Algorithm1 implements AlgorithmsInterface{
    public function run(){
    print "Algorithm1";
    }
    }

    class Algorithm2 implements AlgorithmsInterface{
    public function run(){
    print "Algorithm2";
    }
    }


    $payment = new Algorithms(new Algorithm2());
    $payment->run();


    and this is a simple implementation of State design pattern I implemented



    <?php
    interface State{
    public function execute();
    }

    class Context{

    public $state;

    public function __construct(State $initialState){
    $this->state = $initialState;
    }

    public function changeState(State $state){
    $this->state = $state;
    }

    public function execute(){
    $this->state->execute();
    }
    }

    class State1 implements State{
    public function execute(){
    print "This is State1";
    }
    }

    class State2 implements State{
    public function execute(){
    print "This is State2";
    }
    }

    $initialState = new State1();
    $state2 = new State2();
    $context = new Context($initialState);
    $context->execute();
    $context->changeState($state2);
    $context->execute();

    ?>


    I can't see much difference between state and strategy while I know exactly what the intents of these strategies are. Besides that, the logic of movement between states and the way a state should be aware of its parent are missed from the code.










    share|improve this question



























      0












      0








      0








      I read about state and strategy design patterns in refactoring.guru web site in pages State and Strategy. The author says




      This structure may look similar to the Strategy pattern, but there’s one key difference. In the State pattern, the particular states may be aware of each other and initiate transitions from one state to another, whereas strategies almost never know about each other.




      The author also says, the ConcereteState classes, store a variable context which is an object to Context class and by this variable, states may aware of each other.



      There are two things I can't understand:




      1. How a state is aware of its predecessor?

      2. Where should I implement the logic of transition between states? For example state1 by input a moves to state2 and by b moves to state4, where exactly this logic must be implemented?


      This is a simple implementation of strategy I implemented in php language



      <?php
      class Algorithms{
      public $algorithm;
      function __construct(AlgorithmsInterface $algorithm){
      $this->algorithm = $algorithm;
      }

      public function run(){
      $this->algorithm->run();
      }
      }

      interface AlgorithmsInterface{
      public function run();
      }

      class Algorithm1 implements AlgorithmsInterface{
      public function run(){
      print "Algorithm1";
      }
      }

      class Algorithm2 implements AlgorithmsInterface{
      public function run(){
      print "Algorithm2";
      }
      }


      $payment = new Algorithms(new Algorithm2());
      $payment->run();


      and this is a simple implementation of State design pattern I implemented



      <?php
      interface State{
      public function execute();
      }

      class Context{

      public $state;

      public function __construct(State $initialState){
      $this->state = $initialState;
      }

      public function changeState(State $state){
      $this->state = $state;
      }

      public function execute(){
      $this->state->execute();
      }
      }

      class State1 implements State{
      public function execute(){
      print "This is State1";
      }
      }

      class State2 implements State{
      public function execute(){
      print "This is State2";
      }
      }

      $initialState = new State1();
      $state2 = new State2();
      $context = new Context($initialState);
      $context->execute();
      $context->changeState($state2);
      $context->execute();

      ?>


      I can't see much difference between state and strategy while I know exactly what the intents of these strategies are. Besides that, the logic of movement between states and the way a state should be aware of its parent are missed from the code.










      share|improve this question
















      I read about state and strategy design patterns in refactoring.guru web site in pages State and Strategy. The author says




      This structure may look similar to the Strategy pattern, but there’s one key difference. In the State pattern, the particular states may be aware of each other and initiate transitions from one state to another, whereas strategies almost never know about each other.




      The author also says, the ConcereteState classes, store a variable context which is an object to Context class and by this variable, states may aware of each other.



      There are two things I can't understand:




      1. How a state is aware of its predecessor?

      2. Where should I implement the logic of transition between states? For example state1 by input a moves to state2 and by b moves to state4, where exactly this logic must be implemented?


      This is a simple implementation of strategy I implemented in php language



      <?php
      class Algorithms{
      public $algorithm;
      function __construct(AlgorithmsInterface $algorithm){
      $this->algorithm = $algorithm;
      }

      public function run(){
      $this->algorithm->run();
      }
      }

      interface AlgorithmsInterface{
      public function run();
      }

      class Algorithm1 implements AlgorithmsInterface{
      public function run(){
      print "Algorithm1";
      }
      }

      class Algorithm2 implements AlgorithmsInterface{
      public function run(){
      print "Algorithm2";
      }
      }


      $payment = new Algorithms(new Algorithm2());
      $payment->run();


      and this is a simple implementation of State design pattern I implemented



      <?php
      interface State{
      public function execute();
      }

      class Context{

      public $state;

      public function __construct(State $initialState){
      $this->state = $initialState;
      }

      public function changeState(State $state){
      $this->state = $state;
      }

      public function execute(){
      $this->state->execute();
      }
      }

      class State1 implements State{
      public function execute(){
      print "This is State1";
      }
      }

      class State2 implements State{
      public function execute(){
      print "This is State2";
      }
      }

      $initialState = new State1();
      $state2 = new State2();
      $context = new Context($initialState);
      $context->execute();
      $context->changeState($state2);
      $context->execute();

      ?>


      I can't see much difference between state and strategy while I know exactly what the intents of these strategies are. Besides that, the logic of movement between states and the way a state should be aware of its parent are missed from the code.







      algorithm design-patterns






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 31 '18 at 16:56







      No one

















      asked Dec 31 '18 at 6:21









      No oneNo one

      6741031




      6741031
























          1 Answer
          1






          active

          oldest

          votes


















          1














          From your examples the two patterns look very similar. But your example of State design pattern is not really state design pattern, because you are setting the state from outside.
          Typical state design pattern changes state internally and very often delegates the change to the state itself.
          Let's look at simple toggle button. It has a state, and method to press it, and method to describe current state (toString()):



          class ToggleButton {
          enum State {
          ON {
          public State press() {
          return OFF;
          }
          },
          OFF {
          public State press() {
          return ON;
          }
          };
          abstract public State press();
          }

          State state = State.OFF;
          public void press() {
          state = state.press();
          }
          public String toString() {
          return "Device is " + state;
          }
          }


          So from outside you're not setting the state, so you don't know in which state it is and how it will react. You use:



          button.press();
          System.out.println(button);


          So the key difference is, that for strategy, you pass the strategy from outside, and let your object perform some operation (which doesn't change the strategy), so it's sticky delegation.



          But purpose of State design pattern is, that the state is supposed to change, very often intrrnally, and with change of the state also the behavior changes. So even if we set some state before computation of some task, it may change (typically does) internally during the task to complete it.
          It's a way to achieve state polymorphism. Also notice, that it's often related to state automata.






          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53984246%2fthe-difference-between-strategy-and-state-design-patterm-how-a-state-is-aware-o%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            From your examples the two patterns look very similar. But your example of State design pattern is not really state design pattern, because you are setting the state from outside.
            Typical state design pattern changes state internally and very often delegates the change to the state itself.
            Let's look at simple toggle button. It has a state, and method to press it, and method to describe current state (toString()):



            class ToggleButton {
            enum State {
            ON {
            public State press() {
            return OFF;
            }
            },
            OFF {
            public State press() {
            return ON;
            }
            };
            abstract public State press();
            }

            State state = State.OFF;
            public void press() {
            state = state.press();
            }
            public String toString() {
            return "Device is " + state;
            }
            }


            So from outside you're not setting the state, so you don't know in which state it is and how it will react. You use:



            button.press();
            System.out.println(button);


            So the key difference is, that for strategy, you pass the strategy from outside, and let your object perform some operation (which doesn't change the strategy), so it's sticky delegation.



            But purpose of State design pattern is, that the state is supposed to change, very often intrrnally, and with change of the state also the behavior changes. So even if we set some state before computation of some task, it may change (typically does) internally during the task to complete it.
            It's a way to achieve state polymorphism. Also notice, that it's often related to state automata.






            share|improve this answer






























              1














              From your examples the two patterns look very similar. But your example of State design pattern is not really state design pattern, because you are setting the state from outside.
              Typical state design pattern changes state internally and very often delegates the change to the state itself.
              Let's look at simple toggle button. It has a state, and method to press it, and method to describe current state (toString()):



              class ToggleButton {
              enum State {
              ON {
              public State press() {
              return OFF;
              }
              },
              OFF {
              public State press() {
              return ON;
              }
              };
              abstract public State press();
              }

              State state = State.OFF;
              public void press() {
              state = state.press();
              }
              public String toString() {
              return "Device is " + state;
              }
              }


              So from outside you're not setting the state, so you don't know in which state it is and how it will react. You use:



              button.press();
              System.out.println(button);


              So the key difference is, that for strategy, you pass the strategy from outside, and let your object perform some operation (which doesn't change the strategy), so it's sticky delegation.



              But purpose of State design pattern is, that the state is supposed to change, very often intrrnally, and with change of the state also the behavior changes. So even if we set some state before computation of some task, it may change (typically does) internally during the task to complete it.
              It's a way to achieve state polymorphism. Also notice, that it's often related to state automata.






              share|improve this answer




























                1












                1








                1







                From your examples the two patterns look very similar. But your example of State design pattern is not really state design pattern, because you are setting the state from outside.
                Typical state design pattern changes state internally and very often delegates the change to the state itself.
                Let's look at simple toggle button. It has a state, and method to press it, and method to describe current state (toString()):



                class ToggleButton {
                enum State {
                ON {
                public State press() {
                return OFF;
                }
                },
                OFF {
                public State press() {
                return ON;
                }
                };
                abstract public State press();
                }

                State state = State.OFF;
                public void press() {
                state = state.press();
                }
                public String toString() {
                return "Device is " + state;
                }
                }


                So from outside you're not setting the state, so you don't know in which state it is and how it will react. You use:



                button.press();
                System.out.println(button);


                So the key difference is, that for strategy, you pass the strategy from outside, and let your object perform some operation (which doesn't change the strategy), so it's sticky delegation.



                But purpose of State design pattern is, that the state is supposed to change, very often intrrnally, and with change of the state also the behavior changes. So even if we set some state before computation of some task, it may change (typically does) internally during the task to complete it.
                It's a way to achieve state polymorphism. Also notice, that it's often related to state automata.






                share|improve this answer















                From your examples the two patterns look very similar. But your example of State design pattern is not really state design pattern, because you are setting the state from outside.
                Typical state design pattern changes state internally and very often delegates the change to the state itself.
                Let's look at simple toggle button. It has a state, and method to press it, and method to describe current state (toString()):



                class ToggleButton {
                enum State {
                ON {
                public State press() {
                return OFF;
                }
                },
                OFF {
                public State press() {
                return ON;
                }
                };
                abstract public State press();
                }

                State state = State.OFF;
                public void press() {
                state = state.press();
                }
                public String toString() {
                return "Device is " + state;
                }
                }


                So from outside you're not setting the state, so you don't know in which state it is and how it will react. You use:



                button.press();
                System.out.println(button);


                So the key difference is, that for strategy, you pass the strategy from outside, and let your object perform some operation (which doesn't change the strategy), so it's sticky delegation.



                But purpose of State design pattern is, that the state is supposed to change, very often intrrnally, and with change of the state also the behavior changes. So even if we set some state before computation of some task, it may change (typically does) internally during the task to complete it.
                It's a way to achieve state polymorphism. Also notice, that it's often related to state automata.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 1 at 22:45

























                answered Jan 1 at 22:35









                Ondřej FischerOndřej Fischer

                200211




                200211
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53984246%2fthe-difference-between-strategy-and-state-design-patterm-how-a-state-is-aware-o%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    How to fix TextFormField cause rebuild widget in Flutter

                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith