1
0
mirror of https://github.com/tmrts/go-patterns.git synced 2024-11-22 13:06:09 +03:00

add abstract factory

This commit is contained in:
alexpantyukhin 2017-09-01 12:48:46 +04:00
parent f978e42036
commit 9947015ae1
2 changed files with 67 additions and 1 deletions

View File

@ -15,7 +15,7 @@ A curated collection of idiomatic design & application patterns for Go language.
| Pattern | Description | Status | | Pattern | Description | Status |
|:-------:|:----------- |:------:| |:-------:|:----------- |:------:|
| [Abstract Factory](/creational/abstract_factory.md) | Provides an interface for creating families of releated objects | | | [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 | ✔ | | [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 | ✔ | | [Object Pool](/creational/object-pool.md) | Instantiates and maintains a group of objects instances of the same type | ✔ |

View File

@ -0,0 +1,66 @@
# Abstract Factory Pattern
Abstract Factory creational design pattern provides an interface for
creating families of related or dependent objects without specifying
their concrete classes.
## Implementation
```go
package afactory
import "fmt"
// Coin hierarchy
type Coin interface {
name() string
}
type Etherium struct {
}
type Bitcoin struct {
}
func (c Etherium) name() string {
return "Etherium"
}
func (c Bitcoin) name() string {
return "Bitcoin"
}
// Abstract Factory implementation
type AbstractCoinFactory interface {
createCoin() Coin
}
type EtheriumFactory struct {
}
type BitcoinFactory struct {
}
func (c EtheriumFactory) createCoin() Coin {
return Etherium{}
}
func (c BitcoinFactory) createCoin() Coin {
return Bitcoin{}
}
```
## Usage
```go
func printNewCoinName (factory AbstractCoinFactory) {
coin := factory.createCoin()
fmt.Printf("%s\n", coin.name())
}
printNewCoinName(EtheriumFactory{})
printNewCoinName(BitcoinFactory{})
```