Created
May 23, 2024 13:42
-
-
Save sensoria-pro/a31ea0a7a5262b9d14418572e2dd84b1 to your computer and use it in GitHub Desktop.
Simple factory pattern, example simple distributed config
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 main | |
import ( | |
"fmt" | |
"net/http" | |
) | |
// Конфигурация сервера | |
type ServerConfig interface { | |
GetPort() string | |
} | |
// Фабрика конфигурации | |
type ConfigFactory interface { | |
CreateConfig() ServerConfig | |
} | |
// Конкретная фабрика для разработческой конфигурации | |
type DevConfigFactory struct{} | |
func (f *DevConfigFactory) CreateConfig() ServerConfig { | |
return &DevServerConfig{port: ":8080"} | |
} | |
// Конкретная фабрика для продакшн конфигурации | |
type ProdConfigFactory struct{} | |
func (f *ProdConfigFactory) CreateConfig() ServerConfig { | |
return &ProdServerConfig{port: ":8081"} | |
} | |
// Реализация конфигураций | |
type DevServerConfig struct{ port string } | |
func (c *DevServerConfig) GetPort() string { return c.port } | |
type ProdServerConfig struct{ port string } | |
func (c *ProdServerConfig) GetPort() string { return c.port } | |
func main() { | |
configFactory := &ProdConfigFactory{} // Можно заменить на ProdConfigFactory для продакшн конфигурации | |
config := configFactory.CreateConfig() | |
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprint(w, "Hello, world!") | |
}) | |
http.ListenAndServe(config.GetPort(), nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment