Configuration Struct + Factory

The Configuration Struct + Factory pattern uses a struct to hold configuration options and a factory function to create and initialize the object.

Applicability

  • When configuration values are grouped and passed together.
  • When you want simple and readable object creation.
  • When you need to validate or process config before object creation.
  • Useful for passing options across layers or packages.

Example

package main

type Config struct {
	Host string
	Port int
}

type Server struct {
	host string
	port int
}

func NewServer(cfg Config) *Server {
	return &Server{
		host: cfg.Host,
		port: cfg.Port,
	}
}

This site is open source! You can contribute or suggest changes by editing the GitHub repository.
Copyright © 2025. Distributed by an MIT license.