forked from jhyscode/Effetive-Java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComplex.java
More file actions
81 lines (72 loc) · 2.02 KB
/
Complex.java
File metadata and controls
81 lines (72 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.github.chapter3;
/**第15条:使可变性最小化
* https://my.oschina.net/jtzen9/blog/1524400
* Created by jhys on 2018/7/20
*/
public class Complex {
private final double re; //实部
private final double im; //虚部
private Complex(double re, double im) {
this.re = re;
this.im = im;
}
public static Complex valueOf(double re, double im) {
return new Complex(re,im);
}
public double realPart() {
return re;
}
public double imaginaryPart() {
return im;
}
//复数相加
public Complex add(Complex c) {
return new Complex(re + c.re,im + c.im);
}
}
//创建一个配套类
class ComplexBuilder {
private double re;
private double im;
private ComplexBuilder(double re, double im) {
this.re = re;
this.im = im;
}
public static ComplexBuilder newInstance(Complex c) {
return new ComplexBuilder(c.realPart(), c.imaginaryPart());
}
public void add(Complex c) {
this.re = this.re + c.realPart();
this.im = this.im + c.imaginaryPart();
}
public Complex toComplex() {
return Complex.valueOf(this.re, this.im);
}
}
/**
*在客户端中我们如果需要用一个复数和另一个复数相加100次,我们如果不用ComplexBuilder的话就像下面这样,
* 算上最开始穿件的两个实例,我们将会创建102个实例:
*/
class Test1 {
public static void main(String[] args) {
Complex c1 = Complex.valueOf(1, 2);
Complex c2 = Complex.valueOf(2, 3);
for (int i = 0; i < 100; i++) {
c1 = c1.add(c2);
}
}
}
/**
* 现在改用ComplexBuilder,现在我们只会创建4个实例
*/
class Test {
public static void main(String[] args) {
Complex c1 = Complex.valueOf(1,2);
Complex c2 = Complex.valueOf(2, 3);
ComplexBuilder cb = ComplexBuilder.newInstance(c1);
for (int i = 0; i < 100; i++) {
cb.add(c2);
}
c1 = cb.toComplex();
}
}