[kotlin] 명령 디자인 패턴과 코틀린
디자인 패턴은 소프트웨어 개발에서 자주 사용되는 효율적인 해결책을 제시합니다. 명령(Command) 디자인 패턴은 특히 다양한 작업을 수행하는 객체들의 행위를 캡슐화하고, 이를 객체로 만들어서 다양한 요청을 처리할 때 유용합니다.
명령 디자인 패턴이란?
명령(Command) 디자인 패턴은 요청을 객체로 캡슐화하여 매개변수화하고, 사용자가 보내는 각각의 요청을 객체로 변환하는 패턴입니다. 이로써 요청을 큐에 쌓거나 로그로 기록하거나 역순으로 실행할 수 있으며, 이동식 요청을 지원하고 실패에 대비할 수 있습니다.
코틀린에서의 명령 디자인 패턴
코틀린은 자바와 호환되는 객체지향 언어로, 명령 디자인 패턴을 쉽게 구현할 수 있습니다. 아래는 간단한 예시입니다.
interface Command {
fun execute()
}
class Light {
fun turnOn() {
println("Light is on")
}
fun turnOff() {
println("Light is off")
}
}
class TurnOnCommand(private val light: Light) : Command {
override fun execute() {
light.turnOn()
}
}
class TurnOffCommand(private val light: Light) : Command {
override fun execute() {
light.turnOff()
}
}
class RemoteControl {
private var command: Command? = null
fun setCommand(cmd: Command) {
command = cmd
}
fun pressButton() {
command?.execute()
}
}
fun main() {
val light = Light()
val remote = RemoteControl()
val turnOn = TurnOnCommand(light)
val turnOff = TurnOffCommand(light)
remote.setCommand(turnOn)
remote.pressButton() // Output: Light is on
remote.setCommand(turnOff)
remote.pressButton() // Output: Light is off
}
위의 예시에서는 Light
클래스를 켜고 끄는 기능을 TurnOnCommand
와 TurnOffCommand
로 캡슐화하였습니다. RemoteControl
클래스를 통해 이들 명령을 실행할 수 있습니다.
명령 디자인 패턴을 활용하면 새로운 명령을 간단히 추가하는 것이 가능해지며, 기존의 코드를 변경하지 않고 유연성을 높일 수 있습니다. 이로써 유지보수성이 개선되고 확장성이 높은 소프트웨어를 개발할 수 있습니다.
결론
명령 디자인 패턴은 객체지향 소프트웨어 개발에서 유용한 패턴 중 하나입니다. 코틀린은 명령 디자인 패턴을 효율적으로 구현할 수 있으며, 이를 통해 유연하고 확장성 있는 코드를 작성할 수 있습니다.
참고 문헌:
- Gamble, C., Meszaros, G. (1998). Pattern Languages of Program Design 3. Addison-Wesley.