关于策略模式重构代码的问题

假设有这样的设计,

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();
}

但这似乎有悖于策略模式“少用继承多用组合”的原则,因此抛出这个问题,希望能有方案能够使用策略模式将这段代码重构。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容