【发布时间】:2016-04-07 17:38:53
【问题描述】:
我已经完成了一个结合 Facade 和 Builder Pattern 的练习。 Root 是一个简单的 LoginService-Interface
public interface LoginService {
void addUser(int id, String username, String password, String mail);
boolean login(String username, String password);
void logout();
}
其他类是 LoginServiceDecorator 和一些具体的装饰器。最后是一个经过这种方式测试的 Builder:
service = new LoginServiceBuilder().withValidation().withEncoding().withLogging().toService();
一些测试用例。
一切都很好,直到toService()-方法的实施,我不知道如何实施。我显示我是否被卡住了:
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
}
嗯,最后还是放弃了,看看解决办法:
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;
}
为什么我仍然在抓挠我的脖子如下:对我来说,看起来当 Stack 为空时,服务很简单,最后一个它捕获的服务。也许有人可以用温和的话解释我,为什么我现在应该拥有所有装饰器。
非常感谢
【问题讨论】:
标签: java design-patterns decorator builder