我已经阅读了 Head First OOAD 第一章它有吉他示例,
吉他课
public class Guitar {
private String serialNumber;
private double price;
private String model;
private Type type;
private Builder builder;
private Wood backWood;
private Wood topWood;
}
在上面的类 Builder 中,Wood 和 Type 是枚举类型。Inventory 类具有吉他列表并提供添加、搜索和获取方法。
库存类
class Inventory {
List<Guitar> guitarList;
public Inventory() {
guitarList = new ArrayList<Guitar>();
}
public boolean addGuitar(Guitar guitar){
return guitarList.add(guitar);
}
public Guitar getGuitar(Guitar guitar) {
for(Guitar guitarData : guitarList ) {
if(guitarData.getSerialNumber().equals(guitar.getSerialNumber())){
return guitarData;
}
}
return null;
}
public List<Guitar> search(Guitar guitar) {
List<Guitar> list = new ArrayList<Guitar>();
for(Guitar guitarData : guitarList ) {
if(guitar.getBuilder() == null || !guitar.getBuilder().equals(guitarData.getBuilder())) {
continue;
}
if(guitar.getTopWood() == null || !guitar.getTopWood().equals(guitarData.getTopWood())) {
continue;
}
if(guitar.getBackWood() == null || !guitar.getBackWood().equals(guitarData.getBackWood())) {
continue;
}
if(guitar.getType() == null || !guitar.getType().equals(guitarData.getType())) {
continue;
}
if(guitar.getModel() == null || !guitar.getModel().equals(guitarData.getModel())) {
continue;
}
list.add(guitarData);
}
return list;
}
}
在书中,为库存中的搜索方法创建另一个类 GuitarSpec,因为在此方法中,客户端从不提供吉他的序列号和价格。
更新的课程:
吉他课
class Guitar {
private String serialNumber;
private double price;
private GuitarSpec guitarSpec;
public String getSerialNumber() {
return serialNumber;
}
public double getPrice() {
return price;
}
public GuitarSpec getGuitarSpec() {
return guitarSpec;
}
}
吉他规格类:
class GuitarSpec {
private String model;
private Type type;
private Builder builder;
private Wood backWood;
private Wood topWood;
public String getModel() {
return model;
}
public Type getType() {
return type;
}
public Builder getBuilder() {
return builder;
}
public Wood getBackWood() {
return backWood;
}
public Wood getTopWood() {
return topWood;
}
}
以及库存类别搜索方法的更改,
public List<Guitar> search(GuitarSpec searchSpec) {
List<Guitar> list = new ArrayList<GuitarSpec>();
for(Guitar guitar : guitarList ) {
GuitarSpec guitarSpec = guitar.getGuitarSpec();
if(searchSpec.getBuilder() == null || !searchSpec.getBuilder().equals(guitarSpec.getBuilder())) {
continue;
}
if(searchSpec.getTopWood() == null || !searchSpec.getTopWood().equals(guitarSpec.getTopWood())) {
continue;
}
if(searchSpec.getBackWood() == null || !searchSpec.getBackWood().equals(guitarSpec.getBackWood())) {
continue;
}
if(searchSpec.getType() == null || !searchSpec.getType().equals(guitarSpec.getType())) {
continue;
}
if(searchSpec.getModel() == null || !searchSpec.getModel().equals(guitarSpec.getModel())) {
continue;
}
list.add(guitar);
}
return list;
}
我不明白为什么要创建新的 GuitarSpec,根据 oops,这是必需的吗?