From the course: Design Patterns in Go for Object Oriented Programming

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Implement a Strategy pattern

Implement a Strategy pattern

- [Instructor] Now we'll be implementing the strategy pattern in go using animals. I've already pre-written our strategy classes, but together we'll write our main function to see how it all comes together. Our animal interface declares a method, makes sound which returns a string. Our cat and our dog structs implement the animal interface. And for our cat, we return meow. And for our dog, we return woof. Our strategy interface contains the execute method which will return a string. We have our concrete strategy A which is our speak strategy and it overrides the execute method by calling make sound from the animal object. That gets passed in as a parameter. Our concrete strategy B is our bark strategy and our execute method that gets overwritten returns s.animal.MakeSound. Our context passes in a strategy as a parameter and our method execute strategy will also execute the strategy that gets passed in as a parameter.…

Contents