接口
//接口
public interface Shape {
void draw();
}
实现
//实现1
@Service
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
//实现2
@Serivce
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
//实现3
@Service
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
枚举类型
public enum SettingTypeEnum {
RECTANGLE("1","Rectangle", "矩形"),
SQUARE("2","Square", "正方形"),
CIRCLE("3","Circle", "圆形"),
;
public String code;
//接口的实现类名
public String implement;
//备注
public String desc;
SettingTypeEnum(String code,String implement, String desc) {
this.code = code;
this.implement = implement;
this.desc = desc;
}
}
策略工厂
@Component
public class ShapeBeanFactory {
@Autowired//关键在这个,原理:当一个接口有多个实现类的时候,key为实现类名,value为实现类对象
private Map<String, Shape> shapeMap;
@Autowired//这个注入了多个实现类对象
private List<Shape> shapeList;
public Shape getShape(String shapeType) {
Shape bean1 = shapeMap.get(shapeType);
System.out.println(bean1);
return bean1;
}
}
控制层或者业务层
@RestController
public class control {
@Autowired
private ShapeBeanFactory factory; // 使用注解注入
@GetMapping("/drawMyShape")
public String drawMyShape(){
shapeBeanFactoryDraw();
return "成功";
}
private void shapeBeanFactoryDraw() {
//根据业务逻辑查库或者其他逻辑确定了一个类型
String circle = SettingTypeEnum.CIRCLE.implement;
//获取真正对象
Shape shapeInterface1 = factory.getShape(circle);
shapeInterface1.draw();
}
}