Edited at

Go言語で factory method パターンを書いてみる

正しいか分かりませんが、Go言語でfactory method パターンを書いてみました。


factory.go

package main

import "fmt"

// created struct
type PersonStruct struct {
Name string
}
type Person interface {
GetZikoshoukai() string
}

type Man struct {
PersonStruct
}
func (man *Man) GetZikoshoukai() string {
return man.Name + "だぜ!"
}

type Woman struct{
PersonStruct
}
func (woman *Woman) GetZikoshoukai() string {
return woman.Name + "よ!"
}

// factory
type Factory interface {
CreateInstance(name string) Person
}

type ManFactory struct {}
func (factory *ManFactory) CreateInstance(name string) Person {
man := new(Man)
man.Name = name
var person Person = man
return person
}

type WomanFactory struct {}
func (factory *WomanFactory) CreateInstance(name string) Person {
woman := new(Woman)
woman.Name = name
var person Person = woman
return person
}

// entry point
func main() {
var factory Factory = new(ManFactory)
man := factory.CreateInstance("ひろし")
fmt.Println(man.GetZikoshoukai())

factory = new(WomanFactory)
woman := factory.CreateInstance("なおこ")
fmt.Println(woman.GetZikoshoukai())
}


クラスで言うと、Personが親クラスでManとWomanが子クラスということになります。