幕后的Facade和Builder Pattern

时间:2016-04-07 17:38:54

标签: java design-patterns decorator builder

我已经完成了与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是空的时候,服务很简单,它抓到的最后一个。也许有人可以用温柔的话语来解释我,为什么我现在应该拥有所有装饰师。

非常感谢提前

1 个答案:

答案 0 :(得分:1)

装饰器的作用是动态地添加对象的行为。 这就是他们实现相同界面的原因。

你应该为一个添加的行为设置一个装饰器。 这就是你创建一堆装饰器的原因

decorator.anOperation()应执行decoratedObject.anOperation() 通过使用继承,您可以替换装饰而不是装饰对象。 这就是你service = decorator的原因。 在您的示例中,您通过关联的装饰器替换您的服务(decoratedObject),然后在装饰对象上应用下一个装饰器。

在堆栈的末尾,你有一个“fullDecoratedObject”。

有关详细说明,我觉得这个网站很有用http://www.dofactory.com。实现在C#中,但它可以在Java中轻松转换。观看此页面:http://www.dofactory.com/net/decorator-design-pattern

希望这个帮助

相关问题