足球戰(zhàn)術(shù)之Factory Method篇
時(shí)間:2024-10-20 來(lái)源: 作者: 我要糾錯(cuò)
<p style=line-height: 150%>接上回:<p style=line-height: 150%><A >http://www.csdn***/Develop/read_article.asp?id=12040</A><p style=line-height: 150%>使用工廠方法有以下好處,
球員僅處理進(jìn)球(product)接口,
但每要產(chǎn)生一種新的進(jìn)球方式,
就必須讓這個(gè)隊(duì)員來(lái)學(xué)會(huì)這種方法,
或者換個(gè)隊(duì)員。球員基類(lèi)在類(lèi)中
創(chuàng)建進(jìn)球,而不是直接創(chuàng)建,
為子類(lèi)提供一個(gè)hook。提供平行
的類(lèi)層次。
代碼如下:
class 球員{
public:
virtual 進(jìn)球* 創(chuàng)建(進(jìn)球類(lèi)型);
};<p style=line-height: 150%>進(jìn)球* 球員::創(chuàng)建(進(jìn)球類(lèi)型 id){
if (id==高空球) return new 頭球進(jìn)球;
if (id==半高球) return new 抽射破門(mén);
<A href="file://repeat">file://repeat</A> for remaining products...
return 0;
}<p style=line-height: 150%>進(jìn)球* 射門(mén)機(jī)器::創(chuàng)建(進(jìn)球類(lèi)型 id){
if (id==高空球) return new 倒鉤;
if (id==半高球) return new 胸部或肩部擋進(jìn)去;
if (id==低球) return new 魚(yú)躍沖頂;
return 球員::創(chuàng)建(id);//全部其他的失敗時(shí)調(diào)用
}
標(biāo)簽: