0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-11-26

正しいか分かりませんが、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が子クラスということになります。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?