在某些情况下,对象图中“较深”的对象需要根据祖先的值进行更新。例如。考虑一个映射练习,其中我们正在映射来自Web视图的对象的值。我们拥有数据库/存储中存在的原始持久对象,并且拥有从视图中传入的变异对象。给定以下可视化的“模式”,如果我们将视图中的传入对象映射到数据库中的持久化“双胞胎”,并且我们想基于策略默认可扣除项的值来设置Coverage可扣除项的值,有没有一种方法无需传递对父对象的引用?
{
Policy: {
DefaultDeducitble: 1000
LocationCollection: [{
Location: {
BuildingCollection: [{
Building: {
CoverageCollection: [{
Coverage: { DefaultDeductible: nulll}
}]
}
}]
}
}]
}
}
我们的映射器映射对象层次结构的一个级别,因此我们将具有以下内容:
class PolicyMapper { /// maps policy and calls a location collection mapper }
class LocationCollectionmapper { /// calls a location mapper for each location }
class Locationmapper {///maps the location and calls building collection mapper }
class BuildingCollectionmapper { /// calls a building mapper for each building }
class BuidlingMapper {///maps the buidling and calls coverage collection mapper }
class CoverageCollectionmapper { /// calls a coverage mapper for each coverage }
class CoverageMapper {///maps the coverage,this is where we want a value from the Policy level }
问题是,如何在不将Policy对象传递到整个映射层次结构的情况下访问CoverageMapper中的Policy级别信息?一种想法是拥有一个我们可以查询的临时缓存。我真的不知道这是否存在...或者这是一个好主意还是反模式...但是看起来像这样:
public class TransientPolicyCache {
///code to load the cache and retreive stuff
public Policy Get() { //returns the policy }
}
public class CoverageMapper {
public CovergaeMapper(TransientPolicyCache cache) { ///cache is provided by ioc }
public Coverage Map(Coverage target,Coverage source){
//need the policy
var policy = _cache.Get();
// do the things
}
}