用流水线完成歌手比赛的评分;其中InputScore这个类的对象负责输入评委给出的分数,类里面组合了一个DelScore类的对象引用。这个对象负责去掉分数的最大值和最小值,这个类里面有一个ComputerAver的类实现求出其他分数的平均分。也就是最终的评分结果。
package Democlass1;
import java.util.Arrays;
import java.util.Scanner;
public class SingGame {
public static void main(String[] args) {
Line line=new Line();
line.getscore();
}
}
class InputScore
{
private DelScore delscore;
public InputScore(DelScore a)
{
delscore=a;
}
public void inputscore()
{
Scanner read=new Scanner(System.in);
System.out.println("请输入评委数:");
int count=read.nextInt();
double [] a=new double [count];
System.out.println("请输入每个评委给出的分数:");
for(int i=0;i<count;i++)
a[i]=read.nextDouble();
delscore.delbig_small(a);
}
}
class DelScore
{
private Computeraver aver;
public DelScore(Computeraver aver)
{
this.aver=aver;
}
public void delbig_small(double[] a)
{
Arrays.sort(a);
double[] b=Arrays.copyOfRange(a, 1,a.length-1);
//System.out.println(b.length);
aver.aver_score(b);
}
}
class Computeraver
{
public void aver_score(double[] c)
{
double sum=0;
for(int i=0;i<c.length;i++)
sum+=c[i];
System.out.println("这次的评分最终结果为:");
System.out.println(".................");
System.out.println(sum/c.length);
System.out.println(".................");
}
}
class Line//完成流水线的类
{
private InputScore one;
private DelScore two;
private Computeraver three;
public Line()//搭建流水线;
{
three=new Computeraver();
two=new DelScore(three);
one=new InputScore(two);
}
public void getscore()
{
one.inputscore();
}
}
<span style="font-size:24px;">总结:这个流水线是使用了类的组合来完成的。通过这个例子也可以看出类的组合是为了提高代码的复用,更重要的是搭建类与类之间的联系,提高可读性。原本一直觉得类的组合是没有必要的,原因是可以通过我们习惯的继承来完成。就这个流水线而然,使用类的组合使得条理清晰,可读性强,使用起来也很方便。假如使用类的继承,一样可以实现。可读性也很好;也方便;代码也一样可以复用;</span><pre name="code" class="plain"><span style="font-size:24px;">但是就这个程序而然,使用类的组合给人更加好的感觉,也说不出好在哪里。</span>