public interface PersonCreationStrategy {
Person create(PersonCreateCommand command);
}
public class PersonCreateCommand {
private String type;
private Map<String , String> params;
}
public class PersonService {
private final Map<String, PersonCreationStrategy> creationStrategies;
public Person create(PersonCreateCommand command) {
PersonCreationStrategy creationStrategy = creationStrategies.get(command.getType());
if (creationStrategy == null) {
throw new UnsupportedTypeException("unsupported type " + command.getType());
}
Person person = creationStrategy.create(command);
return person;
}
}
我在我的应用程序策略模式中将不同类型的类存储到数据库中,我的主类是 Person 和 Person 之后的其他类继承,Person 类将所有类型存储在 SINGLE_TABLE 中,
现在我需要为子类执行 DTO,因为我需要返回附加值。
有人可以向我解释一下吗?如何以良好的方式做到这一点?
这是好方法吗?
public Employee create(PersonCreateCommand command) {
Map<String , String> params = command.getParams();
return Employee.builder()
.firstName(params.get("firstName"))
.lastName(params.get("lastName"))
.identifier(params.get("identifier"))
.height(Long.parseLong(params.get("height")))
.weight(Long.parseLong(params.get("weight")))
.email(params.get("email"))
.hireDate(LocalDate.parse(params.get("hireDate")))
.jobPosition(params.get("jobPosition"))
.salary(BigDecimal.valueOf(Long.parseLong(params.get("salary"))))
.build();
}
更好的是重构:
public interface PersonCreationStrategy<T extends Person> {
T create(PersonCreateCommand command);
boolean accepts(String type);
}
public class PersonCreateCommand {
private String type;
private Map<String , String> params;
}
public class PersonService {
private final List<PersonCreationStrategy<? extends Person>> creationStrategies;
public Person create(PersonCreateCommand command) {
PersonCreationStrategy creationStrategy = creationStrategies.stream().filter(s -> s.accepts(command.getType())).findFirst().orElseThrow(() ->
new UnsupportedTypeException("unsupported type " + command.getType());
Person person = creationStrategy.create(command);
return person;
}
public class EmployeeCreationStrategy implements PersonCreationStrategy<Employee> {
public Employee create(PersonCreateCommand command){ ...
public boolean accepts(String type){ EMPLYEE_TYPE.equals(type)};
}