- 概念:工厂模式(Factory Pattern)是 Java 中最常用的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。
- 意图:定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行。
- demo:
package pattern
import (
"errors"
"fmt"
"testing"
)
func TestFactory(t *testing.T) {
cat, err := AnimalCreator("cat")
if err == nil {
cat.Say()
}
dog, err:= AnimalCreator("dog")
if err == nil {
dog.Say()
}
wrong, err := AnimalCreator("xxx")
if err == nil {
wrong.Say()
}
}
type Animal interface {
Say()
}
type Dog struct {
}
func (d *Dog) Say() {
fmt.Println("wangwang")
}
type Cat struct {
}
func (c *Cat) Say() {
fmt.Println("miaomiao")
}
func AnimalCreator(animalType string) (Animal, error) {
err := errors.New("animal is no pattern")
switch animalType {
case "cat":
return &Cat{},nil
case "dog":
return &Dog{},nil
default:
fmt.Println("animal is no pattern")
return nil, err
}
}
网友评论