所以我一直对D感兴趣一段时间了,我前段时间对它感到困惑。我已经开始重新审视它,并且我确实喜欢它试图实现的目标,但是我对我的一个最喜欢的C++设计选项非常虚惊......。私有继承和非虚拟接口
我喜欢这种设计,它允许在继承层次的“顶部”进行事前和事后条件检查,记录和资源管理。这允许设计者指定一组相关类的所有通用功能,并将类的可定制部分分解为非常小的功能。它还减少了需要写入子类的功能数量。另外,因为虚拟扩展点是私有的,所以它不会污染接口,或者允许用户直接调用实现特定的函数(这非常关键)。
有没有办法在D中实现这一点?
C++示例(未经测试,未编译...仅用于说明)。
class Radio{
public:
Radio(std::string id, Station defaultStation, RxChip chip)
:defaultStation(defaultStation),
id(id),
chip(chip){
}
void turnOn() {
log.trace("Radio turned on: id:[%s]", id.c_str());
doEnableRx();
doPostEnable();
setToStation(defaultStation);
}
void turnOff(){
log.trace("Radio turned off: id:[%s]", id.c_str());
doDisableRx();
doPowerOff();
}
void tune(){
log.trace("Tuning");
findAllStations();
}
void setToStation(Station target){
logStationChange(target);
doSetRxChipPassFilter(target);
}
void setChip(RxChip chip) {
rxChip = chip;
}
RxChip getChip() {
return rxChip;
}
private:
// doesn't start with "do" as this is considered a "normal" virtual function.
virtual void findAllStations(){
chip.setFrequency(chip.getLowFreq());
setChipToNextTunedPoint();
Station stat(chip.getFrequency(), tunedStations.size());
tunedStations.push_back(stat);
}
virtual bool setChipToNextTunedPoint() {
if(chip.isTuned()) {
while(isTuned && chip.getFrequency() < chip.getHighFreq())
chip.incrementFreq();
}
while(!chip.isTuned() && chip.getFrequency() < chip.getHighFreq())
chip.incrementFreq();
return chip.isTuned();
}
// "do" functions are considered mandatory extension points for sub-classes
virtual void doEnableRx() = 0;
virtual void doPostEnable() = 0;
virtual void doDisableRx() = 0;
virtual void doPowerOff() = 0;
virtual void doSetRxChipPassFilter(Station target) = 0
{
//default implementation but it must be specified for use by sub-class.
chip.setFrequency(target.getLowFreq());
while(!chip.isTuned() && chip.getFrequency() < station.getHighFreq()) {
chip.incrementFreq();
}
}
Station defaultStation;
std::vector<Station> tunedStations;
RxChip chip;
}
任何人都知道为什么语法突出显示对代码示例不起作用? – Dennis
我不认为我曾经见过在stackoverflow上的任何D代码中的语法突出显示。 –