gpt4 book ai didi

java - 类中封装是否设计得当

转载 作者:行者123 更新时间:2023-12-01 17:59:58 25 4
gpt4 key购买 nike

该类的封装设计是否正确?具有负高度和宽度值的示例对象实例是否可以存在?

import java.awt.Dimension; 
/** * Example class. The x and y values should never * be negative.
*/
public class Example {
private Dimension d = new Dimension (0, 0);
public Example () {}
/** * Set height and width. Both height and width must be nonnegative * or an exception is thrown. */
public synchronized void setValues (int height, int width) throws IllegalArgumentException {
if (height < 0 || width < 0) throw new IllegalArgumentException();
d.height = height;
d.width = width;
}

public synchronized Dimension getValues() { // Passing member content by ref
return d;
}
}

最佳答案

你无法强制执行这一点。人们仍然可以通过在 getValues() 中返回的 Dimension 对象来更改高度和宽度值,即使这违反了 demeter 原理定律。

Example example = new Example();
example.setValues(10, 5);
System.out.println(example.getValues()); // java.awt.Dimension[width=5,height=10]

Dimension dimension = example.getValues();
dimension.height = -1;
dimension.width = -1;
System.out.println(example.getValues()); // java.awt.Dimension[width=-1,height=-1]

来自文档: https://docs.oracle.com/javase/8/docs/api/java/awt/Dimension.html#width

public int width

The width dimension; negative values can be used.

为了克服这个问题,解决方案可能是在 getValues() 中返回 Dimension 对象的深度克隆,以防止使用库更改原始对象,例如: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/SerializationUtils.html#clone(java.io.Serializable)

public synchronized Dimension getValues() { 
return SerializationUtils.clone(d);
// OR return new Dimension(d.width, d.height);
}

关于java - 类中封装是否设计得当,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41801133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com