我已经阅读了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类具有Guitar列表,并提供add,search和get方法。
库存类
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吗?
答案 0 :(得分:2)
这是因为每把吉他都有一个规格。但并不是每个规格都有吉他 但是当你在寻找具有特定规格的吉他时, 你基本上会将每把吉他的规格与你要搜索的规格进行比较。 但是你不会搜索序列号和价格。
这样你可以使用guitarspec类withuit来制作吉他