From 0cb101cb12156d01386c1f06db4ca2eeec9e89e0 Mon Sep 17 00:00:00 2001 From: ismayilmalik Date: Wed, 3 Jan 2018 23:35:09 +0300 Subject: [PATCH] implemented adapter pattern --- README.md | 5 ++++ structural/adapter/adapter.go | 51 +++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 structural/adapter/adapter.go diff --git a/README.md b/README.md index 5d902c6..83312ad 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ - [Abstract Factory](#abstract-factory) - [Structural patterns](#structural-patterns) - [Composition](#composition) + - [Adapter](#adapter) - [Behavioral patterns](#behavioral-patterns) - [Chain of responsibility](#chain-of-responsibility) - [Strategy](#strategy) @@ -49,6 +50,10 @@ more classes into one. Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. +### Adapter +Convert the interfac e of a class into another interface clients expect. Adapter lets +classes work together that couldn' t otherwise because of incompatible interfaces. + ## Behavioral patterns Behavioral patterns are concerned with algorithms and the assignment of responsibilities between objects. Behavio ral patterns describe not just patterns of objects or classes diff --git a/structural/adapter/adapter.go b/structural/adapter/adapter.go new file mode 100644 index 0000000..3a7f085 --- /dev/null +++ b/structural/adapter/adapter.go @@ -0,0 +1,51 @@ +package adapter + +//old bad service which we can't chane +type OldEmailSender interface { + Send(from, to, subject, body string) error +} + +type OldEmailSvc struct{} + +func (s OldEmailSvc) Send(from, to, subject, body string) error { + //Send email... + return nil +} + +//new service ehich has state +//we have client only supports this interface +type NewEmailSender interface { + Send() error +} + +type NewEmailService struct { + From, To, Subject, Body string +} + +func (s NewEmailService) Send() error { + //state already initialized just send + return nil +} + +//adapter for old email service +type OldEmailServiceAdapter struct { + From, To, Subject, Body string + OldEmailService OldEmailSender +} + +func (a OldEmailServiceAdapter) Send() error { + return a.OldEmailService.Send(a.From, a.To, a.Subject, a.Body) +} + +/* + client which only supports new email service interface + EmailClient{ Mail: OldEmailServiceAdapter{...}} old service + EmailClient{ Mail: NewEmailService{...}} new service +*/ +type EmailClient struct { + Mail NewEmailSender +} + +func (e EmailClient) SendEmail(From, To, Subject, Body string) error { + return e.Mail.Send() +}