Coding again the interface.
interface:
package com.frankmoley.lil.designpatternsapp.factory; public interface Pet { void setName(String name); String getName(); String getType(); boolean isHungry(); void feed(); }
Factory:
package com.frankmoley.lil.designpatternsapp.factory; import org.springframework.stereotype.Component; @Component public class PetFactory { public Pet createPet(String animalType){ switch(animalType.toLowerCase()){ case "dog": return new Dog(); case "cat": return new Cat(); default: throw new UnsupportedOperationException("unknown animal type"); } } }
@Component added to tell this class should be managed by Spring, so later we can use @Autowired.
Class implements the interface:
package com.frankmoley.lil.designpatternsapp.factory; public class Cat implements Pet { private String name; private boolean hungry; public Cat(){ super(); this.hungry = true; } @Override public void setName(String name) { this.name = name; } @Override public String getName() { return this.name; } @Override public String getType() { return "CAT"; } @Override public boolean isHungry() { return this.hungry; } @Override public void feed() { this.hungry = false; } }
Controller:
@RestController @RequestMapping("/") public class AppController { @Autowired private PetFactory petFactory; @GetMapping public String getDefault(){ return "{"message": "Hello World"}"; } @PostMapping("adoptPet/{type}/{name}") public Pet adoptPet(@PathVariable String type, @PathVariable String name){ Pet pet = this.petFactory.createPet(type); pet.setName(name); pet.feed(); return pet; } }