Goファクトリーパターンを実装する方法

Goのファクトリーメソッドパターンが適用できるユースケース:

  1. 条件に応じて異なるコンクリートオブジェクトインスタンスを返す必要があるオブジェの作成。
  2. オブジェクト生成具体的な手順を隠蔽し、ファクトリメソッドだけを外部に公開する必要がある。
  3. 複数の類似したオブジェクトを作成するために、共通のファクトリーを使う必要がある。

ここでコードの一例を紹介します:

package main

import "fmt"

// 定义一个接口
type Animal interface {
	Sound() string
}

// 定义具体的狗类
type Dog struct{}

func (d Dog) Sound() string {
	return "汪汪汪"
}

// 定义具体的猫类
type Cat struct{}

func (c Cat) Sound() string {
	return "喵喵喵"
}

// 定义工厂函数,根据传入的参数返回相应的具体对象实例
func AnimalFactory(animalType string) Animal {
	switch animalType {
	case "dog":
		return Dog{}
	case "cat":
		return Cat{}
	default:
		return nil
	}
}

func main() {
	dog := AnimalFactory("dog")
	fmt.Println(dog.Sound()) // 输出:汪汪汪

	cat := AnimalFactory("cat")
	fmt.Println(cat.Sound()) // 输出:喵喵喵
}

上で定義したAnimalインターフェースと、それを具体化したDogとCatという2つのクラスから、Factoryパターンを用いて入力パラメーターによって、適切な具象オブジェクトのインスタンスを返却するAnimalFactoryというFactory関数を作成し、Mainメソッドで利用して、動物オブジェクトを生成し、そのメソッドを呼び出します。

bannerAds