[英]How to create a Class when its attributes are dynamic & variable in Java, C++ or any Object-Oriented Language?
好吧,在面向對象語言(OOL)中,創建類時我們經常知道它的所有屬性。 例如,Item類應具有固定屬性(顏色,型號,品牌,價格)。 所以我們只是:
public Class Item{
private String color;
private String model;
//etc more attribute here
//& set & get method for all attributes
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
但是,如果所有屬性都是動態的呢? 例如,在1家公司中,他們的商品屬性可能是顏色,品牌,但在其他公司,他們沒有顏色和品牌屬性,但有寬度,高度,尺寸......
如何創建一個接受Java,C ++或任何OOL中的動態屬性的類?
如何創建一個接受Java,C ++或任何OOL中的動態屬性的類?
這實際上取決於你想如何使用它。 在許多情況下,您可以重新編寫類以包含某種類型的動態增長集合,例如C ++中的std::map
或Java中的Map
(或Dictionary
)。
這允許您使用在運行時選擇的鍵為每個實例創建和添加任意數據。
。凈
我首先要分析你的要求,這不是你經常會看到的。 也許你的課程沒有正確設置。
選項可以存儲在詞典中
使用新版本的.NET,他們擁有動態關鍵字 ,可以幫助創建ViewBag等動態屬性。
您還可以使用Reflection Emit或ICustomTypeDescriptor進行反射 。
我認為這是你應該使用繼承的一個主要例子。 以下面的例子為例:
Abstract Class Item
{
// This class will never be instantiated, but it can hold
// things that are common to all Items, such as sale price.
private int price;
public int getPrice() { return price; }
// etc.
}
Class VendorOneItem : Item
{
// This class gets 'price' and 'getPrice' by default,
// since it inherits from Item
private String color;
private String model;
// etc.
}
Class VendorTwoItem : Item
{
// This class also gets 'price' and 'getPrice'
private Double width;
private Double height;
// etc.
}
我知道這不會采取動態讀取數據的路線,但這是我腦海中更明確的方式。 即使您以某種方式能夠動態讀取所有數據,如何處理該數據? 正如里德指出的那樣,你可以使用某種詞典或某種地圖,這是合理的。 您的數據可能如下所示:
{"key": value}
{"Color": "blue"}
{"Price": 9.99}
{"Model": 1234-567-890}
要么
{"Price": 129.99}
{"Height": 12.750}
{"Width": 8.55}
但是,您只是將您的問題從編譯時的屬性轉移到在運行時計算屬性。 為了處理這兩個代碼,代碼的某些部分必須知道如何處理"Width"
和"Height"
,並且還需要知道如何處理"Model"
和"Color"
。 反思是一種可能性,但這些項目所描述的內容從根本上是不同的,並且幾乎不可能推廣處理其細節的算法。
對於我來說,從基類開始並繼承了知道細節的類似乎要容易得多。 您甚至可以在代碼中創建Item
集合,而無需知道每個對象的確切類型。
在C ++中:
std::vector<*Item> items;
items.push_back(new VendorOneItem());
items.push_back(new VendorTwoItem());
現在說你將它添加到Item
類:
virtual public void ProcessItem()=0; //This will throw compilation errors
// if all derived classes don't define ProcessItem
現在,回到定義矢量items
位置,您可以這樣做:
items[0].ProcessItem();
items[1].ProcessItem();
並且兩個對象是不同類的實例化沒有區別。 它們都必須實現ProcessItem,因此確定調用哪些函數沒有問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.