M
M
Mozzarella2018-04-10 22:21:09
C++ / C#
Mozzarella, 2018-04-10 22:21:09

How to get a singleton within a single class, not the entire application?

I'm developing a game like HearthStone. There is a state of the table

public class Table
    {
        public Table()
        {
            Players = new List<PlayerModel>();
        }
        public List<PlayerModel> Players { get; set; }
        public int Queue { get; set; }
    }

And there is a certain trigger manager that notifies that an event has occurred in the game (the card has been attacked, a spell has been played, etc.)
public class TriggerDispatcher
    {
        public TriggerDispatcher()
        {
            if (Triggers == null)
                Triggers = new Dictionary<string, ITrigger>();
        }
        public ITrigger GetTrigger<T>() where T : ITrigger
        {
            if (Triggers.ContainsKey(typeof(T).Name))
                return Triggers[typeof(T).Name];
            var trigger = Activator.CreateInstance<T>();
            Triggers.Add(typeof(T).Name, trigger);
            return trigger;
        }
        public Dictionary<string, ITrigger> Triggers { get; }
    }
    public interface ITrigger
    {
        void AddAction(IAction action);
        void RemoveAction(IAction action);
        void ExecuteActions(object param);
    }

It is necessary that these two classes be available from anywhere within the same session. Sessions consisting of two players are created on the server and table and dispatcher instances are created for them. How to organize their receipt in other places of the code within the session?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavlo Ponomarenko, 2018-04-11
@sfreaky

If correct, connect DI Container, do everything through it.
If without a container, transfer dependencies manually. Usually they are not needed everywhere
. What you are talking about personally, I did a little differently. There are no events as such. There is a team , which is an event. For example AttackCommand, MoveCommand, DeployCommand. All interaction goes through commands, all other classes are dry data. Accordingly, all such things are needed only by teams, and they are created through a single center, which makes the injection.
Here I wrote an article:
https://habrahabr.ru/post/322258/
https://habrahabr.ru/post/322268/
And also, if you write to the email (available in the profile), I can send an example of the KKI server in C #.

G
Griboks, 2018-04-10
@Griboks

And Session.TriggerDispatcherdo Session.Tableyou not like something?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question