mirror of
https://github.com/tmrts/go-patterns.git
synced 2024-11-25 06:26:06 +03:00
creational/builder: implement the abstract factory
This commit is contained in:
parent
f978e42036
commit
5fdf4a775d
@ -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 | ✔ |
|
||||
|
55
creational/abstract-factory.md
Normal file
55
creational/abstract-factory.md
Normal file
@ -0,0 +1,55 @@
|
||||
# Abstract Factory Method Pattern
|
||||
|
||||
Abstract Factory method creational design pattern allows providing interface that creating objects without having to specify the exact type of the object that will be created.
|
||||
|
||||
## Implementation
|
||||
|
||||
The example implementation shows how to make a phone from different copmanies.
|
||||
|
||||
### Types
|
||||
|
||||
```go
|
||||
package company
|
||||
|
||||
type iCompnayFactory interface {
|
||||
makePhone() iPhone
|
||||
}
|
||||
```
|
||||
|
||||
### Different Implementations
|
||||
|
||||
```go
|
||||
package company
|
||||
|
||||
type CompnayType int
|
||||
|
||||
const (
|
||||
SAMSNUG CompnayType = iota
|
||||
APPLE
|
||||
)
|
||||
|
||||
func getCompnayFactory(compnay CompnayType) (iCompnayFactory, error) {
|
||||
switch compnay {
|
||||
case SAMSNUG:
|
||||
return &samsungFactory{}, nil
|
||||
case APPLE:
|
||||
return &appleFactory{}, nil
|
||||
default:
|
||||
return nil, fmt.Errorf(/* .. */)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
With the abstract factory method, the user can provide an interface for creating families of releated objects.
|
||||
|
||||
```go
|
||||
appleFactory, _ := getCompnayFactory(APPLE)
|
||||
applePhone := appleFactory.makePhone();
|
||||
applePhone.makeCall(/*...*/);
|
||||
|
||||
samsungFactory, _ := getCompnayFactory(SAMSNUG)
|
||||
samsungPhone := samsungFactory.makePhone();
|
||||
samsungPhone.makeCall(/*...*/);
|
||||
```
|
Loading…
Reference in New Issue
Block a user