[英]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.