课时143:综合实战:宠物商店
1.1宠物商店具体流程
假设有一个宠物商店里面可以出售各种宠物,要求可以实现宠物的上架处理、下架处理也可以根据关键字查询出宠物的信息。
例子:王静没钱了,养只林强行吗?当然不行,因为林强不是宠物,亦或者能养但是不能在商店里买卖。
例子2:一般拿到小狗会说“小狗你叫什么名字”小狗则回应“汪汪”“小狗你什么颜色的”小狗回应“我是黄色的”。由此可见,在整个流程不关注东西怎么来的,而关注它是什么。宠物商店能放狗、猫、鱼,如果这些都能放进宠物商店,为什么林强不能放进去,因为林强是人不符合宠物标准。
所以宠物商店里面严格来讲是有一个宠物标准:接口( Interface ),而狗、猫、鱼都是符合宠物标准,才能在商店里出售。宠物商店与宠物标准有直接的联系,而宠物标准有多种实现的类型。中间为了描述“多”的概念,需要设计专门保存数据的链表。
对于能保存多种信息而言就是链表的操作形式,宠物商品可以有多个宠物种类就是链表实现子类,这样可以实现一对多的关系。这便是动态对象数组。
(1)定义出宠物的标准
interface Pet { // 定义宠物标准 public String getName () ; // 获得名字 publie String getColor () ; // 获得颜色 }
(2)宠物商店以宠物的标准为主
class Petshop { // 宠物商店 private ILink<pet>allPets=new LinkImpl<Pet> () ; // 保存多个宠物信息 public void add (Pet pet) { //追加宠物,商品上架 this.allPets.add(pet) ;{ //集合中保存对象 } public void delete(Pet pet) { this.allPets.remove(pet) ; } public ILink<Pet> search(String keyword){ ILink<pet>searchResult = new LinkImpl<Pet> () ; //保存查询结果 Object result [ ]= this.allPets.toArray () ; //获取全部数据 If (result ! = null) { for (object obj : result) { If(pet.getName().contains(keyword) II pet.getColor().contains(keyWord) { searchResult.add(pet) ; // 保存查询结果 } } } return searchResult ; } }
(3)根据宠物的标准来定义宠物信息
定义宠物猫:
class Cat implements Pet { //实现宠物标准 private String name ; private String color; public Cat(string name,String color) { this.name = name ; this.color =color ; } public String getName () { Return this.name ; } public String getColor () return this.color ; } public boolean equals (Object obj ) { if (obj ==null) { Return False ; } If (!(obj instanceof Cat ) ) { return false ; } if (this = = obj) { return true ; } Cat cat= (Cat) obj ; Return this.name.equals (cat.name) && this.color.equals(cat.name) ; this.color.equals(cat.color); } public String toString () { return"【宠物猫】名字:"+this.name +"、颜色:"+ this. Color ; } } public class JavaDemo {
定义宠物狗:
class Dog implements Pet { //实现宠物标准 private String name ; private String color; public Dog (string name,String color) { this.name = name ; this.color =color ; } public String getName () { Return this.name ; } public String getColor () return this.color ; } public boolean equals (Object obj ) { if (obj ==null) { Return False ; } If (!(obj instanceof Cat ) ) { return false ; } if (this = = obj) { return true ; } Dog dog= (Dog) obj ; Return this.name.equals (dog.name) && this.color.equals(dog.name) ; this.color.equals(dog.color); } public String toString () { return"【宠物狗】名字:"+this.name +"、颜色:"+ this. Color ; } } public class JavaDemo {
(4)实现宠物商店的操作
public class JavaDemo { public static void main(String args [] ) { Petshop shop = new PetShop () ;// 开店 shop.add(new Dog("黄斑狗","绿色") ) ; shop.add(new Cat("小强猫","深绿色") ) ; shop.add(new Cat("黄猫","深色") ) ; shop.add(new Dog("黄狗""黄色") ) ; shop.add(new Dog("斑点狗""灰色") ) ; Object result [] = shop.search("黄").toArray() ; for (object obj :result) { System.out.println(obj) ; } } }
代码执行结果:
(5)总结
通过这样的程序代码发现接口对于标准的意义,整个代码重要的过程都在接口上,所有的程序开发都是以接口为标准进行的,这样再进行后期程序处理的时候就可以非常的灵活,只要符合标准的对象都可以保存。