ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 상태패턴과 전략패턴의 차이는 무엇일까?
    Kotlin 2023. 10. 17. 00:01
    728x90

    상태패턴이란?

    // State interface
    interface LightState {
        fun turnOn(light: FluorescentLight)
        fun turnOff(light: FluorescentLight)
    }
    
    // Concrete state classes
    class OnState : LightState {
        override fun turnOn(light: FluorescentLight) {
            println("The light is already on.")
        }
    
        override fun turnOff(light: FluorescentLight) {
            println("Turning off the light.")
            light.lightState = OffState()
        }
    }
    
    class OffState : LightState {
        override fun turnOn(light: FluorescentLight) {
            println("Turning on the light.")
            light.lightState = OnState()
        }
    
        override fun turnOff(light: FluorescentLight) {
            println("The light is already off.")
        }
    }
    
    // FluorescentLight class
    class FluorescentLight(var lightState: LightState) {
    
        fun turnOn() {
            lightState.turnOn(this)
        }
    
        fun turnOff() {
            lightState.turnOff(this)
        }
    }
    
    fun main() {
        val initialLightState = OffState()
        val fluorescentLight = FluorescentLight(initialLightState)
    
        // Scenario: Off, On, Off
        fluorescentLight.turnOff()
        fluorescentLight.turnOn()
        fluorescentLight.turnOff()
    
        // Try to turn on again while already on (will print "The light is already on.")
        fluorescentLight.turnOn()
    
        // Try to turn off again while already off (will print "The light is already off.")
        fluorescentLight.turnOff()
    }

    형광등이라는 인스턴스를 생성했다고 가정하겠습니다.

    형광등의 OFF인 상태에서 스위치를 ON 하면 불이 켜질 것입니다.

    그렇지만 ON인 상태에서 스위치를 ON하면 이미 불이 켜진 상태라 아무런 동작을 하지 않을 것입니다.

    형광등의 상태는 ON인 상태에서나 OFF인 상태에서 각각 다르게 처리돼야 한다.

    즉, 하나의 인스턴스가 여러 행동을 수행할 수 있고, 이런 행동이 상태를 바꾸는 경우에 사용합니다.

     

    전략패턴이란?

    // Strategy interface
    interface DrawingStrategy {
        fun draw()
    }
    
    // Concrete drawing strategy classes
    class BrushStrategy : DrawingStrategy {
        override fun draw() {
            println("Using a brush to paint with broad strokes.")
        }
    }
    
    class PencilStrategy : DrawingStrategy {
        override fun draw() {
            println("Using a pencil to draw with fine lines.")
        }
    }
    
    class HighlighterStrategy : DrawingStrategy {
        override fun draw() {
            println("Using a highlighter to emphasize text or shapes.")
        }
    }
    
    // Context class that uses the selected drawing strategy
    class DrawingContext(private val drawingStrategy: DrawingStrategy) {
        fun drawPicture() {
            println("Drawing a picture:")
            drawingStrategy.draw()
            println("Picture drawing completed.")
        }
    }
    
    fun main() {
        val brush = BrushStrategy()
        val pencil = PencilStrategy()
        val highlighter = HighlighterStrategy()
    
        val canvas1 = DrawingContext(brush)
        val canvas2 = DrawingContext(pencil)
        val canvas3 = DrawingContext(highlighter)
    
        canvas1.drawPicture()
        canvas2.drawPicture()
        canvas3.drawPicture()
    }

    도구 모움을 갖고 작업을 수행하는데 사용하는 도구를 선택하는 것과 같습니다.

    예를 들어 그림을 그리는 다양한 도구 (붓, 연필, 형광펜)등이 있을 때 사용하고 싶은 도구를 선택하여 그릴 수 있습니다.

    도구의 선택은 도구의 상태를 바꾸지는 않으며 그림의 모양에 영향을 미칩니다.

     

    둘의 차이점

    상태 패턴과 전략패턴은 둘 다 인터페이스와 클래스를 활용하여 하나의 인스턴스가 상태를 변경하거나 전략을 변경하여 유연한 코드를 제공합니다.

     

    둘의 가장 큰 차이로는 내부적으로 상태가 변하는가 변하지 않는가입니다.

    상태 패턴에서는 하나의 객체가 상태에 따라 내부적으로 상태를 변경합니다.

    전략 패턴은 작업을 수행하기 위해 다양한 전략을 선택하지만 객체 내부 상태는 동일하게 유지합니다.

    'Kotlin' 카테고리의 다른 글

    Kotlin Value Class란?  (0) 2023.09.01
    Mapstrcut 변환시 함수 호출하기  (0) 2023.05.22
    Kotlin으로 Jwt 개발하기  (0) 2023.05.14

    댓글

Designed by Tistory.