[swift] State 디자인 패턴

State design pattern is a behavioral design pattern that allows an object to alter its behavior when its internal state changes. This pattern is useful when an object needs to change its behavior dynamically based on its state.

In Swift, we can implement the state design pattern using a combination of protocols and classes.

Anatomy of State Design Pattern

The State pattern consists of several key components:

Example Implementation

Let’s say we have a TCPConnection class that can be in one of two states: Connected or Disconnected. We can implement the state pattern as follows:

// State protocol
protocol ConnectionState {
    func connect()
    func disconnect()
}

// Concrete Connected State
class ConnectedState: ConnectionState {
    func connect() {
        print("Already connected")
    }
    
    func disconnect() {
        print("Disconnecting...")
        // Transition to disconnected state
        tcpConnection.state = DisconnectedState()
    }
}

// Concrete Disconnected State
class DisconnectedState: ConnectionState {
    func connect() {
        print("Connecting...")
        // Transition to connected state
        tcpConnection.state = ConnectedState()
    }
    
    func disconnect() {
        print("Already disconnected")
    }
}

// Context class
class TCPConnection {
    var state: ConnectionState
    
    init() {
        state = DisconnectedState()
    }
    
    func connect() {
        state.connect()
    }
    
    func disconnect() {
        state.disconnect()
    }
}

In this example, the TCPConnection class acts as the context, while the ConnectedState and DisconnectedState classes act as concrete states that implement the behavior for the connected and disconnected states, respectively.

Benefits of State Design Pattern

State design pattern is a powerful tool for modeling state-based behavior in an object-oriented system, and it can lead to more clean and maintainable code.

References