在子类或超类中设计模式验证

时间:2015-08-27 19:27:54

标签: java design-patterns

我有以下结构。

import java.awt.*;

public class Enemy {
static int x = -100;
static int y = -100;

private boolean level2 = false;
private boolean level3 = false;
private boolean level4 = false;
private boolean level5 = false;
private boolean level6 = false;
private boolean level7 = false;
private boolean level8 = false;
private boolean level9 = false;
private boolean level10 = false;
Player player;

public Enemy(Player player) {this.player = player;}

public void update(){
    if(player.getX() < x){
        x -= 2;
    }
    if(player.getX() > x){
        x += 2;
    }
    if(player.getY() > y){
        y += 2;
    }
    if(player.getY() < y){
        y -= 2;
    }       
}

public void scoreMethod(){
    if(GameClass.score == 500){
        level2 = true;
    }
    if(GameClass.score == 1000){
        level3 = true;
    }
    if(GameClass.score == 1500){
        level4 = true;
    }
    if(GameClass.score == 2000){
        level5 = true;
    }
    if(GameClass.score == 2500){
        level6 = true;
    }
    if(GameClass.score == 3000){
        level7 = true;
    }
    if(GameClass.score == 3500){
        level8 = true;
    }
    if(GameClass.score == 4000){
        level9 = true;
    }
    if(GameClass.score == 4500){
        level10 = true;
    }
}

public void paint(Graphics g){
    g.setColor(Color.ORANGE);
    g.fillRect(x, y, 20, 20); //THE ACTUAL SPAWNING OF ONE ENEMY
    if(level2)
        g.fillRect(x, y, 20, 20); //HERE SHOULD SPAWN THE SECOND ONE(I TRIED)
    if(level3)
        g.fillRect(x, y, 20, 20);
    if(level4)
        g.fillRect(x, y, 20, 20);
    if(level5)
        g.fillRect(x, y, 20, 20);
    if(level6)
        g.fillRect(x, y, 20, 20);
    if(level7)
        g.fillRect(x, y, 20, 20);
    if(level8)
        g.fillRect(x, y, 20, 20);
    if(level9)
        g.fillRect(x, y, 20, 20);
    if(level10)
        g.fillRect(x, y, 20, 20);
}

在T1DynamoDBDao中复制验证规则是否有意义?

2 个答案:

答案 0 :(得分:2)

不,您不仅可以多次验证输入,还违反了DRY原则。

一个选项是让私人或受保护的成员在验证参数后执行实际工作:

class Base {
    public final Object get( String arg )
    {
        if( !validate( arg ) )
        {
           //throw?
        }

        return get_validated( arg );
    }

    protected Object get_validated( String arg )
    {
        // do work
    }
}

public class Derived extends Base
{
    protected Object get_validated( String arg )
    {
       // do work
       // maybe super.get_validated( arg );
    }
}

答案 1 :(得分:2)

因为T1DynamoDBDao是DynamoDBDao的一个子级,它可以从supercalss访问所有公共方法。就个人而言,我不会复制它。