简体   繁体   English

使用C ++ / CLI或C#实现状态设计模式

[英]Implementing state design pattern using C++/CLI or C#

I am trying to implement the state design pattern using C++/CLI. 我正在尝试使用C ++ / CLI实现状态设计模式。 This pattern requires that the State class be a friend of the Context. 这种模式要求State类成为Context的朋友。 But C++/CLI does not allow a friend class. 但是C ++ / CLI不允许朋友类。 I understand that this is also the case with C#. 我知道C#也是如此。 Has anyone implemented the state pattern with C++/CLI or C#? 有没有人用C ++ / CLI或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. 让State类成为Context类的朋友并不是实现State模式的必要条件 Wikipedia has an implementation without using the friend modifier. Wikipedia的实现不使用friend修饰符。

Its done using Association (or what all the cool kids are calling Dependency Injection). 它是使用Association(或所有很酷的孩子称之为Dependency Injection)来完成的。 Inject the state into the context. 将状态注入上下文。 See the implementation on DoFactory 参见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() { }
  }
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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