2013-08-18 29 views
0

考虑接下来的一段代码:更换条件有多态性,但如何做到这一点

class NumberWrapper { 
    boolean negative; 
    void setNegativeTrue(boolean isNegative) { 
     negative = isNegative; 
    } 

    void negateNumber(int x) { 
     if (negative) { 
      x = x * -1; 
     } else { 
     x = Math.abs(x); 
     } 
     return x; 
    } 
} 

在这样的代码,怎么可能使用多态?

+2

这是一门功课?您想应用什么多态性概念?坦率地说,目前的代码并不是一个好例子。请为您的方法提供一个更好的名称。 'calculate'?它是什么计算的?给一个描述性的名字。 –

+0

这是一个很好的多态教程:http://www.tutorialspoint.com/java/java_polymorphism.htm。正如Rohit Jain所评论的,您提供的代码并不适合转换为多态。 –

回答

2
public enum UnaryOperator { 

    NEGATE { 
     @Override 
     public int apply(int x) { 
      return -x; 
     } 
    }, 
    ABS { 
     @Override 
     public int apply(int x) { 
      return Math.abs(x); 
     } 
    } 

    public abstract int apply(int x); 
} 

class Foo { 
    private UnaryOperator operator = UnaryOperator.ABS; 

    void setUnaryOperator(UnaryOperator operator) { 
     this.operator = operator; 
    } 

    void calculate(int x) { 
     return operator.apply(); 
    } 
} 
+0

+1,尽管对于看起来像作业的东西肯定太多了。不过,喜欢使用枚举! –

+0

枚举可以被接口或抽象类所替代。 –

3

,可随时更换boolean参数,这导致具有两个不同的类,每个类实现一个路径中的两个不同的代码路径。

abstract class Foo { 
    abstract void calculate(int x); 
} 

class NormalFoo extends Foo { 
    void calculate(int x) { 
     x = Math.abs(x); 
     return x; 
    } 
} 

class NegativeFoo extends Foo { 
    void calculate(int x) { 
     x = x * -1; 
     return x; 
    } 
} 

相反的setNegativeTrue你创建这些类之一,从而代替条件与多态性

相关问题