1

在Java中(一般来说)有没有办法让一个类如此公开以至于它的方法等......可以从周围的小类访问,甚至不实例化它?哈,我的意思是......如果我有一个爸爸类,它有一个方法draw(),它实例化一个名为 Hand 的婴儿类和一个名为 Deck 的婴儿类,然后 Deck 实例化一个名为 Card 的婴儿类,它有一个方法play(),有没有办法Play()然后Draw()从爸爸班打电话?

这里的想法是......爸爸类说“Deck!play(card)!” 然后甲板说“卡!玩()!” 然后play转身说:“嘿,爸爸!Draw()!”

PS这个想法是......在CCG中,每张卡都有一个不同的“play()”方法,但它们基本上都以相同的方式调用。打牌的机会来了,你就打牌。但是卡本身并没有做任何内部的事情:不,不,它从游戏规则中调用了许多方法,这是可见的。所以,就像万智牌中的一张牌,上面写着“抓一张牌。对目标玩家造成一次伤害。” 正在调用 draw(player, 1) 和 dealDamage(player, 1) ,它们可能不在卡片本身中......因为它们会影响可能由玩家在开始游戏时实例化的变量,并就生命总数和规则等达成一致“画”是什么意思?

(元问题:像往常一样,有人可以重命名这个问题,以便它反映我的要求......作为一个初学者真是令人沮丧!)

4

5 回答 5

4

当 Daddy 类实例化 Baby 类时,它(Daddy)可以将对自身的引用传递给 Baby 构造函数,从而使 Baby 可​​以访问其所有公共方法。

class Daddy {
    public foo(){...}
    public createBaby(){
        Baby baby = new Baby(this);
        // baby now has a reference to Daddy
    }
}


class Baby {
    Daddy daddy;
    public Baby(Daddy daddy){
        this.daddy = daddy;
    }
    ...
    public callDaddy(){
        daddy.foo();
    }
}
于 2008-12-04T13:34:43.120 回答
1

你可以:

  • 通过构造函数传递对象引用。或者通过 getter 和 setter。或者直接给函数。
  • 使用继承。
  • 使用静态类。
于 2008-12-04T13:31:22.207 回答
0

从面向对象的角度来看,我会说使用继承。一种方法是创建一个不实现子类行为不同的方法的抽象类;并实现对所有子类行为相同的方法。

于 2008-12-04T13:37:55.517 回答
0

看起来您正在尝试实现某种双重调度

于 2008-12-04T13:56:20.300 回答
0

您还可以定义内部和外部类。然后内部类可以访问外部类的所有字段。

public class OuterClass{
    int x
    private class InnerClass{
        InnerClass(){
            x = 10;
        }
    }
}

However, you're probably going to be better off using either a Singleton pattern, where you have a static reference to a single resource (like the deck for most card games, although CCGs tend to have one per player), or else passing in the shared resource in the object's constructor. In the case of MTG or something similar, I'd probably give each card a cast() method that takes a Player and a list of targets. The Player is the caster, so a spell like Brainstorm could then invoke draw() on the Player to get them to draw cards, while a permanent spell could then assign itself under control of the Player. The targets then would be for any other targets the spell would possibly need and could potentially be null or the empty list (whichever you think is more appropriate).

于 2008-12-04T13:57:13.387 回答