forked from AlexanderGrom/go-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
strategy.go
64 lines (56 loc) · 1.14 KB
/
strategy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Package strategy is an example of the Strategy Pattern.
package strategy
// StrategySort provides an interface for sort algorithms.
type StrategySort interface {
Sort([]int)
}
// BubbleSort implements bubble sort algorithm.
type BubbleSort struct {
}
// Sort sorts data.
func (s *BubbleSort) Sort(a []int) {
size := len(a)
if size < 2 {
return
}
for i := 0; i < size; i++ {
for j := size - 1; j >= i+1; j-- {
if a[j] < a[j-1] {
a[j], a[j-1] = a[j-1], a[j]
}
}
}
}
// InsertionSort implements insertion sort algorithm.
type InsertionSort struct {
}
// Sort sorts data.
func (s *InsertionSort) Sort(a []int) {
size := len(a)
if size < 2 {
return
}
for i := 1; i < size; i++ {
var j int
var buff = a[i]
for j = i - 1; j >= 0; j-- {
if a[j] < buff {
break
}
a[j+1] = a[j]
}
a[j+1] = buff
}
}
// Context provides a context for execution of a strategy.
type Context struct {
strategy StrategySort
}
// Algorithm replaces strategies.
func (c *Context) Algorithm(a StrategySort) {
c.strategy = a
}
// Sort sorts data according to the chosen strategy.
func (c *Context) Sort(s []int) {
c.strategy.Sort(s)
}