2017-1-18 11:40:25 oye
五条原则
- 不要提供任何会修改对象状态的方法
- 保证类不会被扩展(也有其他设计方法可以支持扩展)
- 所有域都是
final
的 - 使所有的域都成为私有的
- 确保对于任何可变组件的互斥访问(确保客户端无法获取指向可变对象的域的引用)
Example Code:
/**
* 复数(不可变类)
* @author zWX332481
*/
public final class Complex
{
private final double re;
private final double im;
public Complex(double re, double im)
{
this.re = re;
this.im = im;
}
/**
* 实部
* @return double
*/
public double realPart()
{
return re;
}
/**
* 虚部
* @return double
*/
public double imaginaryPart()
{
return im;
}
public Complex add(Complex c)
{
return new Complex(re + c.re, im + c.im);
}
public Complex subtract(Complex c)
{
return new Complex(re - c.re, im - c.im);
}
public Complex multiply(Complex c)
{
return new Complex(re * c.re - im * c.im, re * c.im + im * c.re);
}
public Complex divide(Complex c)
{
double tmp = c.re * c.re + c.im * c.im;
return new Complex((re * c.re + im * c.im) / tmp, (im * c.re - re * c.im) / tmp);
}
@Override
public boolean equals(Object o)
{
if (o == this)
return true;
if (!(o instanceof Complex))
return false;
Complex c = (Complex) o;
return Double.compare(re, c.re) == 0 && Double.compare(im, c.im) == 0;
}
@Override
public int hashCode()
{
return (17 + hashDouble(re)) * 31 + hashDouble(im);
}
private int hashDouble(double val)
{
long longBits = Double.doubleToLongBits(re);
return (int) (longBits ^ (longBits >>> 32));
}
}
Analysis:
- 针对
Complex
类中的私有域,实部re
和虚部im
,类将其定义为final
的,且只提供了getter
方法,保证了类在创建之后就无法改变 - 同时针对其提供的四个基本运算方法,均未改变其私有域,而是产生一个新的对象
Improvement:
改进的更灵活的方法晚些时候添加