Golang Design Pattern Abstract Factory and Factory Method

Hello my dear friends. This post will discuss a Creational design pattern Abstract Factory and we will implement it in Golang. There are too many complex definition of Abstract Factory written by very very wide people, but I call my self a normal guy, who just understand the basic language. I will try to explain it in a same way and will implement in Golang.

type AbstractFactory interface {
        CreateMyLove()
}

AbstractFactory is a interface which provides a method CreateMyLove(). This a basic thing we need for Abstract Factory.

CreateMyLove() is a factory method.

To explain this all, I will just say without knowing the concrete objects our AbstractFactory can create an objects of my GirlFriend. Now I am ready to create my concrete girlfriend.

package main

import "fmt"

// this is my concrete girl friend
type GirlFriend struct {
       nationality string
       eyesColor string
       language string
}

// abstract factory for creating girlfriend
type AbstractFactory interface {
        CreateMyLove() GirlFriend
}


// my indian girlfriend
type IndianGirlFriendFactory struct {

}

// mu korean girlfirend
type KoreanGirlFriendFactory struct {

}

// concrete implementation
func (a IndianGirlFriendFactory) CreateMyLove() GirlFriend {
       return GirlFriend{"Indian" , "Black" , "Hindi"}
}


// concrete implementation
func (a KoreanGirlFriendFactory) CreateMyLove() GirlFriend {
       return GirlFriend{"Korean" , "Brown" , "Korean"}
}


// main factory method
func getGirlFriend(typeGf string) GirlFriend {

       var gffact AbstractFactory
       switch typeGf {
       case "Indian":
              gffact = IndianGirlFriendFactory{}
              return gffact.CreateMyLove()
       case "Korean":
              gffact = KoreanGirlFriendFactory{}
              return gffact.CreateMyLove()
       }
       return GirlFriend{}
}

func main(){

       var typeGf string
       fmt.Scanf("%s", &typeGf)
       a := getGirlFriend(typeGf)

       fmt.Println(a.eyesColor)

}

Above is a basic implementation for Abstract Factory in Golang. If you need more details Wikipedia is a great place to refer for design patterns understanding. You don’t need to use them every-time. Just use them when you need them most, because they make code reusable but, their implementation is complex. See you soon friends.  🙂

Advertisements

One thought on “Golang Design Pattern Abstract Factory and Factory Method

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s