Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 动态生成器模式_Java_Polymorphism_Builder - Fatal编程技术网

Java 动态生成器模式

Java 动态生成器模式,java,polymorphism,builder,Java,Polymorphism,Builder,下面是基本的构建器模式 enum AccountType { BASIC,PREMIUM; } class AccountBuilder { private AccountBuilder(Builder builder) {} private static class PremiumAccountBuilder extends Builder { public PremiumAccountBuilder () {

下面是基本的构建器模式

enum AccountType {
     BASIC,PREMIUM;
}


class AccountBuilder {  
     private AccountBuilder(Builder builder) {}

     private static class PremiumAccountBuilder extends Builder {
           public PremiumAccountBuilder () {
              this.canPost = true;
           }

           public PremiumAccountBuilder image(Image image) {
               this.image = image;
           }
     }

     public static class Builder {
            protected String username;
            protected String email;
            protected AccountType type;
            protected boolean canPost = false;
            protected Image image;

            public Builder username(String username) {
                this.username = username;
                return this;
            }

            public Builder email(String email) {
                this.email = email;
                return this;
            }

            public Builder accountType(AccountType type) {
                this.type = type;
                return (this.type == AccountType.BASIC) ? 
                        this : new PremiumAccountBuilder();
            }

            public Account builder() {
                return new Account (this.name,this.email,this.type, this.canPost, this.image);
            }

     } 
}
因此,premium帐户基本上覆盖了canPost并可以设置图像

我不确定我是否能做像这样的事情

Account premium = new AccountBuilder.Builder().username("123").email("123@abc.com").type(AccountType.PREMIUM).image("abc.png").builder();
就像在
类型
方法调用之后,如果是高级帐户,那么我可以进行
图像
方法调用


它给了我一个错误,因为它无法识别和找到图像方法。我不确定这是否是正确的方法,或者有更好的方法吗?

accountType
返回类型为
Builder
的对象,该对象没有
图像
方法。一种可能的解决方案是向
Builder
类添加一个
image
方法,该方法只忽略
image
,然后当
premiumbulder
方法可以对
image
执行一些有用的操作时,它就会被
image
方法覆盖;另一种方法是将
图像
传递到
accountType
方法中,然后该方法负责将
图像
传递给
PremiumBuilder

@user1389813,在这种情况下,将
图像
传递给重载的
accountType
方法;或者将
Image
作为字段或方法包含在
AccountType
类中,以便
AccountType
方法可以检索它并将其传递给
premiumbulder
构造函数。您所说的重载AccountType方法是什么意思?在这种情况下,如何设置映像?@user1389813您可以有多个
accountType
方法,在这种情况下
accountType(accountType类型)
accountType(accountType类型,映像映像)
;第二个方法的实现将
image
传递给
premiumbulder
构造函数