[GO] [Gang of Four] Design pattern learning --Strategy

Strategy --Strategy

** Table of Contents ** There is no way to express it other than what is written for the purpose, but to put it in more detail, it is like abstracting the parts that can be shared by the algorithm and implementing the behavior in a concrete class.

Purpose

Define a set of algorithms, encapsulate each algorithm and make them interchangeable. The Strategy pattern allows the algorithm to be modified independently of the clients that use it.

Component

・ Strategy Abstract class of common part ・ ConcreateStrategy Concrete class of common part ・ Context algorithm part

Implementation

Let's implement bubble sort and shaker sort, which are algorithms for sorting arrays.

Strategy Common part abstract class

Sort.kt


package strategy

interface Sort {
    fun swap(index: Int)
    fun outOfOrder(index: Int): Boolean
    fun length(): Int
    fun setArray(array: Any)
}

ConcreateStrategy Concrete class of common parts

For Int type arrays.

IntSort.kt


package strategy

class IntSort: Sort {
    private lateinit var array: Array<Int>

    override fun swap(index: Int) {
        val temp = array[index]
        array[index] = array[index + 1]
        array[index + 1] = temp
    }

    override fun outOfOrder(index: Int): Boolean {
        return array[index] > array[index + 1]
    }

    override fun length(): Int {
        return array.size
    }

    override fun setArray(array: Any) {
        this.array = array as Array<Int>
    }
}

Context algorithm part

Implement from bubble sort.

BubbleSort.kt


package strategy

class BubbleSort(private val sort: Sort) {
    private var operations = 0
    private var length = 0

    fun sort(array: Any): Int {
        sort.setArray(array)
        length = sort.length()
        operations = 0

        if (length <= 1) {
            return operations
        }

        for (nextToLast in length - 2 downTo 0) {
            for (index in 0..nextToLast) {
                if (sort.outOfOrder(index)) {
                    sort.swap(index)
                }
                operations++
            }
        }

        return operations
    }
}

Next is shaker sort

ShakerSort.kt


package strategy

class ShakerSort(private val sort: Sort) {

    fun sort(array: Any): Int {
        sort.setArray(array)
        var length = sort.length()
        var operations = 0

        if (length <= 1) {
            return operations
        }

        var thisPassInOrder = false

        loop@ for (nextToLast in length - 2 downTo 0) {
            if (thisPassInOrder) {
                break@loop
            }

            thisPassInOrder = true
            for (index in 0..nextToLast) {
                if (sort.outOfOrder(index)) {
                    sort.swap(index)
                    thisPassInOrder = false
                }
                operations++
            }
        }
        return operations
    }
}

Let's sort it now.

People who use

Client.kt


package strategy

class Client {
    init {
        val array1 = arrayOf(22,533,43212,1,567,7,22,2,35,9913)
        val array2 = arrayOf(25,77,834534,32,11,3,880)

        val intSort = IntSort()

        //Bubble sort
        BubbleSort(intSort).sort(array1)

        println("Bubble sort result")
        array1.forEach {
            println("$it")
        }

        //Shaker sort
        ShakerSort(intSort).sort(array2)

        println("Shaker sort result")
        array2.forEach {
            println("$it")
        }
    }
}
[out-put]
Bubble sort result
1
2
7
22
22
35
533
567
9913
43212
Shaker sort result
3
11
25
32
77
880
834534

It is a pattern that enables flexible implementation by code that conforms to DIP.

Create not only an Int type array, but also a `DoubleSort``` that implements the ``` Sort interface `, for example. I just change the type of the array set by the setArray method ...

DoubleSort.kt


package strategy

class DoubleSort: Sort {
    private lateinit var array: Array<Double>

    override fun swap(index: Int) {
        val temp = array[index]
        array[index] = array[index + 1]
        array[index + 1] = temp
    }

    override fun outOfOrder(index: Int): Boolean {
        return array[index] > array[index + 1]
    }

    override fun length(): Int {
        return array.size
    }

    override fun setArray(array: Any) {
        this.array = array as Array<Double>
    }
}

Client.kt


package strategy

class Client {
    init {
        val array1 = arrayOf(33.5, 5.4, 5.0, 225.4, 225.3)
        val array2 = arrayOf(10.4, 10.2, 10.5, 10.1, 10.3, 10.6)

        val doubleSort = DoubleSort()

        //Bubble sort
        BubbleSort(doubleSort).sort(array1)

        println("Bubble sort result")
        array1.forEach {
            println("$it")
        }

        //Shaker sort
        ShakerSort(doubleSort).sort(array2)

        println("Shaker sort result")
        array2.forEach {
            println("$it")
        }
    }
}

Output result

[out-put]
Bubble sort result
5.0
5.4
33.5
225.3
225.4
Shaker sort result
10.1
10.2
10.3
10.4
10.5
10.6

Factory Method It looks like a pattern that goes very well with the pattern. intsortOrdoublesortIf the factory method class generates the class, it seems that a very convenient module can be created.

that's all

Recommended Posts

[Gang of Four] Design pattern learning --Strategy
[Gang of Four] Design pattern learning
[Gang of Four] Design pattern learning --Singleton
[Gang of Four] Design Pattern Learning --Decorator
[Gang of Four] Design pattern learning --Visitor
[Gang of Four] Design pattern learning --Mediator
[Gang of Four] Design pattern learning --Iterator
[Gang of Four] Design pattern learning --Facade
[Gang of Four] Design pattern learning --Composite
[Gang of Four] Design pattern learning --Prototype
[Gang of Four] Design pattern learning --Memento
[Gang of Four] Design pattern learning --State
[Gang of Four] Design pattern learning --Interpreter
[Gang of Four] Design pattern learning --Builder
[Gang of Four] Design pattern learning --Bridge
[Gang of Four] Design pattern learning --Proxy
[Gang of Four] Design pattern learning --Adapter
[Gang of Four] Design pattern learning --Observer
[Gang of Four] Design pattern learning --Command
[Gang of Four] Design pattern learning --Fly Weight
[Gang of Four] Design pattern learning --Abstract Factory
[Gang of Four] Design pattern learning --Factory Method
[Gang of Four] Design pattern learning --Chain of Responsibility
[Gang of Four] Design pattern learning --Template Method
Design Pattern #Strategy
Gang of Four (GoF) Patterns in Python
Learn the design pattern "Strategy" in Python
Design Pattern #Adapter
Design Pattern #Decorator
Pattern recognition learning in video Part 1 Field of Pattern Recognition
Design Pattern #Template Method
Template Method pattern in Java
Python Design Pattern --Template method
Design Pattern #Factory Method
Learn the design pattern "Template Method" in Python
[Gang of Four] Design pattern learning --Template Method
template
Design Pattern #Observer
Design Pattern #Facade
Design Pattern #Singleton
Learn the design pattern "Chain of Responsibility" in Python
Design Pattern #Factory Method
Deep learning 1 Practice of deep learning
Design Pattern #Template Method
GoF design pattern is just an "introduction of abstraction layer"