管理对象间关系 [英] Managing inter-object relationships

查看:65
本文介绍了管理对象间关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何编码对象的特殊情况?

How do you code special cases for objects?

例如,假设我正在编码一个rpg-有N = 5个类.矩阵中存在N ^ 2个关系,这些关系将确定角色A是否可以攻击(或使用能力M来)角色B(暂时忽略其他因素).

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).

我如何在OOP中编写代码而又不会在各处放置特殊情况?

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 )

我不确定if语句的内容,而是它

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

if ( CharacterA.CanDo( CharacterB ) )

或元类

if ( Board.CanDo( CharacterA, CharacterB ) )

何时CanDo函数应该依赖于ClassA和ClassB或带有ClassA/ClassB的属性/修饰符?

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

推荐答案

Steve Yegge在 awesome 博客文章中介绍了可用于处理属性"模式的内容.实际上,他使用它编写了一个RPG!

Steve Yegge has an awesome blog post about the Properties pattern that you could use handle this. In fact, he wrote an RPG using it!

http://steve-yegge.blogspot.com /2008/10/universal-design-pattern.html

您可能会说player1是type1,type1s可以攻击type2s,player2是type2,因此,除非特定的player1上存在替代",否则player1可以攻击player2.

You might say player1 is a type1 and type1s can attack type2s and player2 is a type2, so unless there is some "override" on the specific player1, player1 can attack player2.

这可以实现非常健壮和可扩展的行为.

This enables very robust and extensible behavior.

这篇关于管理对象间关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆