I've done an exercise with Facade and Builder Pattern combined. Root is a simple LoginService-Interface
public interface LoginService {
void addUser(int id, String username, String password, String mail);
boolean login(String username, String password);
void logout();
}
Other classes are a LoginServiceDecorator and some concrete Decorators. Finally a Builder, who is tested this way:
service = new LoginServiceBuilder().withValidation().withEncoding().withLogging().toService();
with some test cases.
All was fine, until the implementation of the toService()-method, where I had no real good idea how to implement. I show were I stucked:
LoginServiceBuilder
public class LoginServiceBuilder {
/*
* Note that the decorators must be connected in reverse order of the
* builder method invocations. So we use a stack to hold all decorator
* instances and at the end of the building process, we connect the
* decorators in the right order.
*/
private Stack<LoginServiceDecorator> stack = new Stack<LoginServiceDecorator>();
public LoginServiceBuilder() {
}
public LoginServiceBuilder withValidation() {
stack.push(new ValidationDecorator(new LoginServiceImpl()));
return this;
}
public LoginServiceBuilder withEncoding() {
stack.push(new EncodingDecorator(new LoginServiceImpl()));
return this;
}
public LoginServiceBuilder withLogging() {
stack.push(new LoggingDecorator(new LoginServiceImpl()));
return this;
}
public LoginService toService() {
// Here I stucked
}
Well, finally I gave up, and took a look at the solution:
public LoginService toService() {
LoginService service = new LoginServiceImpl();
while (!stack.isEmpty()) {
LoginServiceDecorator decorator = stack.pop();
decorator.setService(service); // just to set the private member there (Type of the Interface as shown at beginning)
service = decorator;
}
return service;
}
Why I'm still scratching my neck is following: For me it looks like when the Stack is empty, the service is simple the last one it caught. Maybe someone could explain me with soft words, why I should have all decorators now.
Thanks much in advance
Aucun commentaire:
Enregistrer un commentaire