My question relates to usage of delegation together with inheritance and dependency injection.
I have a MailerService class that requires a delegate in order to do its job.
Furthermore, I have a hierarchy of delegates with an abstraction: MailerServiceDelegate together with a number of implementations amongst others an EmailResetDelegate.
Here is the Spring class using the delegate:
@Service
public class MailerService {
private static final boolean IS_HTML = true;
private static final boolean MULTIPART = true;
private static final String ENCODING = "UTF-8";
...
private final JavaMailSender mailSender;
private MailerServiceDelegate mailerServiceDelegate;
public MailerService(...
JavaMailSender mailSender,
...) {
this.mailSender = mailSender;
}
public void setMailerServiceDelegate(MailerServiceDelegate mailerServiceDelegate) {
this.mailerServiceDelegate = mailerServiceDelegate;
}
public void sendMail(Object ...objects) {
try {
final Context ctx = new Context();
...
mailerServiceDelegate.setContext(ctx, objects);
final MimeMessage mimeMessage = mailSender.createMimeMessage();
...
mailSender.send(mimeMessage);
} catch (MessagingException | UnsupportedEncodingException e) {
throw new MailerException(e);
}
}
}
Here is the implementation for the delegate:
//As of now this is a plain class and not a spring dependency
public class EmailResetDelegate implements MailerServiceDelegate {
And the client:
@Service
public class Client {
private MailerService mailerService;
public Client(MailerService mailerService) {
this.mailerService = mailerService;
}
public void sendEmailAddressResetRequest(UserAccount userAccount, EmailReset emailReset) {
mailerService.setMailerServiceDelegate(new EmailResetDelegate());
mailerService.sendMail(userAccount, emailReset);
}
}
The trouble with the current design is that I have to set the delegate manually using the setMailerServiceDelegate method from the client. Also I am mixing dependency injection with manual instantiation. Can someone suggest a better design ?
Edit: Here is the diagram for the current design:

MailerServiceDelegatebe changed some when during the lifetime of aMailerServiceinstance?