Creational Pattern in Go With Abstract Factory and Factory Method
Jun 8, 2019
1 minute read
package main

type Reader interface {
	ReadAll(body []byte) error
}

type reader struct{}

func NewReader() *reader {
	return &reader{}
}

func (r *reader) ReadAll(body []byte) error {
	// Implement function ReadAll
	return nil
}

type Writer interface {
	WriteFile(name string, destination string, data interface{}) error
}

type writer struct{}

func NewWriter() *writer {
	return &writer{}
}

func (w *writer) WriteFile(name string, destination string, data interface{}) error {
	// Implement function WriteFile
	return nil
}

type Option struct {
	reader Reader
	writer Writer
}

func NewOption(reader Reader, writer Writer) *Option {
	return &Option{reader, writer}
}

func (o *Option) Injector() {
	// Use ReadAll function from Reader interface
	o.reader.ReadAll([]byte("ReadAll"))

	// Use WriteFile function from Writer interface
	o.writer.WriteFile("test", "test", "test")
}

func main() {
	reader := NewReader()
	writer := NewWriter()
	option := NewOption(reader, writer)

	option.Injector()
}