足球战术之Factory Method篇


<p style=line-height: 150%>接上回:

<p style=line-height: 150%><A href="http://www.csdn***/Develop/read_article.asp?id=12040">http://www.csdn***/Develop/read_article.asp?id=12040</A>

<p style=line-height: 150%>使用工厂方法有以下好处,
球员仅处理进球(product)接口,
但每要产生一种新的进球方式,
就必须让这个队员来学会这种方法,
或者换个队员。球员基类在类中
创建进球,而不是直接创建,
为子类提供一个hook。提供平行
的类层次。
代码如下:
class 球员{
public:
     virtual 进球* 创建(进球类型);
};

<p style=line-height: 150%>进球* 球员::创建(进球类型 id){
    if (id==高空球) return new 头球进球;
    if (id==半高球) return new 抽射破门;
    <A href="file://repeat">file://repeat</A> for remaining products...
    return 0;
}

<p style=line-height: 150%>进球* 射门机器::创建(进球类型 id){
    if (id==高空球) return new 倒钩;
    if (id==半高球) return new 胸部或肩部挡进去;
   
    if (id==低球) return new 鱼跃冲顶;
     return 球员::创建(id);//全部其他的失败时调用
}




扫一扫在手机打开当前页

关注公众号

微信公众号