oop - Create complex class with factory and builder
问题描述
background:
I build a class diagram for shopping on the net.
For creating a user interface with tow type (golden-User and silver-User) I use the factory pattern.
But the User class become to be very complex.
How can I create this class by bulider and on the other hand the ability to specify the user type such as the factory will remain on the class name (will help me to recognize which type is by polymorphism and not by if&else)
解决方案
装饰器模式是一个简单的解决方案:
public class Main {
public static void main(String[] args) {
User silverUser = new UserDecorator(new SilverUser("Kyriakos", "Georgiopoulos"));
User goldenUser = new UserDecorator(new GoldenUser("GoldenUser firstName", "GoldenUser lastName"));
User nullUser = new UserDecorator(null);
System.out.println(silverUser.firstName() + " " + silverUser.lastName() + " is " + silverUser.type());
System.out.println(goldenUser.firstName() + " " + goldenUser.lastName() + " is " + goldenUser.type());
System.out.println(nullUser.firstName() + " " + nullUser.lastName() + " is " + nullUser.type());
}
}
interface User {
String firstName();
String lastName();
String type();
}
class SilverUser implements User {
private final String firstName;
private final String lastName;
SilverUser(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String firstName() {
return firstName;
}
public String lastName() {
return lastName;
}
public String type() {
return "SilverUser ";
}
}
class GoldenUser implements User {
private final String firstName;
private final String lastName;
GoldenUser(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String firstName() {
return firstName;
}
public String lastName() {
return lastName;
}
public String type() {
return "GoldenUser ";
}
}
class UserDecorator implements User {
private final User user;
UserDecorator(User user){
this.user = user;
}
public String firstName() {
return user != null && user.firstName() != null && user.firstName().length() > 0 ?
user.firstName() : "";
}
public String lastName() {
return user != null && user.lastName() != null && user.lastName().length() > 0 ?
user.lastName() : "";
}
public String type() {
return user != null ? user.type() : "NullPointerException";
}
}
推荐阅读
- javascript - 如何正确阻止 bluebird promise.map
- swift - 现在 RxSwift 测试失败 .delay 已被引入
- php - 如何在不提交表单的情况下获取文件信息
- visual-studio-2017 - TestContext 属性为空
- list - 循环遍历python中的字典列表
- ios - 如何使容器视图中的表格视图不会在键盘弹出窗口中反弹?
- java - StringBuilder 中的多个 StringBuilder。值得吗?
- javascript - 如何从角度的Jquery函数内的输入字段中获取数据?
- asp.net-mvc - 将 Html 转换为 Pdf 时出现身份验证失败错误
- geometry - 传单:更容易选择圆形标记