|
先来第一题(Java)
此文章由 fyang1024 原创或转贴,不代表本站立场和观点,版权归 oursteps.com.au 和作者 fyang1024 所有!转贴必须注明作者、出处和本声明,并保持内容完整
1.猜拳游戏。有3个class:Rock(拳头),Paper(巴掌)和 Scissor(剪刀)。这3个class有共同的super class GE.游戏中会调用这3个class来进行猜拳 object1.versus(object2).
问题1:要求写一个method返回猜拳的结果(object1.versus(object2)的结果) 问要写在这4个class中的哪一个部分(where),为什么。
问题2: 不用overloading,也不用条件判断,要求返回猜拳的结果,class的Structure应该是怎样构建。
abstract class GE {
protected String id;
protected Map<GE, String> resultMap;
public String versus(GE other) {
return resultMap.get(other);
}
public boolean equals(Object o) { // this method is important to the resultMap
if(o == null) return false;
if(!o instanceof GE) return false;
GE other = (GE)o;
return id.equals(other.id);
}
public int hashCode() { // this method is important to the resultMap, too
return id.hashCode();
}
}
class Rock extends GE {
protected String id = "Rock";
public Rock() {
resultMap = new HashMap<GE, String>();
resultMap.put(new Rock(), "TIE");
resultMap.put(new Paper(), "LOSE");
resultMap.put(new Scissor(), "WIN");
}
}
...
以上是问题2的回答
问题1可以用类似的思路,在父类里不放resultMap,而是放
protected GE destroying;
public String versus(GE other) {
if(other.equals(this)) return "TIE";
if(other.equals(destroying)) return "WIN";
return "LOSE";
}
子类Paper的destroying是Rock对象, 依此类推 |
评分
-
查看全部评分
|