[Spring] Factory Pattern
Spring pattern Factory
2023-09-14 08:59:13 时间
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; } }
相关文章
- 补习系列(22)-全面解读 Spring Profile 的用法
- 【Spring Boot】Spring Boot之使用 Spring Boot Configuration Processor 完成设置自定义项目属性自动补全
- spring: 在Spring应用中使用JDBC(使用profiles选择数据源/使用基于JDBC驱动的数据源)
- Quartz在Spring中动态设置cronExpression (spring设置动态定时任务)------转帖
- [Spring Pattern] Builder pattern
- Spring Boot 的Logback
- Spring 的两个配置容器的讲解
- [JS Pattern] Proxy pattern
- Spring调用spymemcached客户端的例子
- spring boot单元测试之六:用mockmvc模拟cookie(spring boot 2.4.3)
- 在ABAP里模拟实现Java Spring的依赖注入
- Spring 基于注解(annotation)的配置之@Required注解
- 学习Spring Boot:(十四)spring-shiro的密码加密
- 009-Spring Boot 事件监听、监听器配置与方式、spring、Spring boot内置事件
- 008-shiro与spring web项目整合【二】认证、授权、session管理
- 【Spring Boot】SpringBoot 优雅整合Swagger Api 自动生成文档