2. 工厂方法模式(Factory Method)

问题:创建对象的逻辑分散在各处,想统一管理。

核心:把 new 的过程封装到工厂函数里,调用者不关心具体类。

class Dog {
  speak() { return '汪汪'; }
}

class Cat {
  speak() { return '喵喵'; }
}

function createPet(type) {
  switch (type) {
    case 'dog': return new Dog();
    case 'cat': return new Cat();
    default: throw new Error(`未知类型: ${type}`);
  }
}

const pet = createPet('dog');
console.log(pet.speak()); // 汪汪
package factory

import "fmt"

type Pet interface {
  Speak() string
}

type Dog struct{}
func (d Dog) Speak() string { return "汪汪" }

type Cat struct{}
func (c Cat) Speak() string { return "喵喵" }

func CreatePet(kind string) (Pet, error) {
  switch kind {
  case "dog":
    return Dog{}, nil
  case "cat":
    return Cat{}, nil
  default:
    return nil, fmt.Errorf("未知类型: %s", kind)
  }
}