File tree 4 files changed +56
-44
lines changed
4 files changed +56
-44
lines changed Original file line number Diff line number Diff line change @@ -45,7 +45,7 @@ __Behavioral Patterns__:
45
45
| [ Observer] ( observer.go ) | Provide a callback for notification of events/changes to data |
46
46
| [ Registry] ( registry.go ) | Keep track of all subclasses of a given class |
47
47
| [ State] ( state.go ) | Encapsulates varying behavior for the same object based on its internal state |
48
- | [ Strategy] ( strategy /strategy.go ) | Enables an algorithm's behavior to be selected at runtime |
48
+ | [ Strategy] ( behavioral /strategy.md ) | Enables an algorithm's behavior to be selected at runtime |
49
49
| [ Template] ( template.go ) | Defines a skeleton class which defers some methods to subclasses |
50
50
| [ Visitor] ( visitor.go ) | Separates an algorithm from an object on which it operates |
51
51
Original file line number Diff line number Diff line change
1
+ #Strategy Pattern
2
+ Strategy behavioral design pattern enables an algorithm's behavior to be selected at runtime.
3
+
4
+ It defines algorithms, encapsulates them, and uses them interchangeably.
5
+
6
+ ## Implementation
7
+ Implementation of an interchangeable operator object that operates on integers.
8
+
9
+ ``` go
10
+ type Operator interface {
11
+ Apply (int , int ) int
12
+ }
13
+
14
+ type Operation struct {
15
+ Operator Operator
16
+ }
17
+
18
+ func (o *Operation ) Operate (leftValue , rightValue int ) int {
19
+ return o.Operator .Apply (leftValue, rightValue)
20
+ }
21
+ ```
22
+
23
+ ## Usage
24
+ ### Addition Operator
25
+ ``` go
26
+ type Addition struct {}
27
+
28
+ func (Addition ) Apply (lval , rval int ) int {
29
+ return lval + rval
30
+ }
31
+ ```
32
+
33
+ ``` go
34
+ add := Operation {Addition{}}
35
+ add.Operate (3 , 5 ) // 8
36
+ ```
37
+
38
+ ### Multiplication Operator
39
+ ``` go
40
+ type Multiplication struct {}
41
+
42
+ func (Multiplication ) Apply (lval , rval int ) int {
43
+ return lval * rval
44
+ }
45
+ ```
46
+
47
+ ``` go
48
+ mult := Operation {Multiplication{}}
49
+
50
+ mult.Operate (3 , 5 ) // 15
51
+ ```
52
+
53
+ ## Rules of Thumb
54
+ - Strategy pattern is similar to Template pattern except in its granularity.
55
+ - Strategy pattern lets you change the guts of an object. Decorator pattern lets you change the skin.
Load Diff This file was deleted.
Load Diff This file was deleted.
You can’t perform that action at this time.
0 commit comments