简体   繁体   中英

Implementing state design pattern using C++/CLI or C#

I am trying to implement the state design pattern using C++/CLI. This pattern requires that the State class be a friend of the Context. But C++/CLI does not allow a friend class. I understand that this is also the case with C#. Has anyone implemented the state pattern with C++/CLI or C#? I would like to know how you got around the absence of friend class.

Having the State class be a friend of the Context class is not a requirement for implementing the State pattern. Wikipedia has an implementation without using the friend modifier.

Its done using Association (or what all the cool kids are calling Dependency Injection). Inject the state into the context. See the implementation on DoFactory

You could keep state in a subclass, then replace sub class object with a different inheriting type when state changes.

class YourClass
{
  private MyEnum _myStateEnum; // Wrap this with a public property
  private MyInnerClass _myStateLogic; // Change this with appropriate type when above changes

  public void AnExampleMethod()
  {
      _myStateLogic.AnExampleMethod();
  }

  internal abstract class MyInnerClass
  {
      public virtual abstract void AnExampleMethod();
  }

  internal class MyOtherInnerClass1: MyInnerClass
  {
      public override void AnExampleMethod() { }
  }

  internal class MyOtherInnerClass2: MyInnerClass
  {
      public override void AnExampleMethod() { }
  }
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM