【发布时间】:2012-01-29 00:08:38
【问题描述】:
我正在为我的公司开展一个内部项目,该项目的一部分是能够在工厂设计中生成各种“数学问题”。
- 要产生问题,必须指定工厂的难度级别。
- 每个
ProblemFactory都包含抽象方法,例如ConfigureXLevels 和Generate。 - 提供
Random变量。 - 包含一个字典,其中包含可用级别(
key:=Levels、value:=IConfiguration,其工作方式类似于对生成问题有用的对象容器(例如二进制表和时间表都需要两个Bound对象)。李>
_
public abstract class ProblemFactory
{
private IDictionary<Levels, IConfiguration> Configurations = new Dictionary<Levels, IConfiguration>();
protected Random Random = new Random();
public ProblemFactory() {
LoadLevels();
}
protected abstract Problem Generate();
protected abstract IConfiguration ConfigureEasyLevel();
protected abstract IConfiguration ConfigureMediumLevel();
protected abstract IConfiguration ConfigureHardLevel();
private void LoadLevels() {
Configurations.Add(Levels.Easy, ConfigureEasyLevel();
Configurations.Add(Levels.Medium, ConfigureMediumLevel();
Configurations.Add(Levels.Hard, ConfigureHardLevel();
}
}
这是一个关于创建加法问题的具体类,检查我如何从抽象 ProblemFactory 覆盖一些 ConfigureXLevel 并返回IConfiguration。
public class AdditionProblemFactory : ProblemFactory
{
public override Problem Generate() {
int x = //.. x must receive a random number according to the configuration selected for the level
int y = //..
Operators op = Operator.Addition
return BinaryProblem.CreateProblem(x, y, op);
}
protected override IConfiguration ConfigureEasyLevel() {
// the same of ConfigureMediumLevel() but with others values
}
protected override IConfiguration ConfigureMediumLevel() {
BinaryProblemConfiguration configuration = new BinaryProblemConfiguration();
configuration.Bound1 = new Bound<int>(100, 1000);
configuration.Bound2 = new Bound<int>(10, 100);
return configuration;
}
protected override IConfiguration ConfigureHardLevel() {
// the same of ConfigureMediumLevel() but with others values
}
}
public class BinaryProblemConfiguration : IConfiguration
{
public Bound<int> Bound1 { get; set; } //Bounds for Number1 of a binary problem
public Bound<int> Bound2 { get; set; } // Bounds… Number2 …
}
问题在AdditionProblemFactory和TimesTablesProblemFactory的Generate method中,x, y应该根据Level IConfiguration接收随机数。
Bound 类包含 Min 和 Max 值。比如我选择Levels.Medium,我一定会收到Number1和Number2中特定范围或绑定的问题(Number 1 + Number 2 = X)
AdditionProblemFactory factory = new AdditionProblemFactory();
BinaryProblem problem = (BinaryProblem)factory.Generate(Levels.Medium);
这是我不知道我应该在设计中修改什么的部分。 Random 在 ProblemFactory 上,但最好将变量移动到 IConfiguration 并在那里生成数字。
如果您喜欢下载它。别担心,它这么小。 http://www.mediafire.com/?z5j9hu1szpuu2u5
【问题讨论】:
-
@L.B 抱歉。我不知道我不应该这样做。我只是想在我的解释中更简短一些。下次我会记住的。
标签: c# design-patterns factory factory-pattern