我想创建一个包含状态成员和卡尔曼滤波方法的类"track"。我喜欢使用不同类型的卡尔曼滤波器。由于每个卡尔曼滤波器的接口是相同的,我想,我使用策略模式。我遇到的问题是,我还喜欢在改变策略时动态地改变状态成员。因为所使用的状态必须适合适当的卡尔曼滤波器。
下面是一个简化的代码片段:class CVState : public StateBase { ... };
class CAState : public StateBase { ... };
卡尔曼底:
class KalmanStrategy {
public:
virtual void Prediction(StateBase* state) = 0;
virtual void Correction(StateBase* state) = 0;
virtual ~KalmanStrategy(){}
protected:
KalmanStrategy() {}
};
卡尔曼子类:
class KalmanCV : public KalmanStrategy {
public:
KalmanCV(){}
void Prediction(StateBase* state) {...}
void Correction(StateBase* state) {...}
};
class KalmanCA : public KalmanStrategy {...}
这里是我的Track Class,它包含一个状态成员,它必须适合于Kalman。
class track {
public:
track() {
Kalman_ = new KalmanCV;
}
void ChangeStateModel(KalmanStrategy* K) {
Kalman_ = K;
//state_ = new CVState; // the state in track has to fit to the Kalman Class
// in this Case KalmanCV
}
private:
KalmanStrategy* Kalman_;
StateBase* state_;
}
是否有一种方法,当改变策略时,也改变state__ ?
你可以这样做:
struct KalmanModelCV {
typedef KalmanCV filter_t;
typedef StateCV state_t;
};
class track {
public:
track() {
filter_ = NULL;
state_ = NULL;
}
typedef<typename Model>
void ChangeModel() {
delete filter_;
delete state_;
filter_ = new typename Model::filter_t();
state_ = new typename Model::state_t();
}
private:
KalmanStrategy* filter_;
StateBase* state_;
};
track t;
t.ChangeModel<KalmanModelCV>();
但是,如果每个过滤器都需要自己特定的状态类型,那么最好将状态的创建移到过滤器类中。例如:
class KalmanStrategy {
public:
virtual void Prediction(StateBase* state) = 0;
virtual void Correction(StateBase* state) = 0;
virtual StateBase* CreateState() = 0;
virtual ~KalmanStrategy(){}
protected:
KalmanStrategy() {}
};
class KalmanCV : public KalmanStrategy {
public:
KalmanCV(){}
void Prediction(StateBase* state) {...}
void Correction(StateBase* state) {...}
StateBase* CreateState() { return new StateCV(); } // KalmanCV only works with StateCV!
};
class track {
public:
track() {
filter_ = NULL;
state_ = NULL;
}
void ChangeModel(KalmanStrategy* strat) {
delete filter_;
delete state_;
filter_ = strat;
state_ = strat->CreateState();
}
private:
KalmanStrategy* filter_;
StateBase* state_;
};