Java实例分析:宠物商店

时间:2023-03-08 23:54:09
Java实例分析:宠物商店

设计一个“宠物商店”,在宠物商店中可以有多种宠物,试表示出此种关系,并要求可以根据宠物的关键字查找相应的宠物信息。

//=================================================
// File Name : factory
//------------------------------------------------------------------------------
// Author : Common // 接口名:Pet
// 属性:
// 方法:
interface Pet{
public String getName();
public String getColor();
public int getAge();
} //类名:Cat
//属性:
//方法:
class Cat implements Pet{
private String Name;
private String Color;
private int Age; public Cat(String name, String color, int age) { //构造方法
this.setName(name);
this.setColor(color);
this.setAge(age);
} public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getColor() {
return Color;
}
public void setColor(String color) {
Color = color;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
} //类名:Dog
//属性:
//方法:
class Dog implements Pet{
private String Name;
private String Color;
private int Age; public Dog(String name, String color, int age) { //构造方法
this.setName(name);
this.setColor(color);
this.setAge(age);
} public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getColor() {
return Color;
}
public void setColor(String color) {
Color = color;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
} //类名:PetShop
//属性:
//方法:
class PetShop{ private Pet[] pets; //定义一个Pet形数组,此数字的大小由传入的len决定
private int foot; //定义数组的当前元素下标 public PetShop(int len){ //数组的大小由len决定,构造方法
if(len>0){ //判断传入的长度是否大于0
this.pets = new Pet[len]; //根据传入的大小开辟空间
}else{
this.pets = new Pet[1]; //否则只开辟长度为1的空间
}
} public boolean add(Pet pet){
if(this.foot < this.pets.length){ //判断数组是否已经满了
this.pets[foot] = pet; //没有存满则继续添加
this.foot++; //修改下标
return true; //添加成功
}else{
return false; //添加失败,已经存满了
}
} public Pet[] search(String keyWord){ //关键字查找
Pet p[] = null; //存放查找的结果,此处的大小不是固定的
int count = 0; //记录下多少个宠物符合查询结果 for (int i=0;i<this.pets.length;i++){
if(this.pets[i] != null){
if(this.pets[i].getName().indexOf(keyWord) != -1 || this.pets[i].getColor().indexOf(keyWord) != -1){
count++; //统计符合条件的宠物个数
}
}
}
p = new Pet[count]; //根据已经确定的记录数开辟对象数组
int f = 0; //设置增加的位置标记
for (int i=0;i<this.pets.length;i++){
if(this.pets[i] != null){
if(this.pets[i].getName().indexOf(keyWord) != -1 || this.pets[i].getColor().indexOf(keyWord) != -1){
p[f] = this.pets[i]; //将符合查询条件的宠物信息保存
f++;
}
}
}
return p;
} } //主类
//Function : 适配器设计模式
public class Pet_demo { public static void main(String[] args) {
// TODO 自动生成的方法存根
PetShop ps = new PetShop(5);
ps.add(new Cat("白猫","白",2));
ps.add(new Cat("黑猫","黑",4));
ps.add(new Cat("黄猫","黄",3));
ps.add(new Cat("白狗","白",2));
ps.add(new Cat("黑狗","黑",2));
ps.add(new Cat("黄狗","黄",3));
print(ps.search("黑"));
} public static void print(Pet p[]){
for (int i = 0;i<p.length;i++){
if(p[i] != null){
System.out.println(p[i].getName()+p[i].getAge()+p[i].getColor());
}
}
} }