|
1 | 1 | package behavioral |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | +) |
| 6 | + |
| 7 | +// Machine defines a machine which can be swwitched on and off. |
| 8 | +type Machine struct { |
| 9 | + current State |
| 10 | +} |
| 11 | + |
| 12 | +// NewMachine creates a new machine. |
| 13 | +func NewMachine() *Machine { |
| 14 | + fmt.Fprintf(outputWriter, "Machine is ready.\n") |
| 15 | + return &Machine{NewOFF()} |
| 16 | +} |
| 17 | + |
| 18 | +// setCurrent sets the current state of the machine. |
| 19 | +func (m *Machine) setCurrent(s State) { |
| 20 | + m.current = s |
| 21 | +} |
| 22 | + |
| 23 | +// On pushes the on button. |
| 24 | +func (m *Machine) On() { |
| 25 | + m.current.On(m) |
| 26 | +} |
| 27 | + |
| 28 | +// Off pushes the off button. |
| 29 | +func (m *Machine) Off() { |
| 30 | + m.current.Off(m) |
| 31 | +} |
| 32 | + |
| 33 | +// State describes the internal state of the machine. |
| 34 | +type State interface { |
| 35 | + On(m *Machine) |
| 36 | + Off(m *Machine) |
| 37 | +} |
| 38 | + |
| 39 | +// ON describes the on button state. |
| 40 | +type ON struct { |
| 41 | +} |
| 42 | + |
| 43 | +// NewON creates a new ON state. |
| 44 | +func NewON() State { |
| 45 | + return &ON{} |
| 46 | +} |
| 47 | + |
| 48 | +// On does nothing. |
| 49 | +func (o *ON) On(m *Machine) { |
| 50 | + fmt.Fprintf(outputWriter, " already ON\n") |
| 51 | +} |
| 52 | + |
| 53 | +// Off switches the state from on to off. |
| 54 | +func (o *ON) Off(m *Machine) { |
| 55 | + fmt.Fprintf(outputWriter, " going from ON to OFF\n") |
| 56 | + m.setCurrent(NewOFF()) |
| 57 | +} |
| 58 | + |
| 59 | +// OFF describes the off button state. |
| 60 | +type OFF struct { |
| 61 | +} |
| 62 | + |
| 63 | +// NewOFF creates a new OFF state. |
| 64 | +func NewOFF() State { |
| 65 | + return &OFF{} |
| 66 | +} |
| 67 | + |
| 68 | +// On switches the state from off to on. |
| 69 | +func (o *OFF) On(m *Machine) { |
| 70 | + fmt.Fprintf(outputWriter, " going from OFF to ON\n") |
| 71 | + m.setCurrent(NewON()) |
| 72 | +} |
| 73 | + |
| 74 | +// Off does nothing. |
| 75 | +func (o *OFF) Off(m *Machine) { |
| 76 | + fmt.Fprintf(outputWriter, " already OFF\n") |
| 77 | +} |
0 commit comments