【问题标题】:Facade and Builder Pattern behind the scenes幕后的立面和建造者模式
【发布时间】: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


    【解决方案1】:

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

    您应该为一种添加行为使用一个装饰器。 这就是你创建一堆装饰器的原因

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

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

    更多解释,我发现这个网站很有用http://www.dofactory.com。该实现在 C# 中,但在 Java 中很容易转换。观看此页面:http://www.dofactory.com/net/decorator-design-pattern

    希望有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多