开发者

Rolling Some Dice...Look But Don't Touch

开发者 https://www.devze.com 2023-02-19 07:49 出处:网络
Does anyone have any thoughts on passing full objects as variables as opposed to only pointers to the functions of the full object?

Does anyone have any thoughts on passing full objects as variables as opposed to only pointers to the functions of the full object?

For example, I have a Dice object with two methods:

Now, I need to utilize the dice for more than just player moving, other objects need to be able to look at the Dice as well. Now, it seems wrong to me to pass the whole Dice object to these other objects, since then those objects would 'technically' be able to re-roll the Dice. Is it good or bad programming to pass only the GetCount function pointer to these other objects? Essentially saying "I'm not giving you the Dice, but I'll show you how to read them.".

Thoughts?


It seems that its an excellent oportunity to use the OBSERVER PATTERN (GoF);

public class Dice
{
    private List<IDiceObserver> observers;
    public void RegisterObserver(IDiceObserver observer)
    {
        this.observers.Add(observer);
    }

    private Int32 count;
    public Int32 Count
    {
        get
        {
            return this.count;
        }
        private set
        {
            this.count = value;
            foreach (IDiceObserver observer in this.observers)
                observer.DiceRolled(new DiceParameters(this.count));
        }
    }

    public void RollDice()
    {
        this.Count = new Random(DateTime.Now.Millisecond).Next();
    }

    public Dice()
    {
        this.observers = new List<IDiceObserver>();
    }
}

Do you need any further explanation on pattern, or other classes implementations????


Why don't you pass them an integer? This means they are decoupled from the dice.

If you are using dependency injection to inject the dice into service objects for each move, then create an interface that only contains the GetCount() method.


You can create a wrapper class for dice to make them immutable. The wrapper can be implemented either by delegation or by subclassing and overriding RollDice(). Then pass a wrapper object instead of a mutable Dice object when you want to guarantee that it won't change.


Sounds like your Dice object should have a DiceValue or FaceValue attribute. You could pass this value instead of passing the dice themselves. This controls access to dice behaviour, and also avoids the primitive obsession code smell which would result from passing just the integer value of the face. It also keeps your dice value more abstract, so you could later use values other than numbers, such as special face values, etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消