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 State pattern

Implement a State pattern

- [Instructor] Now we're going to walk through an example of building the state pattern in Go using shapes. I've already written our state interface and concrete state classes but together we'll write our context and see how it comes together in our main function. Our shape state interface will have two functions, draw shape, and erase shape. Our concrete classes implement the state interface. In this example, we'll have our circle state and our rectangular state. So you'll see the circle state has draw shape and erase shape. And our rectangle state has draw shape and erase shape. Now we're going to build our context which is the shape struct which will pass in our shape state object. We want to build our setters and headers that will set the state as well as get the state. First, we'll build set state which will pass in this shape state object. It'll say s.state is equal to state. And then we'll have our getter…

Contents