Skip to content

Instantly share code, notes, and snippets.

@maxclav
Last active December 20, 2022 16:52
Show Gist options
  • Save maxclav/0e5dd39ba014a4bcfd67fc10f6096d22 to your computer and use it in GitHub Desktop.
Save maxclav/0e5dd39ba014a4bcfd67fc10f6096d22 to your computer and use it in GitHub Desktop.
Factory Method Design Pattern example in Go (GoLang).
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