gpt4 book ai didi

c++ - 使用策略模式改变方法及其关联状态

转载 作者:太空狗 更新时间:2023-10-29 21:43:33 25 4
gpt4 key购买 nike

我想创建一个包含状态成员和卡尔曼滤波器方法的“track”类。我喜欢使用不同类型的卡尔曼滤波器。由于每个卡尔曼滤波器的接口(interface)都是相同的,我想,我使用策略模式。我遇到的问题是,我也喜欢在更改策略时动态更改状态成员。因为使用的状态必须适合适当的卡尔曼滤波器。

这里是一个简化的代码片段:

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 {...}

这里是我的轨道类,它包含一个状态成员,必须适合卡尔曼。

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_;
};

关于c++ - 使用策略模式改变方法及其关联状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22660280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com