如果在课堂上正确设计了封装

时间:2017-01-23 07:25:47

标签: java encapsulation

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

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; 
    }
}

1 个答案:

答案 0 :(得分:4)

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

# internal forward from pretty URL to actual one
RewriteRule ^details/([^/.]+)/?$ server.php?id=$1 [L,QSA,NC]

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

  

public int width

     

宽度尺寸;可以使用负值。

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

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]