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:
parent
f978e42036
commit
9947015ae1
@ -15,7 +15,7 @@ A curated collection of idiomatic design & application patterns for Go language.
|
||||
|
||||
| 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 | ✔ |
|
||||
| [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 | ✔ |
|
||||
|
66
creational/abstract-factory.md
Normal file
66
creational/abstract-factory.md
Normal 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{})
|
||||
|
||||
```
|
Loading…
Reference in New Issue
Block a user