diff --git a/README.md b/README.md index 00448df..8b694da 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ __Creational Patterns__: | [Builder](builder/builder.go) | Builds a complex object using simple objects | | [Factory Method](factory_method.go) | Defers instantiation of an object to a specialized function for creating instances | | [Object Pool](object_pool/pool.go) | Instantiates and maintains a group of objects instances of the same type | -| [Singleton](singleton/singleton.go) | Restricts instantiation of a class to one object | +| [Singleton](creational/singleton.md) | Restricts instantiation of a type to one object | __Structural Patterns__: @@ -29,7 +29,7 @@ __Structural Patterns__: | [Bridge](bridge.go) | Decouples an interface from its implementation so that the two can vary independently | | [Composite](composite.go) | Encapsulates and provides access to a number of different objects | | [Decorator](structural/decorator.md) | Adds behavior to an object, statically or dynamically | -| [Facade](facade.go) | Uses one class as an API to a number of others | +| [Facade](facade.go) | Uses one type as an API to a number of others | | [Flyweight](flyweight.go) | Reuses existing instances of objects with similar/identical state to minimize resource usage | | [Model View Controller](mvc.go) | Divides an app into three interconnected parts to separate internal representation from presentation to user | | [Proxy](proxy.go) | Provides a surrogate for an object to control it's actions | diff --git a/creational/singleton.md b/creational/singleton.md new file mode 100644 index 0000000..0c0c54d --- /dev/null +++ b/creational/singleton.md @@ -0,0 +1,35 @@ +#Singleton Pattern +Singleton creational design pattern restricts the instantiation of a type to a single object. + +## Implementation +```go +package singleton + +type singleton map[string]string + +var once sync.Once + +var instance *singleton + +func New() *singleton { + once.Do(func() { + instance = make(singleton) + }) + + return instance +} +``` + +## Usage +```go +s := singleton.New() + +s["this"] = "that" + +s2 := singleton.New() + +// s2["this"] == "that" +``` + +## Rules of Thumb +- Singleton pattern represents a global state and most of the time reduces testability. diff --git a/singleton/singleton.go b/singleton/singleton.go deleted file mode 100644 index d85a4a6..0000000 --- a/singleton/singleton.go +++ /dev/null @@ -1,20 +0,0 @@ -package singleton - -import ( - "sync" -) - -type Object struct { -} - -var once sync.Once -var instance *Object - -func GetInstance() *Object { - // Creates a singleton instance once. - once.Do(func() { - instance = &singleton{} - }) - - return instance -}