Last active
December 20, 2022 16:52
-
-
Save maxclav/0e5dd39ba014a4bcfd67fc10f6096d22 to your computer and use it in GitHub Desktop.
Factory Method Design Pattern example in Go (GoLang).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package storage | |
import ( | |
"errors" | |
"io" | |
) | |
// Product interface | |
type Storage interface { | |
Open(string) (io.ReadWriteCloser, error) | |
} | |
// Concrete product: In Memory Storage | |
type inMemory struct { /* ... */ } | |
func newInMemory() (*inMemory, error) { /* ... */ } | |
func (i *inMemory) Open(string) (io.ReadWriteCloser, error) { | |
// ... | |
} | |
// Concrete product: Disk Storage | |
type disk struct { /* ... */ } | |
func newDisk() (*disk, error) { /* ... */ } | |
func (d *disk) Open(string) (io.ReadWriteCloser, error) { | |
// ... | |
} | |
// Factory | |
type StorageType string | |
const ( | |
StorageTypeInMemory StorageType = "Storage In Memory" | |
StorageTypeDisk = "Storage Disk" | |
) | |
func New(t StorageType) (Storage, error) { | |
switch t { | |
case StorageTypeInMemory: | |
return newInMemory() | |
case StorageTypeDisk: | |
return newDisk() | |
// Add other concrete types here... | |
} | |
return nil, errors.New("invalid storage type") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment