常见的做法是使用JavaBean风格的
class Address {
private String name;
private String city;
public setName(String name){
this.name = name;
}
public String getName() {
return name;
}
public setCity(String city){
this.city = city;
}
public getCity() {
return city;
}
}
另一种常见的做法,这是相当类似于您第二种方法是创建不可变对象。参数传递给构造函数而不是大的setter方法。
class Address {
private final String name;
private final String city;
public Address(String name, String city) {
this.name = name;
this.city = city;
}
public String getName() {
return name;
}
public getCity() {
return city;
}
}
从视图存储器点,差异将是第二个例子是设置在构造所有属性和所有这些属性是不可变的。一般来说,用这种方法构建的对象在被多个线程使用时更安全。
在第二示例中,没有必要进行同步。当使用标准JavaBean对象的多线程时,您需要处理同步/内存问题。
向我们展示两种方法的代码示例的含义。 –
这个班的目的是什么?它是一个价值对象吗?你需要独立设置每个值吗?创建对象后,这些值是否必须改变? “记忆的角度”是什么意思?人类记忆或计算机记忆? – buritos
第一个例子很好,第二个例子很糟糕。使用构造函数。 – BalusC