20145311实验二 "Java面向对象程序设计"
程序设计过程
实验内容
使用单元测试、TDD的方式设计实现复数类 Complex
编写代码:
1、首先设计实现复数类 Complex,复数类 Complex的方法设计有:复数类的定义、复数类输出的形式,复数的加法、减法、乘法、除法(除法因为涉及到一个整除的问题,所以会有些缺陷)运算。 2、伪代码:
Complex类中会有一个复数的实部与虚部,以及复数输出的形式
然后是四种运算:
加法:实部相加,虚部相加,最后返回虚数的形式
减法:实部相减,虚部相减,最后返回虚数的形式
乘法:实部相乘减去虚部相乘返回实部,实部虚部交错相乘后相加返回虚部,最后返回虚数形式
除法:利用共轭复数转换为类似乘法进行运算,最后返回虚数形式
3、撰写Complex类:
package com.company;
public class Complex {
protected int a;
protected int b;
public Complex(int a, int b) {
this.a = a;
this.b = b;
}
public String toString() {
return this.a + " + " + this.b + "i";
}
public static Complex addition(Complex complex1, Complex complex2) {
int a = complex1.a + complex2.a;
int b = complex1.b + complex2.b;
return new Complex(a, b);
}
public static Complex subtract(Complex complex1, Complex complex2) {
int a = complex1.a - complex2.a;
int b = complex1.b - complex2.b;
return new Complex(a, b);
}
public static Complex multiplication(Complex complex1, Complex complex2) {
int a = complex1.a * complex2.a - complex1.b * complex2.b;
int b = complex1.b * complex2.a + complex1.a * complex2.b;
return new Complex(a, b);
}
public static Complex division(Complex complex1, Complex complex2) {
if (complex2.a * complex2.a + complex2.b * complex2.b == 0) {
System.out.println("ERROR");
}
int a = (complex1.a * complex2.a + complex1.b * complex2.b) / (complex2.a * complex2.a + complex2.b * complex2.b);
int b = (complex1.b * complex2.a - complex1.a * complex2.b) / (complex2.a * complex2.a + complex2.b * complex2.b);
return new Complex(a, b);
}
}
调用Complex类实例:
4、测试代码:
public class Main {
public static void main(String[] args) {
Complex complex1 = new Complex(1, 2);
Complex complex2 = new Complex(3, 4);
if(Complex.addition(complex1, complex2).a!=4||Complex.addition(complex1, complex2).b!=6)
System.out.println("Test failed addition");
else
System.out.println("Test passed addition");
if(Complex.subtract(complex1, complex2).a!=-2||Complex.subtract(complex1, complex2).b!=-2)
System.out.println("Test failed substract");
else
System.out.println("Test passed substract");
if(Complex.multiplication(complex1, complex2).a!=-5||Complex.multiplication(complex1, complex2).b!=10)
System.out.println("Test failed multiplication");
else
System.out.println("Test passed multiplication");
}
}
测试结果:
TDD(Test Driven Devlopment, 测试驱动开发)和单元测试其实就是在不断的测试代码的同时对代码进行改进,从而减少使用时可能的错误。
继承封装多态
Complex类就是一种封装,在这个类中将复数的相关形式以及加减乘除运算都封装在这个类中,从而在其他类中可以继承或调用。
建模结果截图:
S.O.L.I.D原则
SRP(Single Responsibility Principle,单一职责原则)
OCP(Open-Closed Principle,开放-封闭原则)
LSP(Liskov Substitusion Principle,Liskov替换原则)
ISP(Interface Segregation Principle,接口分离原则)
DIP(Dependency Inversion Principle,依赖倒置原则)
PSP(Personal Software Process)
步骤 | 耗时 | 百分比 |
---|---|---|
需求分析 | 10min | 9 |
设计 | 10min | 9 |
代码实现 | 30min | 28 |
测试 | 40min | 36 |
分析总结 | 20min | 18 |