首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

保龄球计分的面向对象兑现

2012-10-24 
保龄球计分的面向对象实现闲来无事,看到论坛中一个帖子谈到 《OO 还是 procedural 小程序的设计》http://www

保龄球计分的面向对象实现
闲来无事,看到论坛中一个帖子谈到
《OO 还是 procedural 小程序的设计》http://www.iteye.com/topic/1112383
尝试用OO的方式写了一下(真的是太闲了 ):



public class Frame {public static final int BALLS = 10;protected Frame nextFrame;protected int[] hitCounts;public Frame(int[] hitCounts) {this.hitCounts = hitCounts;}/** 当前Frame以及之后的总分 */public int totalScore() {int total = 0;for (Frame f = this; f != null; f = f.nextFrame) {total += f.frameScore();}return total;}/** 一局得分 */public int frameScore() {int total = 0;for (int hit : hitCounts)total += hit;if (nextFrame != null) {if (isStrikeFrame()) total += nextFrame.getStrikeBonus();if (isSpareFrame()) total += nextFrame.getSpareBonus();}return total;}/** 当前Frame可贡献的Spare奖励 */public int getSpareBonus() {return hitCounts[0];}/** 当前Frame可贡献的Strike奖励 */public int getStrikeBonus() {return hitCounts[0] + (nextFrame != null && isStrikeFrame() ? nextFrame.hitCounts[0] : hitCounts[1]);}public boolean isSpareFrame() {return !isStrikeFrame() && hitCounts[0] + hitCounts[1] == BALLS;}public boolean isStrikeFrame() {return hitCounts[0] == BALLS;}public void setNextFrame(Frame frame) {nextFrame = frame;}} class FrameFactory {public static Frame buildFrames(int[][] hitCounts) {Frame last = new Frame(hitCounts[hitCounts.length - 1]);for (int i = hitCounts.length - 2; i >= 0; i--) {Frame frame = new Frame(hitCounts[i]);frame.setNextFrame(last);last = frame;}return last;}} class Main {public static void main(String[] args) {int[][] hitCounts = new int[][] { { 10, 0 }, { 7, 2 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },{ 0, 0 }, { 0, 0 }, { 0, 0 } };Frame head = FrameFactory.buildFrames(hitCounts);System.out.println(head.totalScore());}}
2 楼 sswh 2011-07-22   策略模式的实现。

附件下载test.rar:
http://dl.iteye.com/topics/download/64530cce-063f-351f-86d6-3a6056cac132

热点排行