From 4595241f77481bdb10014e96b3d5258d963cf264 Mon Sep 17 00:00:00 2001 From: Tamer Tas Date: Tue, 21 Feb 2017 11:30:21 +0300 Subject: [PATCH] creational/factory: implement factory method pattern --- README.md | 2 +- creational/factory.md | 58 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 creational/factory.md diff --git a/README.md b/README.md index bbde453..c9fa11e 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ A curated collection of idiomatic design & application patterns for Go language. |:-------:|:----------- |:------:| | [Abstract Factory](/creational/abstract_factory.md) | Provides an interface for creating families of releated objects | ✘ | | [Builder](/creational/builder.md) | Builds a complex object using simple objects | ✘ | -| [Factory Method](/creational/factory.md) | Defers instantiation of an object to a specialized function for creating instances | ✘ | +| [Factory Method](/creational/factory.md) | Defers instantiation of an object to a specialized function for creating instances | ✔ | | [Object Pool](/creational/object-pool.md) | Instantiates and maintains a group of objects instances of the same type | ✔ | | [Singleton](/creational/singleton.md) | Restricts instantiation of a type to one object | ✔ | diff --git a/creational/factory.md b/creational/factory.md new file mode 100644 index 0000000..8d80a1f --- /dev/null +++ b/creational/factory.md @@ -0,0 +1,58 @@ +# Factory Method Pattern + +Factory method creational design pattern allows creating objects without having +to specify the exact type of the object that will be created. + +## Implementation + +The example implementation shows how to provide a data store with different +backends such as in-memory, disk storage. + +### Types + +```go +package data + +import "io" + +type Store interface { + Open(string) (io.ReadWriteCloser, error) +} +``` + +### Different Implementations + +```go +package data + +type StorageType int + +const ( + DiskStorage StorageType = 1 << iota + TempStorage + MemoryStorage +) + +func NewStore(t StorageType) Store { + switch t { + case MemoryStorage: + return newMemoryStorage( /*...*/ ) + case DiskStorage: + return newDiskStorage( /*...*/ ) + default: + return newTempStorage( /*...*/ ) + } +} +``` + +## Usage + +With the factory method, the user can specify the type of storage they want. + +```go +s, _ := data.NewStore(data.MemoryStorage) +f, _ := s.Open("file") + +n, _ := f.Write([]byte("data")) +defer f.Close() +```