加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 更改类和对象. (其他aproachs?)

发布时间:2020-12-15 04:58:05 所属栏目:Java 来源:网络整理
导读:我有几种情况,我想这样做.这可能是一个例子: 考虑国际象棋游戏的可能实现.我们定义抽象类’Piece’和从它继承的类:’bishop”peon”塔”马”’女王’等 我们可能会让我们的peon即将到达棋盘的末端,并且可能需要一个调用该peon对象??的方法来将该对象的类更
我有几种情况,我想这样做.这可能是一个例子:

考虑国际象棋游戏的可能实现.我们定义抽象类’Piece’和从它继承的类:’bishop”peon”塔”马”’女王’等

我们可能会让我们的peon即将到达棋盘的末端,并且可能需要一个调用该peon对象??的方法来将该对象的类更改为“Queen”,“horse”或其他任何东西.

所以我的问题是,有没有办法在C或Java中做到这一点?如果没有,用其他语言?
此外,这种情况一般还有其他方法吗?

解决方法

您可以使用 decorator pattern或 strategy pattern.

有装饰:

interface ChessPiece {
    Set<Move> getPossibleMoves();
    Image getAppearance();
}

class Pawn implements ChessPiece {
    ...
}

class Decorator implements ChessPiece {
    ChessPiece decorated;

    public Decorator(ChessPiece decorated_) {
        this.decorated = decorated_;
    }

    @override
    Set<Move> getPossibleMoves() {
        Set<Move> result = decorated.getPossibleMoves();
        // alter result
        return result;
    }
}

需要时,使用Decorative实例替换Pawn实例.所以它仍然涉及用OpenSause’s答案中提到的另一个实例替换一个实例.

ChessPiece pawn = new Pawn;
...
pawn = new Decorated(pawn);

当你提前计划时,你可以使用策略它仍然没有真正改变类:

interface PossibleMovesStrategy {
    Set<Move> getPossibleMoves();
}

interface AppearanceStrategy {
    Image getAppearance();
}

class ChangingChessPiece extends ChessPiece {
    PossibleMovesStrategy posMoves;
    AppearanceStrategy appearance;

    @override
    Set<Move> getPossibleMoves() {
        return posMoves.getPossibleMoves();
    }

    @override
    Image getAppearance() {
        return appearance.getAppearance();
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读