B/O - State
- Category: behavioral
- Type: object
- Motivation: change the behavior of a class when the state changes
- implements a state machine in an object-oriented way
- invoke the method in state object
do {
let editor = Editor()
editor.type("hello WORLD")
editor.state = Upppercase()
editor.type("hello world")
editor.state = Lowercase()
editor.type("hello world")
}
class Editor
{
var state: Writing = Default()
func type(_ words: String)
{
state.write(words)
}
}
protocol Writing
{
func write(_ words: String)
}
class Default: Writing
{
func write(_ words: String)
{
print(words)
}
}
class Upppercase: Writing
{
func write(_ words: String)
{
print(words.uppercased())
}
}
class Lowercase: Writing
{
func write(_ words: String)
{
print(words.lowercased())
}
}