模拟 API 需要一个表示属性更改的类型和一个具有传入和传出IObservable<T>
更改流的模拟方法。模拟引擎的实现将包含对传入属性更改做出反应以更新输出流的规则。
类型是这样的(尽管结构可能比类更好):
class PropertyChange
{
public PropertyChange(string name, object value) { Name = name; Value = value; }
public string Name { get; private set; }
public object Value { get; private set; }
}
模拟方法如下所示。为了演示多个规则,此代码预设了一个IsLightOn
简单地跟踪的属性IsPowered
。
IObservable<PropertyChange> Simulate(IObservable<PropertyChange> incomingChanges)
{
var isLightOnRule =
from c in incomingChanges
where c.Name == "IsPowered"
select new PropertyChange("IsLightOn", c.Value);
var ramp = Observable.Generate(0, speed => (speed <= 1000), speed => speed + 10, speed => new PropertyChange("Speed", speed), _ => TimeSpan.FromSeconds(1));
var speedRule = incomingChanges
.Where(c => c.Name == "IsPowered" && (bool)c.Value)
.SelectMany(ramp);
// Add more rules here.
return Observable.Merge(isLightOnRule, speedRule /* merge more rules here */);
}