java—如何消除这个重复的方法错误?

sdnqo3pr  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(264)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

17天前关门了。
改进这个问题
这是我的代码,我想修复它,以便复制方法错误,我想做“公共颜色(float h,float s,float v,int a)”作为占位符,但我想知道是否有更好的选择。

private float red;
    private float blue;
    private float green;

    public Color( float r, float g, float b){
        red = r;
        blue = b;
        green = g;
    }
    private float hue;
    private float saturation;
    private float value;
    public Color (float h, float s, float v){
        hue = h;
        saturation = s;
        value = v;
    }
8ulbf1ek

8ulbf1ek1#

如果构造器的行为不清楚,就像在本例中一样,可以使用静态方法返回新对象,同时返回私有构造器。

private float red;
private float green;
private float blue;

private Color(float r, float g, float b){
    red = r;
    green = g;
    blue = b;
}

public static Color fromRGB(float r, float g, float b) {
   return new Color(r, g, b);
}

public static Color fromHSV( float h, float s, float v) {
   // Do the mathematics here to convert HSV to RGB, and then use 
   // return new Color(...) on the result
}

这样,你就可以写作了 Color.fromRGB(10, 10, 10) (或者别的什么),而不是 new Color(10, 10, 10) 而且含义更清楚。

相关问题