请用C语言写一个Replace Type Code with State/Strategy重构代码示例
时间: 2024-03-14 22:45:49 浏览: 146
假设我们现在有一个电视类,其中包含了两种状态:开启和关闭。这个类使用一个布尔型变量来表示电视的状态,我们需要使用Replace Type Code with State/Strategy重构手法来改善这个类的设计。
重构前的代码如下:
```c
struct TV {
bool isOn;
int channel;
int volume;
};
void turnOnTV(struct TV* tv) {
tv->isOn = true;
printf("TV is turned on.\n");
}
void turnOffTV(struct TV* tv) {
tv->isOn = false;
printf("TV is turned off.\n");
}
void changeChannel(struct TV* tv, int channel) {
if (tv->isOn) {
tv->channel = channel;
printf("Channel is changed to %d.\n", channel);
} else {
printf("TV is turned off.\n");
}
}
void changeVolume(struct TV* tv, int volume) {
if (tv->isOn) {
tv->volume = volume;
printf("Volume is changed to %d.\n", volume);
} else {
printf("TV is turned off.\n");
}
}
```
重构后的代码如下:
```c
struct TVState;
struct TV {
struct TVState* state;
int channel;
int volume;
};
struct TVState {
void (*turnOn)(struct TV* tv);
void (*turnOff)(struct TV* tv);
void (*changeChannel)(struct TV* tv, int channel);
void (*changeVolume)(struct TV* tv, int volume);
};
struct TVOnState {
struct TVState state;
};
struct TVOffState {
struct TVState state;
};
void turnOnTV(struct TV* tv);
void turnOffTV(struct TV* tv);
void changeChannel(struct TV* tv, int channel);
void changeVolume(struct TV* tv, int volume);
void TVOnState_turnOn(struct TV* tv) {
printf("TV is already on.\n");
}
void TVOnState_turnOff(struct TV* tv) {
tv->state = (struct TVState*)malloc(sizeof(struct TVOffState));
tv->state->turnOn = turnOnTV;
tv->state->turnOff = turnOffTV;
tv->state->changeChannel = changeChannel;
tv->state->changeVolume = changeVolume;
printf("TV is turned off.\n");
}
void TVOnState_changeChannel(struct TV* tv, int channel) {
tv->channel = channel;
printf("Channel is changed to %d.\n", channel);
}
void TVOnState_changeVolume(struct TV* tv, int volume) {
tv->volume = volume;
printf("Volume is changed to %d.\n", volume);
}
void TVOffState_turnOn(struct TV* tv) {
tv->state = (struct TVState*)malloc(sizeof(struct TVOnState));
tv->state->turnOn = turnOnTV;
tv->state->turnOff = turnOffTV;
tv->state->changeChannel = changeChannel;
tv->state->changeVolume = changeVolume;
printf("TV is turned on.\n");
}
void TVOffState_turnOff(struct TV* tv) {
printf("TV is already off.\n");
}
void TVOffState_changeChannel(struct TV* tv, int channel) {
printf("TV is turned off.\n");
}
void TVOffState_changeVolume(struct TV* tv, int volume) {
printf("TV is turned off.\n");
}
void turnOnTV(struct TV* tv) {
tv->state->turnOn(tv);
}
void turnOffTV(struct TV* tv) {
tv->state->turnOff(tv);
}
void changeChannel(struct TV* tv, int channel) {
tv->state->changeChannel(tv, channel);
}
void changeVolume(struct TV* tv, int volume) {
tv->state->changeVolume(tv, volume);
}
```
通过Replace Type Code with State/Strategy重构手法,我们将电视类分成了两个状态类,分别表示开启和关闭状态,每个状态类都包含了一个TVState结构体,用来表示电视状态的行为。同时,我们将原来的四个函数都改为了通过状态类指针调用状态类的相应函数来完成电视的操作。这样做的好处是,可以使代码更加易于扩展和维护,并且可以避免使用大量的if语句来判断电视的状态。
阅读全文