user18952345
user18952345

Reputation:

Using Template Method (Design Pattern) for differentiate fields

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?

Upvotes: 0

Views: 106

Answers (1)

Phoenix
Phoenix

Reputation: 982

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 extends parentClass 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:

public subClass extends parentClass {
    subClass(String arg1) {
        super(arg1, "default arg2");
    }
}

Upvotes: 0

Related Questions