0
\$\begingroup\$

Here I'm trying to learn the Abstract factory pattern. Have referred some examples and trying to mimic the same with some dummy server examples. Please help me to review this.

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

type server interface {
    Query()
    GetContent() string
}

type google struct {
    URL     string
    content string
}

type yahoo struct {
    URL     string
    content string
}

func (g *google) Query() {
    resp, err := http.Get(g.URL)
    if err != nil {
        log.Fatal(err)
    }
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    g.content = string(body)
}

func (g *google) GetContent() string {
    return g.content

}

func (g *yahoo) Query() {
    resp, err := http.Get(g.URL)
    if err != nil {
        log.Fatal(err)
    }
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    g.content = string(body)

}

func (g *yahoo) GetContent() string {
    return g.content
}

func createFactory(domain string) server {
    switch domain {
    case "google":
        return &google{URL: "https://www.google.com"}
    case "yahoo":
        return &yahoo{URL: "https://www.yahoo.com"}

    default:
        fmt.Println("Invalid domain")
        return nil
    }

}

func main() {
    googleServer := createFactory("google")
    googleServer.Query()
    fmt.Println(googleServer.GetContent())

    yahooServer := createFactory("yahoo")
    yahooServer.Query()
    fmt.Println(googleServer.GetContent())

}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.