Tuesday, July 25, 2017

Factory Pattern in Golang

Factory Pattern is  a creational design pattern and one of the most use pattern in programming. In factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.

Here is the code shown as below:


package main

import "fmt"

//concrete shape
type Shape struct {
    draw string
}

//abstract factory for creating shape
type AbstractFactory interface {
    CreateShape() Shape
}

type CubeFactory struct {
}

type CircleFactory struct {
}

//concrete implementation
func (a CubeFactory) CreateShape() Shape {
    return Shape{"Cube"}
}

//concrete implementation
func (a CircleFactory) CreateShape() Shape {
    return Shape{"Circle"}
}

//main factory method
func getShape(typeGf string) Shape {

    var gffact AbstractFactory
    switch typeGf {
    case "cube":
        gffact = CubeFactory{}
        return gffact.CreateShape()
    case "circle":
        gffact = CircleFactory{}
        return gffact.CreateShape()
    }
    return Shape{}
}

func main() {
    a := getShape("cube")
    fmt.Println(a.draw)
}


Other Topics:


No comments:

Post a Comment