使用模板方法(设计模式)进行区分字段
我一直在使用如下所示的创建请求,并且需要使用一些不需要的字段来实现更新请求。
@Data
public class CreateRequest extends BaseRequest {
@NotEmpty
private String token;
@NotEmpty
private String secret;
}
@Data
public class UpdateRequest extends BaseRequest {
private String token;
private String secret;
}
两个请求都应使用一些关系和接口。我认为通过保留这些请求的共享字段来使用模板设计模式。这适合这种情况吗?或者,您建议什么?
I have been using a Create Request as shown below and needed to implement an Update Request with some fields non-required.
@Data
public class CreateRequest extends BaseRequest {
@NotEmpty
private String token;
@NotEmpty
private String secret;
}
@Data
public class UpdateRequest extends BaseRequest {
private String token;
private String secret;
}
There are some relations and interfaces that should be used by both request. I think of using Template Design pattern by keeping the shared fields of these requests. Is that suitable for this scenario? Or, what would you suggest?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可能是您对最佳方法的想法中所期待的,但是我认为您最好的选择是拥有共享父级中两种请求类型所需的任何领域/行为,并拥有他们的个人需求/不同的领域在儿童课上。
我不确定您的可选字段是如何在概念上工作的,但是如果由于“默认”值是可选的,那么您可以将具有可选字段的类延伸从具有强制性字段的类别,并且只需实现一个构造函数调用具有默认值的超级构造函数。例如,如果
subclass
扩展了parentclass
,而父类的构造函数是两个字符串,第二个字符串在子类中具有“默认值”,则类似以下内容可以完成:This may have been what you were getting at in your thoughts on the best approach, but I think your best bet is to have whatever fields/behavior are required for both request types in a shared parent class, and have their individual needs/different fields in a child class.
I am not sure exactly how your optional fields are meant to work conceptually, but if they are optional because of "default" values, then you can have the class with optional fields extend from the one with mandatory fields, and just implement a constructor which calls a super constructor with the default values. For instance if
subClass
extendsparentClass
and the constructor of the parent class is two strings, the second of which has a "default" in the child class, something like the following could be done: