From 82090ab82704b3ca3c2eda208f9c3624155223a8 Mon Sep 17 00:00:00 2001 From: ismayilmalik Date: Tue, 2 Jan 2018 22:08:52 +0300 Subject: [PATCH] implemented factory pattern --- creational/factory/factory.go | 42 ++++++++++++++++++++++++++++++ creational/factory/factory_test.go | 42 ++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 creational/factory/factory.go create mode 100644 creational/factory/factory_test.go diff --git a/creational/factory/factory.go b/creational/factory/factory.go new file mode 100644 index 0000000..445f751 --- /dev/null +++ b/creational/factory/factory.go @@ -0,0 +1,42 @@ +package factory + +import ( + "errors" + "fmt" +) + +const ( + SMS = 1 + Email = 2 +) + +type Notification struct { + To string + Message string +} + +type Notifier interface { + SendNotification(Notification) string +} + +type SMSNotification struct{} +func (n SMSNotification) SendNotification(notification Notification) string { + return fmt.Sprintf("`%s` was sent to number `%s` successfully!", notification.Message, notification.To) +} + +type EmailNotification struct{} +func (n EmailNotification) SendNotification(notification Notification) string { + return fmt.Sprintf("`%s` was sent to email `%s` successfully!", notification.Message, notification.To) +} + +// Factory ..... +func GetNotifier(notifierType int) (Notifier, error) { + switch notifierType { + case SMS: + return new(SMSNotification), nil + case Email: + return new(EmailNotification), nil + default: + return nil, errors.New(fmt.Sprintf("Notifier type %d not recognized.", notifierType)) + } +} diff --git a/creational/factory/factory_test.go b/creational/factory/factory_test.go new file mode 100644 index 0000000..4abe542 --- /dev/null +++ b/creational/factory/factory_test.go @@ -0,0 +1,42 @@ +package factory + +import ( + "strings" + "testing" +) + +func TestGetSMSNotifier(t *testing.T) { + notification := Notification{"5552233", "Hello world!"} + notifier, err := GetNotifier(SMS) + + if err != nil { + t.Fatal("Notifier type 'SMS' must be returned") + } + + resultStr := notifier.SendNotification(notification) + if !strings.Contains(resultStr, "was sent to number") { + t.Error("SMS notifier result message was not correct.") + } +} + +func TestGetEmailNotifier(t *testing.T) { + notification := Notification{"5552233", "Hello world!"} + notifier, err := GetNotifier(Email) + + if err != nil { + t.Fatal("Notifier type 'Email' must be returned") + } + + resultStr := notifier.SendNotification(notification) + if !strings.Contains(resultStr, "was sent to email") { + t.Error("Email notifier result message was not correct.") + } +} + +func TestGetNonExistanceNotifier(t *testing.T) { + _, err := GetNotifier(3) + + if err == nil { + t.Fatal("Error must be returned for unrecognized notifier type.") + } +} \ No newline at end of file