综合案例:宠物商店

建立宠物商店,里面可以进行要销售宠物的上架、下架、关键字查询。宠物的信息只需要:名字、年龄、颜色。

那么此时对应的关系:一个宠物商店有多种宠物。
PNG image 12.png

建立宠物标准:
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, 颜色:金色

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值