![](/img/trans.png)
[英]use factory design pattern with subclass that has extra constructor arguments
[英]Subclass constructor with extra attributes
如果我有一個擴展了另一類“動物”的“狗”類,而動物類的構造函數帶有幾個屬性,如latinName,latinFamily等。我應該如何為狗創建構造函數? 我是否應該包括在Animal中找到的所有屬性以及在Dog中想要的所有其他屬性,例如:
public Animal(String latinName){
this.latinName = latinName;
}
public Dog(String latinName, breed){
super(latinName);
this.breed = breed;
}
實際的類具有比我在此處列出的屬性更多的屬性,因此,狗的構造函數變得相當長,讓我懷疑這是否是可行的方法或是否有更整潔的方法?
我應該包括在Animal中找到的所有屬性嗎?
那些對狗不是不變的,是的(一種或另一種;見下文)。 但是例如,如果Animal
具有latinFamily
,那么您就不需要Dog
擁有它,因為它始終是"Canidae"
。 例如:
public Animal(String latinFamily){
this.latinFamily = latinFamily;
}
public Dog(String breed){
super("Canidae");
this.breed = breed;
}
如果發現構造函數的參數數量不合理,則可以考慮使用Builder模式:
public class Dog {
public Dog(String a, String b, String c) {
super("Canidae");
// ...
}
public static class Builder {
private String a;
private String b;
private String c;
public Builder() {
this.a = null;
this.b = null;
this.c = null;
}
public Builder withA(String a) {
this.a = a;
return this;
}
public Builder withB(String b) {
this.b = b;
return this;
}
public Builder withC(String c) {
this.c = c;
return this;
}
public Dog build() {
if (this.a == null || this.b == null || this.c == null) {
throw new InvalidStateException();
}
return new Dog(this.a, this.b, this.c);
}
}
}
用法:
Dog dog = Dog.Builder()
.withA("value for a")
.withB("value for b")
.withC("value for c")
.build();
與構造函數的一長串參數相反,這使得更容易弄清哪個參數是哪個參數。 您將獲得清晰的好處(您知道withA
指定了“ a”信息, withB
指定了“ b”,等等),但沒有半建Dog
實例的危險(因為部分構造的實例是較差的做法) ; Dog.Builder
存儲信息,然后build
完成構造Dog
的工作。
如果Dog擴展了Animal,則是,您可能要繼續使用Animal的參數(因為狗的確是動物),並可能添加更多內容來區分狗和動物對象。
因此,一般而言,是的,您需要包括所有父類的參數。
也要考慮使用多個構造函數的可能性可能更短的參數列表。 Say Animal采用String type
的參數,該參數定義子類是哪種動物,對於Dog
,您不必每次都傳遞它。
public Dog (String name){
super("Dog", name);
}
如果我對所有這些內容都含糊不清,請務必告訴我,我將盡一切可能清除它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.