Skip to content

Commit 51e0aeb

Browse files
committed
Refactor strategy pattern
1 parent 3885b01 commit 51e0aeb

File tree

4 files changed

+56
-44
lines changed

4 files changed

+56
-44
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ __Behavioral Patterns__:
4545
| [Observer](observer.go) | Provide a callback for notification of events/changes to data |
4646
| [Registry](registry.go) | Keep track of all subclasses of a given class |
4747
| [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 |
4949
| [Template](template.go) | Defines a skeleton class which defers some methods to subclasses |
5050
| [Visitor](visitor.go) | Separates an algorithm from an object on which it operates |
5151

behavioral/strategy.md

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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.

strategy/strategy.go

-25
This file was deleted.

strategy/strategy_test.go

-18
This file was deleted.

0 commit comments

Comments
 (0)