我必须为我的网站上显示的登录对话框编写测试,但是此登录对话框有两个,只有两个访问点。理想情况下,我的页面对象应反映对此登录对话框的受限访问。
clickLogin
上的Header
,LoginDialog
会弹出
当您postComment
Article
时,您还没有登录(我们假设您不是为了简单起见),{{弹出{1}}。
以下是代码中的内容:
LoginDialog
我提出了解决这个问题的方法。 new LoginDialog().login(); // shouldn't be allowed
new Header().clickLogin().login(); // should be allowed
new Article().postComment().login() // should be allowed
只有两个构造函数,它们都接受一个只能在LoginDialog
或Header
中构造的对象。
Article
我的问题是这是否是现有模式,如果是,它的名字是什么?如果它不是,它会有什么好名字?
答案 0 :(得分:1)
我认为这是确保只有Header
或Article
可以创建LoginDialog
的简单方法:
public class LoginDialog {
private LoginDialog() {
... code to construct
}
public interface Constructor {
LoginDialog newLoginDialog();
}
private static class ConstructorImpl implements Constructor {
public LoginDialog newLoginDialog() {
return new LoginDialog();
}
}
private static ConstructorImpl constructor;
static {
constructor = new ConstructorImpl();
Header.provideLoginDialogConstructor(constructor);
Article.provideLoginDialogConstructor(constructor);
}
}
并在Header
和Article
中提供公开provideLoginDialogConstructor
方法:
private static LoginDialog.Constructor constructor;
public static void provideLoginDialogConstructor(LoginDialog.Constructor constructor) {
Header.constructor = constructor; // or Article.constructor
}
当这些类需要构建LoginDialog
:
if (!loggedIn()) {
return constructor.newLoginDialog();
} else {
return null;
}
由于LoginDialog
类决定哪些类使其私有对象构造LoginDialog
,因此另一个类无法使用常规方法获得构造一个类的能力[可能使用反射是一种棘手的方式]。
注意:我没有测试过这个。