Managing inter-object relationships

2019-02-20 02:35发布

How do you code special cases for objects?

For example, let's say I'm coding an rpg - there are N = 5 classes. There are N^2 relationships in a matrix that would determine if character A could attack (or use ability M on) character B (ignoring other factors for now).

How would I code this up in OOP without putting special cases all over the place?

Another way to put it is, I have something maybe

ClassA CharacterA;
ClassB CharacterB;

if ( CharacterA can do things to CharacterB )

I'm not sure what goes inside that if statement, rather it be

if ( CharacterA.CanDo( CharacterB ) )

or a metaclass

if ( Board.CanDo( CharacterA, CharacterB ) )

when the CanDo function should depend on ClassA and ClassB, or attributes/modifiers with ClassA/ClassB?

标签: oop
7条回答
萌系小妹纸
2楼-- · 2019-02-20 03:24

In response to your edit of your question, you'll want to look into polymorphism. I personally would have the cando() function be a part of the Board, then, depending on the two classes passed in, the Board would call the appropriate function and return the result (of battle, of seeing, so on and so forth).

If you're doing this in java an enum/interface to go along with your Game Board would be a very clean way of approaching this problem.

查看更多
登录 后发表回答