使用工厂设计模式进行重构

时间:2014-02-10 16:59:33

标签: design-patterns

我在重新分解旧代码方面遇到了一些麻烦,这是一个学校作业所以...... 我计划使用工厂设计模式或策略,无论如何我不确定如何在这种特定情况下使用它们:

public void sunk(int i, int j)
{
    if(map[i][j]==hit)
    {

    //if the hit is not on an edge
    if(i<9 && i>0 && j<9 && j>0)
    {

        //dec above if odd
        if(map[i-1][j]!= hit && map[i-1][j]%2==1)
        {
            //if(map[i-1][j]==13)
            map[i-1][j]= map[i-1][j] -9;
        }

        //dec above if even
        if(map[i-1][j]!= hit && map[i-1][j]%2==0)
        {
            map[i-1][j]= map[i-1][j] -2;
        }

        //dec below if odd
        if(map[i+1][j]!= hit && map[i+1][j]%2==1)
        {
            map[i+1][j]= map[i+1][j] -9;
        }

        //dec below if even
        if(map[i+1][j]!= hit && map[i+1][j]%2==0)
        {
            map[i+1][j]= map[i+1][j] -2;
        }

        //dec left if even
        if(map[i][j-1]!= hit && map[i][j-1]%2==0)
        {
            map[i][j-1]= map[i][j-1] -4;
        }

        //dec left if odd
        if(map[i][j-1]!= hit && map[i][j-1]%2==1)
        {
            map[i][j-1]= map[i][j-1] -9;
        }

        //dec right if even
        if(map[i][j+1]!= hit && map[i][j+1]%2==0)
        {
            map[i][j+1]= map[i][j+1] -4;
        }

        //dec right if odd
        if(map[i][j+1]!= hit && map[i][j+1]%2==1)
        {
            map[i][j+1]= map[i][j+1] -9;
        }
    }

然后我继续,因为我有很多if-else语句,我正在考虑使用上述模式。 帮助

2 个答案:

答案 0 :(得分:0)

我不确定这两种模式对你有帮助。

Factory将用于根据输入参数实例化对象(或子类集)的不同子类。

Strategy将用于替换运行时中类的行为。

在不了解上述代码试图实现的内容的情况下,很难提出建议。对于上面这样的代码,可以封装到查找表中,这将为您提供简明的实现(巨大的?)可读性。

答案 1 :(得分:0)

你可以在那里制定策略。首先,从策略的界面开始。我不知道你使用的是哪种语言,所以我将使用类似java的语言。

interface HitStrategy {
    bool AppliesTo(map, i, j);
    void Apply(map,i,j);
}

每个类都将实现不同的if块:

class DecRightIfOdd implements HitStrategy { 
    public bool AppliesTo(map, i, j){
        return map[i][j+1]!= hit && map[i][j+1]%2==1;
    }

    public void Apply(map,i,j){
         map[i][j+1]= map[i][j+1] -9;
    }
}

然后在您的代码中,您可以获得HitStrategy列表并找到适用于地图和位置的列表,然后调用Apply方法。

那么,为什么拥有一堆ifs会更好?你可以使用继承。在你的例子中,你有两个Dec Right,一个用于Odd,一个用于even。你可以这样做:

abstract class DecRight implements HitStrategy { 
    public bool AppliesTo(map, i, j){
        return map[i][j+1]!= hit;
    }
    public abstract Apply(map,i,j);
}

class DecRightIfOdd inherits DecRight { 
    public bool AppliesTo(map, i, j){
        return base(map,i,j) && map[i][j+1]%2==0;
    }

    public void Apply(map,i,j){
         map[i][j+1]= map[i][j+1] -4;
    }
}

class DecRightIfEven inherits DecRight { 
    public bool AppliesTo(map, i, j){
        return base(map,i,j) && map[i][j+1]%2==1;
    }

    public void Apply(map,i,j){
         map[i][j+1]= map[i][j+1] -9;
    }
}

希望它有所帮助。