假设有这样的设计,
class SportEquipment {
String type; // ball or shoe
BallInfo ball;
ShoeInfo shoe;
}
class BallInfo {
int radius;
bool isNew;
String getDetail() {
if(this.isNew) {
return "This is a new " + this.radius + " ball."
}
return "This is a " + this.radius + " ball."
}
}
class ShoeInfo {
int length;
bool isNew;
String getDetail() {
if(this.isNew) {
return "This is a new " + this.length + " shoe."
}
return "This is a " + this.length + " shoe."
}
}
要重构的方法为,
public static getDetail(SportEquipment eq) {
switch(eq.type) {
case "ball":
return eq.ball.getDetail();
break;
case "shoe":
return eq.shoe.getDetail();
break;
}
}
如果采用策略模式,
class SportEquipment {
String type; // ball or shoe
BallInfo ball;
ShoeInfo shoe;
DetailStrategy detailStrategy;
}
interface DetailStrategy {
String getDetail();
}
class BallDetailStrategy implements DetailStrategy {
String getDetail() {
if(this.isNew) {
return "This is a new " + this.radius + " ball."
}
return "This is a " + this.radius + " ball."
}
}
那么,BallDetailStrategy中如何拿到radius和isNew两个变量呢?如果采用参数传入的方式,则要求策略中所有的getDetail参数列表都一致,这显然是很难接受的。如果将这两个也同样作为BallDetailStrategy的成员变量,那如何保证他们的值与BallInfo中的一致?
对我而言,我认为更好的重构方法是使用继承产生Ball和Shoe类。
class SportEquipment {
bool isNew;
String getDetail() {
return "This is a SportEquipment."
}
}
class Ball extends SportEquipment {
int radius;
String getDetail() {
if(this.isNew) {
return "This is a new " + this.radius + " ball."
}
return "This is a " + this.radius + " ball."
}
}
class Shoe extends SportEquipment {
int length;
String getDetail() {
if(this.isNew) {
return "This is a new " + this.length + " shoe."
}
return "This is a " + this.length + " shoe."
}
}
则实现可以重构为:
public static getDetail(SportEquipment eq) {
return eq.getDetail();
}
但这似乎有悖于策略模式“少用继承多用组合”的原则,因此抛出这个问题,希望能有方案能够使用策略模式将这段代码重构。