Strategy design pattern for writing to a file or to the console

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
1
down vote

favorite












I have this interface for all strategies:



type PrintStrategy interface 
Print() error



of two types:



type ConsoleStrategy struct

type FileStrategy struct
DestinationFilePath string



with two concrete implementations of strategy:



func (c *ConsoleStrategy) Print() error 
fmt.Println("ConsoleStrategy")
lister, _ := template.New("foo").Parse(tplTemplate())
lister.Execute(os.Stdout, tplParams())
return nil


func (c *FileStrategy) Print() error
fmt.Println("FileStrategy")
var t bytes.Buffer
foo, _ := template.New("bar").Parse(tplTemplate())
foo.Execute(&t, tplParams())

f, err := os.Create(c.DestinationFilePath)
if err != nil
panic(err)

defer f.Close()
f.Write(t.Bytes())
return nil



and finally a main function that gets the strategy from the console and prints the content built inside tplTemplate() to the console or a file.



func main() 
strategy := flag.String("strategy", "console", "selected strategy")
flag.Parse()

var printStrategy PrintStrategy

switch *strategy
case "console":
printStrategy = &ConsoleStrategy
case "file":
printStrategy = &FileStrategy"bigciao"
default:
printStrategy = &ConsoleStrategy


printStrategy.Print()



Is this a good example of using the pattern?







share|improve this question



























    up vote
    1
    down vote

    favorite












    I have this interface for all strategies:



    type PrintStrategy interface 
    Print() error



    of two types:



    type ConsoleStrategy struct

    type FileStrategy struct
    DestinationFilePath string



    with two concrete implementations of strategy:



    func (c *ConsoleStrategy) Print() error 
    fmt.Println("ConsoleStrategy")
    lister, _ := template.New("foo").Parse(tplTemplate())
    lister.Execute(os.Stdout, tplParams())
    return nil


    func (c *FileStrategy) Print() error
    fmt.Println("FileStrategy")
    var t bytes.Buffer
    foo, _ := template.New("bar").Parse(tplTemplate())
    foo.Execute(&t, tplParams())

    f, err := os.Create(c.DestinationFilePath)
    if err != nil
    panic(err)

    defer f.Close()
    f.Write(t.Bytes())
    return nil



    and finally a main function that gets the strategy from the console and prints the content built inside tplTemplate() to the console or a file.



    func main() 
    strategy := flag.String("strategy", "console", "selected strategy")
    flag.Parse()

    var printStrategy PrintStrategy

    switch *strategy
    case "console":
    printStrategy = &ConsoleStrategy
    case "file":
    printStrategy = &FileStrategy"bigciao"
    default:
    printStrategy = &ConsoleStrategy


    printStrategy.Print()



    Is this a good example of using the pattern?







    share|improve this question























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I have this interface for all strategies:



      type PrintStrategy interface 
      Print() error



      of two types:



      type ConsoleStrategy struct

      type FileStrategy struct
      DestinationFilePath string



      with two concrete implementations of strategy:



      func (c *ConsoleStrategy) Print() error 
      fmt.Println("ConsoleStrategy")
      lister, _ := template.New("foo").Parse(tplTemplate())
      lister.Execute(os.Stdout, tplParams())
      return nil


      func (c *FileStrategy) Print() error
      fmt.Println("FileStrategy")
      var t bytes.Buffer
      foo, _ := template.New("bar").Parse(tplTemplate())
      foo.Execute(&t, tplParams())

      f, err := os.Create(c.DestinationFilePath)
      if err != nil
      panic(err)

      defer f.Close()
      f.Write(t.Bytes())
      return nil



      and finally a main function that gets the strategy from the console and prints the content built inside tplTemplate() to the console or a file.



      func main() 
      strategy := flag.String("strategy", "console", "selected strategy")
      flag.Parse()

      var printStrategy PrintStrategy

      switch *strategy
      case "console":
      printStrategy = &ConsoleStrategy
      case "file":
      printStrategy = &FileStrategy"bigciao"
      default:
      printStrategy = &ConsoleStrategy


      printStrategy.Print()



      Is this a good example of using the pattern?







      share|improve this question













      I have this interface for all strategies:



      type PrintStrategy interface 
      Print() error



      of two types:



      type ConsoleStrategy struct

      type FileStrategy struct
      DestinationFilePath string



      with two concrete implementations of strategy:



      func (c *ConsoleStrategy) Print() error 
      fmt.Println("ConsoleStrategy")
      lister, _ := template.New("foo").Parse(tplTemplate())
      lister.Execute(os.Stdout, tplParams())
      return nil


      func (c *FileStrategy) Print() error
      fmt.Println("FileStrategy")
      var t bytes.Buffer
      foo, _ := template.New("bar").Parse(tplTemplate())
      foo.Execute(&t, tplParams())

      f, err := os.Create(c.DestinationFilePath)
      if err != nil
      panic(err)

      defer f.Close()
      f.Write(t.Bytes())
      return nil



      and finally a main function that gets the strategy from the console and prints the content built inside tplTemplate() to the console or a file.



      func main() 
      strategy := flag.String("strategy", "console", "selected strategy")
      flag.Parse()

      var printStrategy PrintStrategy

      switch *strategy
      case "console":
      printStrategy = &ConsoleStrategy
      case "file":
      printStrategy = &FileStrategy"bigciao"
      default:
      printStrategy = &ConsoleStrategy


      printStrategy.Print()



      Is this a good example of using the pattern?









      share|improve this question












      share|improve this question




      share|improve this question








      edited May 1 at 19:48









      200_success

      123k14142399




      123k14142399









      asked May 1 at 7:00









      sensorario

      1366




      1366




















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          2
          down vote













          According to the GoF, Strategy pattern:




          Define a family of algorithms, encapsulate each one, and make them
          interchangeable. Strategy lets the algorithm vary independently from
          the clients that use it.




          See that the objective is disacouplished client (context object) of your possibles behaviours. So there is two basics elements in this pattern: context object and strategies.



          The contexts objects have domain problems that must be separated from each other, so different algorithms. See in image(source in: https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm):



          UML diagram for Strategy Pattern



          All this allow that you can work to an interface without worrying implementation strategy.



          In your code there is no context object, so this is wrong. If there is no context object, the problem does not exist either.



          Refactoring your code, we will have the following strategies:



          // ----------------------------------------------
          // in strategies.go files
          // ----------------------------------------------

          type PrintStrategy interface
          Print() error


          type ConsoleStrategy struct
          func (c ConsoleStrategy) Print() error
          fmt.Println("Hello, playground by console strategy")
          return nil


          type FileStrategy struct DestinationFilePath string
          func (c FileStrategy) Print() error
          //print in file c.DestinationFilePath
          fmt.Println("Hello, playground by file strategy")
          return nil


          type DefaultStrategy struct
          func (c DefaultStrategy) Print() error
          //print in printer device
          fmt.Println("Hello, playground by default strategy")
          return nil



          And the following context object:



          // ----------------------------------------------
          // in context.go files
          // ----------------------------------------------
          type MyContextObject struct
          ps PrintStrategy


          func (m MyContextObject) Print()
          //check if PrintingStrategy is not nil
          err := m.ps.Print()
          if err != nil
          panic("Fail on PrintMyDatas")



          func NewMyContextObject(p PrintStrategy) MyContextObject
          if (p != nil)
          return MyContextObjectp
          else
          return MyContextObjectDefaultStrategy




          See that on instancing of MyContextObject an behaviour is passed. In your case the behaviour for this context is provided by argument passing on executing. In another case you might like change the behaviour in according with the content size. These are different context using same strategy.



          func main() 
          //read args
          strategy := flag.String("strategy", "console", "selected strategy")
          flag.Parse()

          //context object that needs to print your datas in according with
          //an user arg.
          var m MyContextObject

          //this statments can be replaced by factory method
          switch *strategy
          case "console":
          m = NewMyContextObject(ConsoleStrategy)
          case "file":
          m = NewMyContextObject(FileStrategy"bigciao")
          default:
          m = NewMyContextObject(nil)

          //
          m.Print()



          Now you can does more strategies or share this behaviour in other contexts.
          This is a good practical of reuse!!



          This code is in https://play.golang.org/p/P-kGGOwDDRt.



          I hope I helped you!






          share|improve this answer























            Your Answer




            StackExchange.ifUsing("editor", function ()
            return StackExchange.using("mathjaxEditing", function ()
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            );
            );
            , "mathjax-editing");

            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: "196"
            ;
            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',
            convertImagesToLinks: false,
            noModals: false,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );








             

            draft saved


            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f193328%2fstrategy-design-pattern-for-writing-to-a-file-or-to-the-console%23new-answer', 'question_page');

            );

            Post as a guest






























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            2
            down vote













            According to the GoF, Strategy pattern:




            Define a family of algorithms, encapsulate each one, and make them
            interchangeable. Strategy lets the algorithm vary independently from
            the clients that use it.




            See that the objective is disacouplished client (context object) of your possibles behaviours. So there is two basics elements in this pattern: context object and strategies.



            The contexts objects have domain problems that must be separated from each other, so different algorithms. See in image(source in: https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm):



            UML diagram for Strategy Pattern



            All this allow that you can work to an interface without worrying implementation strategy.



            In your code there is no context object, so this is wrong. If there is no context object, the problem does not exist either.



            Refactoring your code, we will have the following strategies:



            // ----------------------------------------------
            // in strategies.go files
            // ----------------------------------------------

            type PrintStrategy interface
            Print() error


            type ConsoleStrategy struct
            func (c ConsoleStrategy) Print() error
            fmt.Println("Hello, playground by console strategy")
            return nil


            type FileStrategy struct DestinationFilePath string
            func (c FileStrategy) Print() error
            //print in file c.DestinationFilePath
            fmt.Println("Hello, playground by file strategy")
            return nil


            type DefaultStrategy struct
            func (c DefaultStrategy) Print() error
            //print in printer device
            fmt.Println("Hello, playground by default strategy")
            return nil



            And the following context object:



            // ----------------------------------------------
            // in context.go files
            // ----------------------------------------------
            type MyContextObject struct
            ps PrintStrategy


            func (m MyContextObject) Print()
            //check if PrintingStrategy is not nil
            err := m.ps.Print()
            if err != nil
            panic("Fail on PrintMyDatas")



            func NewMyContextObject(p PrintStrategy) MyContextObject
            if (p != nil)
            return MyContextObjectp
            else
            return MyContextObjectDefaultStrategy




            See that on instancing of MyContextObject an behaviour is passed. In your case the behaviour for this context is provided by argument passing on executing. In another case you might like change the behaviour in according with the content size. These are different context using same strategy.



            func main() 
            //read args
            strategy := flag.String("strategy", "console", "selected strategy")
            flag.Parse()

            //context object that needs to print your datas in according with
            //an user arg.
            var m MyContextObject

            //this statments can be replaced by factory method
            switch *strategy
            case "console":
            m = NewMyContextObject(ConsoleStrategy)
            case "file":
            m = NewMyContextObject(FileStrategy"bigciao")
            default:
            m = NewMyContextObject(nil)

            //
            m.Print()



            Now you can does more strategies or share this behaviour in other contexts.
            This is a good practical of reuse!!



            This code is in https://play.golang.org/p/P-kGGOwDDRt.



            I hope I helped you!






            share|improve this answer



























              up vote
              2
              down vote













              According to the GoF, Strategy pattern:




              Define a family of algorithms, encapsulate each one, and make them
              interchangeable. Strategy lets the algorithm vary independently from
              the clients that use it.




              See that the objective is disacouplished client (context object) of your possibles behaviours. So there is two basics elements in this pattern: context object and strategies.



              The contexts objects have domain problems that must be separated from each other, so different algorithms. See in image(source in: https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm):



              UML diagram for Strategy Pattern



              All this allow that you can work to an interface without worrying implementation strategy.



              In your code there is no context object, so this is wrong. If there is no context object, the problem does not exist either.



              Refactoring your code, we will have the following strategies:



              // ----------------------------------------------
              // in strategies.go files
              // ----------------------------------------------

              type PrintStrategy interface
              Print() error


              type ConsoleStrategy struct
              func (c ConsoleStrategy) Print() error
              fmt.Println("Hello, playground by console strategy")
              return nil


              type FileStrategy struct DestinationFilePath string
              func (c FileStrategy) Print() error
              //print in file c.DestinationFilePath
              fmt.Println("Hello, playground by file strategy")
              return nil


              type DefaultStrategy struct
              func (c DefaultStrategy) Print() error
              //print in printer device
              fmt.Println("Hello, playground by default strategy")
              return nil



              And the following context object:



              // ----------------------------------------------
              // in context.go files
              // ----------------------------------------------
              type MyContextObject struct
              ps PrintStrategy


              func (m MyContextObject) Print()
              //check if PrintingStrategy is not nil
              err := m.ps.Print()
              if err != nil
              panic("Fail on PrintMyDatas")



              func NewMyContextObject(p PrintStrategy) MyContextObject
              if (p != nil)
              return MyContextObjectp
              else
              return MyContextObjectDefaultStrategy




              See that on instancing of MyContextObject an behaviour is passed. In your case the behaviour for this context is provided by argument passing on executing. In another case you might like change the behaviour in according with the content size. These are different context using same strategy.



              func main() 
              //read args
              strategy := flag.String("strategy", "console", "selected strategy")
              flag.Parse()

              //context object that needs to print your datas in according with
              //an user arg.
              var m MyContextObject

              //this statments can be replaced by factory method
              switch *strategy
              case "console":
              m = NewMyContextObject(ConsoleStrategy)
              case "file":
              m = NewMyContextObject(FileStrategy"bigciao")
              default:
              m = NewMyContextObject(nil)

              //
              m.Print()



              Now you can does more strategies or share this behaviour in other contexts.
              This is a good practical of reuse!!



              This code is in https://play.golang.org/p/P-kGGOwDDRt.



              I hope I helped you!






              share|improve this answer

























                up vote
                2
                down vote










                up vote
                2
                down vote









                According to the GoF, Strategy pattern:




                Define a family of algorithms, encapsulate each one, and make them
                interchangeable. Strategy lets the algorithm vary independently from
                the clients that use it.




                See that the objective is disacouplished client (context object) of your possibles behaviours. So there is two basics elements in this pattern: context object and strategies.



                The contexts objects have domain problems that must be separated from each other, so different algorithms. See in image(source in: https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm):



                UML diagram for Strategy Pattern



                All this allow that you can work to an interface without worrying implementation strategy.



                In your code there is no context object, so this is wrong. If there is no context object, the problem does not exist either.



                Refactoring your code, we will have the following strategies:



                // ----------------------------------------------
                // in strategies.go files
                // ----------------------------------------------

                type PrintStrategy interface
                Print() error


                type ConsoleStrategy struct
                func (c ConsoleStrategy) Print() error
                fmt.Println("Hello, playground by console strategy")
                return nil


                type FileStrategy struct DestinationFilePath string
                func (c FileStrategy) Print() error
                //print in file c.DestinationFilePath
                fmt.Println("Hello, playground by file strategy")
                return nil


                type DefaultStrategy struct
                func (c DefaultStrategy) Print() error
                //print in printer device
                fmt.Println("Hello, playground by default strategy")
                return nil



                And the following context object:



                // ----------------------------------------------
                // in context.go files
                // ----------------------------------------------
                type MyContextObject struct
                ps PrintStrategy


                func (m MyContextObject) Print()
                //check if PrintingStrategy is not nil
                err := m.ps.Print()
                if err != nil
                panic("Fail on PrintMyDatas")



                func NewMyContextObject(p PrintStrategy) MyContextObject
                if (p != nil)
                return MyContextObjectp
                else
                return MyContextObjectDefaultStrategy




                See that on instancing of MyContextObject an behaviour is passed. In your case the behaviour for this context is provided by argument passing on executing. In another case you might like change the behaviour in according with the content size. These are different context using same strategy.



                func main() 
                //read args
                strategy := flag.String("strategy", "console", "selected strategy")
                flag.Parse()

                //context object that needs to print your datas in according with
                //an user arg.
                var m MyContextObject

                //this statments can be replaced by factory method
                switch *strategy
                case "console":
                m = NewMyContextObject(ConsoleStrategy)
                case "file":
                m = NewMyContextObject(FileStrategy"bigciao")
                default:
                m = NewMyContextObject(nil)

                //
                m.Print()



                Now you can does more strategies or share this behaviour in other contexts.
                This is a good practical of reuse!!



                This code is in https://play.golang.org/p/P-kGGOwDDRt.



                I hope I helped you!






                share|improve this answer















                According to the GoF, Strategy pattern:




                Define a family of algorithms, encapsulate each one, and make them
                interchangeable. Strategy lets the algorithm vary independently from
                the clients that use it.




                See that the objective is disacouplished client (context object) of your possibles behaviours. So there is two basics elements in this pattern: context object and strategies.



                The contexts objects have domain problems that must be separated from each other, so different algorithms. See in image(source in: https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm):



                UML diagram for Strategy Pattern



                All this allow that you can work to an interface without worrying implementation strategy.



                In your code there is no context object, so this is wrong. If there is no context object, the problem does not exist either.



                Refactoring your code, we will have the following strategies:



                // ----------------------------------------------
                // in strategies.go files
                // ----------------------------------------------

                type PrintStrategy interface
                Print() error


                type ConsoleStrategy struct
                func (c ConsoleStrategy) Print() error
                fmt.Println("Hello, playground by console strategy")
                return nil


                type FileStrategy struct DestinationFilePath string
                func (c FileStrategy) Print() error
                //print in file c.DestinationFilePath
                fmt.Println("Hello, playground by file strategy")
                return nil


                type DefaultStrategy struct
                func (c DefaultStrategy) Print() error
                //print in printer device
                fmt.Println("Hello, playground by default strategy")
                return nil



                And the following context object:



                // ----------------------------------------------
                // in context.go files
                // ----------------------------------------------
                type MyContextObject struct
                ps PrintStrategy


                func (m MyContextObject) Print()
                //check if PrintingStrategy is not nil
                err := m.ps.Print()
                if err != nil
                panic("Fail on PrintMyDatas")



                func NewMyContextObject(p PrintStrategy) MyContextObject
                if (p != nil)
                return MyContextObjectp
                else
                return MyContextObjectDefaultStrategy




                See that on instancing of MyContextObject an behaviour is passed. In your case the behaviour for this context is provided by argument passing on executing. In another case you might like change the behaviour in according with the content size. These are different context using same strategy.



                func main() 
                //read args
                strategy := flag.String("strategy", "console", "selected strategy")
                flag.Parse()

                //context object that needs to print your datas in according with
                //an user arg.
                var m MyContextObject

                //this statments can be replaced by factory method
                switch *strategy
                case "console":
                m = NewMyContextObject(ConsoleStrategy)
                case "file":
                m = NewMyContextObject(FileStrategy"bigciao")
                default:
                m = NewMyContextObject(nil)

                //
                m.Print()



                Now you can does more strategies or share this behaviour in other contexts.
                This is a good practical of reuse!!



                This code is in https://play.golang.org/p/P-kGGOwDDRt.



                I hope I helped you!







                share|improve this answer















                share|improve this answer



                share|improve this answer








                edited May 1 at 19:58


























                answered May 1 at 19:43









                Aristofanio Garcia

                1214




                1214






















                     

                    draft saved


                    draft discarded


























                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f193328%2fstrategy-design-pattern-for-writing-to-a-file-or-to-the-console%23new-answer', 'question_page');

                    );

                    Post as a guest













































































                    Popular posts from this blog

                    Greedy Best First Search implementation in Rust

                    Function to Return a JSON Like Objects Using VBA Collections and Arrays

                    C++11 CLH Lock Implementation