Sobes.tech
Middle

Tell about a pattern you have used in your code or product.

sobes.tech AI

Answer from AI

I worked with the "Factory" pattern, particularly when implementing a service for processing various types of incoming requests.

// Interface for request handlers
type RequestHandler interface {
	Handle(requestData string) (string, error)
}

// Concrete handler for type A
type TypeAHandler struct{}

func (h *TypeAHandler) Handle(requestData string) (string, error) {
	// Processing logic for type A
	return "Processed Type A: " + requestData, nil
}

// Concrete handler for type B
type TypeBHandler struct{}

func (h *TypeBHandler) Handle(requestData string) (string, error) {
	// Processing logic for type B
	return "Processed Type B: " + requestData, nil
}

// Factory for creating handlers
func CreateHandler(requestType string) (RequestHandler, error) {
	switch requestType {
	case "type_a":
		return &TypeAHandler{}, nil
	case "type_b":
		return &TypeBHandler{}, nil
	default:
		return nil, fmt.Errorf("unknown request type: %s", requestType)
	}
}

// Example usage
func main() {
	handlerA, err := CreateHandler("type_a")
	if err != nil {
		log.Fatal(err)
	}
	resultA, _ := handlerA.Handle("some data for A")
	fmt.Println(resultA)

	handlerB, err := CreateHandler("type_b")
	if err != nil {
		log.Fatal(err)
	}
	resultB, _ := handlerB.Handle("some data for B")
	fmt.Println(resultB)
}

The "Factory" pattern allowed encapsulating object creation logic into a separate class (function), which simplified dependency management and added flexibility. When it is necessary to add a new request type, it is enough to implement a new RequestHandler and add it to the factory without affecting the code that uses the handlers.