我设计我的游戏应用程序并在OOP设计中遇到一些麻烦 . 我想知道一些可以帮助我的模式,因为java没有任何多重扩展选项 . 我将在下面描述我的问题,并解释为什么多个界面根本无法帮助我 . 我们走吧 .
我们想要的是“类是一组功能” . 我的意思是构造如下:
field a;
field b;
field c;
method m1(){
// use, and change fields a,b,c;
}
method m2(){
// use, and change fields a,b,c;
}
//etc
所以,基本上该功能是一组方法和相应的字段 . 所以,它非常接近java界面 .
当我说这个类实现"feature1"时,我的意思是这个类包含所有"feature needed"字段,并且实现了所有与功能相关的方法 . 当类实现两个功能时,棘手的部分开始 . 有一个变化,两个不同的功能包含相似的字段(此字段的名称相同) . 让这些字段的不同类型的情况超出范围 . 我想要的是"feature naming tolerance" - 这样如果来自特征A的methodA()改变字段“common_field”,来自特征B的方法B,也使用“common_field”作为字段将看到这种改变 .
所以,我想创建一组功能(基本上是接口)及其实现 . 在此之后,我想创建将扩展多个功能的类,没有任何复制粘贴和其他废话 . 但是我不能用Java编写这段代码:
public static interface Feature1 {
public void method1();
}
public static interface Feature2 {
public void method2();
}
public static class Feature1Impl implements Feature1 {
int feature1Field;
int commonField;
@Override
public void method1() {
feature1Field += commonField;
commonField++;
}
}
public static class Feature2Impl implements Feature2 {
int feature2Field;
int commonField;
@Override
public void method2() {
commonField++;
}
}
public static class MyFeaturedClass extends Feature1Impl, Feature2Impl implements Feature1, Features2 {
}
所以,你可以看到问题真的很复杂 . 下面我将描述为什么一些标准方法在这里不起作用 . 1)使用这样的东西:
public static class MyFeaturesClass implements Feature1,Feature2{
Feature1 feature1;
Feature2 feature2;
@Override
public void method2() {
feature2.method2();
}
@Override
public void method1() {
feature1.method1();
}
}
好的,这是非常好的方法 - 但它没有提供“功能字段名称容差” - 因此方法2的调用不会更改对应feature1的对象中的字段“commonField” .
2)使用其他设计 . 为什么你需要这样的方法?好 . 在我的游戏中有一个“单元”概念 . 单位是MOVABLE和ALIVE对象 . 可移动对象具有position和move()方法 . 活着的对象有hp和takeDamage()和die()方法 . 我的游戏中只有MOVABLE对象,但这个对象不是可移动的(例如建筑物) . 当我意识到可移动和活动为类,实现接口时,我真的不知道我应该扩展我的Unit类 . 在这两种情况下,我都会使用复制粘贴 . 上面的例子非常简单,实际上我需要为不同的游戏机制提供很多不同的功能 . 而且我将拥有许多具有不同属性的不同对象 .
我实际尝试的是:
Map<Field,Object> fields;
所以我游戏中的任何对象都有这样的Map,任何对象都可以应用任何方法 . 方法的实现只是从这个 Map 中获取所需的字段,完成它的工作并改变它们中的一些 . 这种方法的问题在于性能 . 首先 - 我不想为double和int字段使用Double和Interger类,第二 - 我希望直接对我的对象的字段(而不是通过map对象) .
有什么建议?
PS . 我想要的结果是:
class A implements Feature1, Feature2, Feature3, Feature4, Feature5 {
// all features has corresponding FeatureNImpl implementations;
// features 1-2-3 has "shared" fields, feature 3-4 has, features 5-1 has.
// really fast implementation with "shared field tolerance" needed.
}
1 回答
一种可能性是添加另一层接口 . 可以为所有可能的公共字段定义XXXProviderInterface,为它们定义getter和setter .
要素实现类将需要构造函数中所需的提供程序 . 所有对公共字段的访问都是通过这些引用完成的 .
具体的游戏对象类实现将实现所需的提供者接口和特征接口 . 通过聚合,它将添加功能实现(将
this
作为提供者传递),并将功能调用委托给它们 .例如 .
但是,我不认为这是一个最佳解决方案