我正在使用状态模式,并且想知道如何定义变量,以便它们可以在每个子类中使用。抽象父类中的受保护变量可能是正确的选择,但有了这个,我想知道如何从主类初始化这些变量。
class Main
{
\\Initialize variable "file" here?
\\...
Context tc = new Context(new Step01());
\\...
}
class Context
{
private State ts;
// Constructor
public Context(State st)
{
this.State = st;
}
// Gets or sets the state
public State State
{
get
{
return st;
}
set
{
st = value;
}
}
public void Request()
{
ts.Handle(this);
}
}
abstract class State
{
protected string file = "file";
public abstract void Handle(Context tc);
}
class Step01 : State
{
tc.State = new Step02();
// use variable "file"
}
class Step02 : State
{
tc.State = new Step0x()
// use variable "file"
}
示例是剪切的代码,但不起作用。我希望有助于更准确地解释我的问题。
子类的数量(Step0x)各不相同,所以我认为在父类中只定义一次变量更容易。
有人知道如何在主类中初始化我的变量吗?
谢谢。
答案 0 :(得分:1)
将文件定义为常量:
abstract class State
{
protected const string file = "file";
public abstract void Handle();
}
以下是使用Step01
的{{1}}和Step02
的实施:
file
以下是class Step01 : State
{
public override void Handle(){}
public void PrintFile()
{
Console.WriteLine(string.Format("step1 + {0}", file));
}
}
class Step02 : State
{
public override void Handle(){}
public void PrintFile()
{
Console.WriteLine(string.Format("step2 + {0}", file));
}
}
和Step01
类的使用方法:
Step02