软件设计模式(Design pattern),又称设计模式,是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设 计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性、程序的重用性。
🏭 工厂方法模式(Factory Method)
现实世界的例子:考虑招聘经理的情况。一个人不可能对每个职位进行面试,根据职位空缺,她必须决定并将面试步骤委托给不同的人。 简单来说:它提供了一种将实例化逻辑委托给子类的方法
代码实现 (源码)
package examples
// 场景:以招聘经理为例。首先,我们有一个访谈者界面和回答问题方法
// Interviewer 面试接口 实现回答问题
type interviewer interface {
AskQuestions() string
}
// Developer 开发者
type Developer struct {
}
// AskQuestions 开发者面试需要回答的问题
func (developer *Developer) AskQuestions() string {
return "问关于开发的问题!"
}
// CommunityExecutive CommunityExecutive(行政人员)
type CommunityExecutive struct {
}
// AskQuestions CommunityExecutive(行政人员)面试需要回答的问题
func (communityExecutive *CommunityExecutive) AskQuestions() string {
return "问关于行政的问题!"
}
// HiringManager 现在让我们创造我们的 HiringManager(招聘经理)
type HiringManager struct {
Interviewer interviewer
}
// TakeInterview 接受面试
func (hiringManager *HiringManager) TakeInterview() string {
return hiringManager.Interviewer.AskQuestions()
}
// NewHiringManager 去找招聘者面试()
func NewHiringManager(iv interviewer) *HiringManager {
return &HiringManager{Interviewer: iv}
}
测试用例(源码)
package examples
import "testing"
// command: go test -v factory_method_test.go factory_method.go
func TestFactoryMethod(t *testing.T) {
// 开发者面试
developer := &Developer{}
// 获取一个给开发者面试的面试官
developmentManager := NewHiringManager(developer)
// 询问开发者问题
if str := developmentManager.TakeInterview(); str != "问关于开发的问题!" {
t.Fail()
}
// 行政人员
communityExecutive := &CommunityExecutive{}
// 获取一个给行政人员面试的面试官
communityExecutiveManager := NewHiringManager(communityExecutive)
// 询问行政人员问题
if str := communityExecutiveManager.TakeInterview(); str != "问关于行政的问题!" {
t.Fail()
}
}
注意
-
设计模式不是解决所有问题的灵丹妙药。
-
不要试图强迫他们; 如果这样做的话,应该发生坏事。
-
请记住,设计模式是问题的解决方案,而不是解决问题的解决方案;所以不要过分思考。
-
如果以正确的方式在正确的地方使用,他们可以证明是救世主; 否则他们可能会导致代码混乱。
声明
- 转载请注明出处
- 本文链接(https://blog.you-tang.com/detail/17)