集册 Java实例教程 仅使用吸气剂创建不可变对象

仅使用吸气剂创建不可变对象

欢马劈雪     最近更新时间:2020-01-02 10:19:05

473
只使用getter创建不可变对象

final public class ImmutableRGB {


    // Values must be between 0 and 255.

    final private int red;/** 来自 时代Java公众号 - nowjava.com**/

    final private int green;

    final private int blue;

    final private String name;


    private void check(int red, int green, int blue) {

        if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0

                || blue > 255) {

            throw new IllegalArgumentException();

        }

    }
/*来 自 nowjava.com - 时代Java*/

    public ImmutableRGB(int red, int green, int blue, String name) {

        check(red, green, blue);

        this.red = red;

        this.green = green;

        this.blue = blue;

        this.name = name;

    }


    public int getRGB() {

        return ((red << 16) | (green << 8) | blue);

    }


    public String getName() {

        return name;

    }


    public ImmutableRGB invert() {

        return new ImmutableRGB(255 - red, 255 - green, 255 - blue,

                "Inverse of " + name);

    }

}


展开阅读全文