mardi 16 février 2021

"friend" classes in C# and the state pattern

I was trying to implement the state pattern in C#, and I did something like this:

class Context {
    private State state = null;
    private State concreteState1 = null;
    private State concreteState2 = null;

    public Context(State state) {
        concreteState1 = new ConcreteState1(this);
        ChangeStateTo(concreteState1);
    }

    public void ChangeStateTo(State state_) {
        state = state_;
    }

    public void DoSomething() {
        state.DoSomething();
    }

    public void DoSomethingElse() {
        state.DoSomethingElse();
    }
}
    
abstract class State {
    protected Context context;

    public void Context(Context context_) {
        context = context_;
    }

    public abstract void DoSomething();

    public abstract void DoSomethingElse();
}

Here, ConcreteState1 and ConcreteState2 are implementations of State that I omitted for brevity. The issue I'm having is that Context has some members that I would like all of the classes implementing State to access; I think this makes sense in the context of the pattern since the idea is for the context to act "as if" it was a different class depending on its state, and for this it would be useful for the states to be able to access its internals.

In C++ I would probably code this by setting State to be a friend class of Context, but since C# doesn't have anything similar to friend I'm not sure what to do here. I don't really want to create an assembly just for this specific finite state machine and put all the code in there. I also don't want a public setter for the private members of Context, because I don't want other classes modifying context. Is there any other good alternative that allows me to keep my Context and ConcreteState classes distinct but makes the internals of Context only available to State?

Aucun commentaire:

Enregistrer un commentaire