问题
I'm trying to build a Monte Carlo object class and am wondering about the best way to design the relevant classes.
The structure of the object (called Entity) contains name, description AND a Distribution type which can be of a few different types eg. Normal, Fixed Integer, Triangle etc. The Distribution class is (or might be) a superclass of the specific distributions eg. Normal.
So, I have
class Entity {
public:
string name;
Distribution* dsn; // superclass. Can this be done?
}
class Distribution {
public:
string Type;
double Sample(void)=0; // To be implemented in subclasses, same function sig.
}
Then an example of the actual distribution might be
class NormalDistribution : public Distribution {
public:
setMean(double mean);
setStdDeb(double stddev);
double Sample(void);
}
FixedDistribtion would also be a subclass of Distribution and implement different methods eg. setWeights, setValues as well as Sample of course.
I was hoping to write code like this
Entity* salesVolume = new Entity();
salesVolume->setDistribution(NORM);
salesVolume->dsn->setMean(3000.0:
salesVolume->dsn->setStdDev(500.0);
Entity* unitCost = new Entity();
unitCost->dsn->setWeights( .. vector of weights);
unitCost->dsn->setValues( .. vector of values) ;
then
loop
sv = salesVolume->sample();
uc = unitCost->sample();
endloop
What I'd like to do is define a Distribution (superclass) in Entity, then use its subclass methods which vary depending on distribution type eg. setMean. The distribution object in Entity would be determined at run-time eg. if (distnType == NORM) dsn = new NormalDistribution; if (distnType == FIXED) dsn = new FixedDistribution;
Is this possible in C++, or have completely lost the concept of Polymorphism? I'm having trouble defining the dsn variable as the superclass, then narrowing down to an actual distribution at run-time. A (simpler) way would be to define Entity without a Distribution, and use Distribution's on their own, without attachment to Entity.
Thanks guys
回答1:
I think you want to do it like this:
Entity* salesVolume = new Entity;
{
NormalDistribution *dsn = new NormalDistribution;
dsn->setMean(3000.0);
dsn->setStdDev(500.0);
salesVolume->setDistribution(dsn);
}
Entity* unitCost = new Entity;
{
FixedDistribution *dsn = new FixedDistribution;
dsn->setWeights( .. vector of weights);
dsn->setValues( .. vector of values) ;
unitCost->setDistribution(dsn);
}
There are other possibilities, but I think this most closely represents your original design.
回答2:
Posting own solution based on answers by pg1989 and Robert Cooper.
To define different types of Distribution, templates will be used. The visitor pattern can be used to solve this problem of wanting different implementations of a master class.
来源:https://stackoverflow.com/questions/10712659/c-class-design-for-monte-carlol-simulation