go设计模式-工厂方法
package main import ( "errors" "fmt" ) const ( ACT = 1 TASK = 2 ) type Quest struct { Id int QuestType int Process int Status int } type Questier interface { DoAction(Quest) } type ActQuest struct { } func (a *ActQuest) DoAction(quest Quest) { quest.Process += 1 fmt.Println("act doaction:", quest) } type TaskQuest struct { } func (t *TaskQuest) DoAction(quest Quest) { quest.Process += 10 fmt.Println("task doaction", quest) } // Factory func GetQuestier(questierType int) (Questier, error) { switch questierType { case ACT: return new(ActQuest), nil case TASK: return new(TaskQuest), nil default: return nil, errors.New(fmt.Sprintf("questier type %d not recognized.", questierType)) } } func main() { quest := Quest{1, 1, 0, 0} questier, err := GetQuestier(ACT) if err == nil { questier.DoAction(quest) } quest2 := Quest{2, 1, 0, 0} questier, err = GetQuestier(TASK) if err == nil { questier.DoAction(quest2) } } output: act doaction: {1 1 1 0} task doaction {2 1 10 0}