From 8f5f035a6fe13e93aa7f8c4ef7a485a778ed40a7 Mon Sep 17 00:00:00 2001 From: ismayilmalik Date: Tue, 2 Jan 2018 17:19:50 +0300 Subject: [PATCH] implemented strategy pattern --- README.md | 6 +++++ behavioral/strategy/strategy.go | 34 ++++++++++++++++++++++++++++ behavioral/strategy/strategy_test.go | 0 3 files changed, 40 insertions(+) create mode 100644 behavioral/strategy/strategy.go create mode 100644 behavioral/strategy/strategy_test.go diff --git a/README.md b/README.md index bf504e3..4823f9b 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ - [Composition](#composition) - [Behavioral patterns](#behavioral-patterns) - [Chain of responsibility](#chain-of-responsibility) + - [Strategy](#strategy) - [Concurrency patterns](#concurrency-patterns) --- @@ -44,10 +45,15 @@ between objects. Behavio ral patterns describe not just patterns of objects or c but also the patterns of communication between them. These patterns characterize complex control flow that's difficult to follow at run-time. They shift your focus away from flow of control to let you concent ratejust on the way objects are interconnected. + ### Chain of responsibility Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. +### Strategy +Define a family oafl gorit h ms, encapsulate each one, and make them interchangeable. +Strategy lets the algorithm vary independently from clients that use it. + ## Concurrency patterns Pattenrs for concurrent work and parallel execution in Go. diff --git a/behavioral/strategy/strategy.go b/behavioral/strategy/strategy.go new file mode 100644 index 0000000..20c354c --- /dev/null +++ b/behavioral/strategy/strategy.go @@ -0,0 +1,34 @@ +package strategy + +import ( + "fmt" +) + +// Abstraction +type LoggerStrategy interface { + Write(string) error +} + +// Strategy 1 +type FileLogger struct {} +func (l FileLogger) Write(data string) error { + fmt.Println("Writed to file...") + return nil +} + +// Strategy 2 +type DbLogger struct {} +func (l DbLogger) Write(data string) error { + fmt.Println("Writed to db..") +} + +// Consumer +type Logger struct{ + logger LoggerStrategy +} + +func (l *Logger) Log(data string) error { + l.logger.Write(data) +} + + diff --git a/behavioral/strategy/strategy_test.go b/behavioral/strategy/strategy_test.go new file mode 100644 index 0000000..e69de29