NMP-Study / EffectiveJava2018

Effective Java Study
9 stars 0 forks source link

아이템 17. 변경 가능성을 최소화하라 #17

Closed madplay closed 5 years ago

duckcalf commented 5 years ago

불변객체를 만드는 다섯가지 규칙

public final class Complex {
    private final double re;
    private final double im;

    public Complex(double re, double im) {
        this.re = re;
        this.im = im;
    }

    public double realPart() {
        return re;
    }

    public double ImaginaryPart() {
        return im;
    }

    public Complex plus(Complex o) {
        return new Complex(re + o.re, im + o.im);
    }

    public Complex minus(Complex o) {
        return new Complex(re - o.re, im - o.im);
    }

    public Complex times(Complex o) {
        return new Complex(re * o.re - im * o.im, re * o.im + im * o.re);

    }

    public Complex dividedBy(Complex o) {
        double tmp = o.re * o.re + o.im + o.im;
        return new Complex((re * o.re + im * o.im) / tmp,(im * o.re - re * o.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(c.re, re) == 0 && Double.compare(c.im, im) == 0;
    }

    @Override
    public int hashCode() {
        return 31 * Double.hashCode(re) + Double.hashCode(im);
    }

    @Override
    public String toString() {
        return "(" + re + " + " + im + "i";
    }
}

장점

단점

불변 클래스를 만드는 다른 방법

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 Complext(re, im);
    }
    ...
}

그외 참고

최종 정리