建立宠物商店,里面可以进行要销售宠物的上架、下架、关键字查询。宠物的信息只需要:名字、年龄、颜色。
那么此时对应的关系:一个宠物商店有多种宠物。
建立宠物标准:
interface Pet {
public String getName();
public String getColor();
public int getAge();
}
宠物商店只关注于宠物的标准,而不关心具体是哪种宠物
class PetShop {
private Link pets = new Link();
public void add(Pet pet) {
this.pets.add(pet);
}
public void delete(Pet pet) {
this.pets.remove(pet);
}
public Link getPets() {
return this.pets;
}
public Link search(String keyWord) {
Link result = new Link();
Object[] data = this.pets.toArray();
for(int x = 0; x < data.length; x++) {
Pet pet = (Pet)data[x];
if(pet.getName().contains(keyWord) || pet.getColor().contains(keyWord))
result.add(pet);
}
return result;
}
}
定义宠物狗
class Dog implements Pet {
private String name;
private int age;
private String color;
public Dog(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
public String getColor() {
return this.color;
}
public boolean equals(Object obj) {
if(obj == null)
return false;
if(this == obj)
return true;
if(!(obj instanceof Dog))
return false;
Dog pet = (Dog)obj;
return this.name.equals(pet.getName()) && this.age == pet.getAge() && this.color.equals(pet.getColor());
}
public String toString() {
return "【狗】名字:" + this.name + ",年龄:" + this.age + ", 颜色:" + this.color;
}
}
主方法
public class TestLinkDemo {
public static void main(String[] args) throws Exception {
PetShop ps = new PetShop();
ps.add(new Dog("黑狗", 1, "黑色"));
ps.add(new Dog("金毛",2, "金色"));
ps.add(new Dog("拉布拉多", 1, "金色"));
ps.add(new Cat("加菲猫", 2, "金色"));
ps.add(new Cat("波斯猫", 1, "白色"));
ps.delete(new Dog("拉布拉多", 1, "金色"));
Link all = ps.search("金");
Object[] data = all.toArray();
for(int x = 0; x < data.length; x++) {
System.out.println(data[x]);
}
}
}
$ java TestLinkDemo
【狗】名字:金毛,年龄:2, 颜色:金色
【猫】名字:加菲猫,年龄:2, 颜色:金色