最近我一直在思考与面向对象的原则、实践和范型有关的内容,例如SOLID、Demeter定律和DDD等。一个不断浮现的主题是强制执行对象基数。
对象关联基数源自业务规则,这些规则规定某些实体只能与一定数量的其他实体对象相关联。例如,如果您正在设计一个管理仓库的系统,一个业务规则可能是单个物品只能存储在一个仓库中。显然,在软件设计中强制执行这些规则是一个实施的问题。
我的疑问是:在业务领域需要严格的基数模型时,最好的执行方法是什么?我能想到的技术包括以下几种:
Bi-directional references - Bi-directional associations between associated objects (object A references object B and object B references object A)
class Warehouse { private List<Item> items; public void RegisterItem(Item obj) { if(obj.Warehouse != null) throw new ArgumentException("Can only register un-owned item") items.Add(obj); obj.Warehouse = this; } }
Encapsulate the owned entity - let the owner control its creation and deletion and provide access through a set of APIs that abstract the actual entity implementation (object A clones a passed in entity B or creates an entity B based on a passed schematic)
class Warehouse { private List<Item> items; public void RegisterItem(Item obj) { items.Add((Item)obj.Clone()); } public void RegisterItem(ItemDescriptor item) { items.Add(new Item(item)); } }
Third party monitor - Have some third party that understands cardinality constraints create and hookup object associations appropriately (object C knows about the relationship between A and B and is responsible for creating and maintaining it - this method is only available to C and not available to clients)
class Warehouse { private List<Item> items; internal void RegisterItem(Item obj) { items.Add(obj); } } class WarehouseItemRegistrationService { private List<Item> registeredItems; public void RegisterItem(Warehouse warehouse, Item item) { if(registeredItems.Contains(item)) throw new ArgumentException("Can only register un-owned items"); warehouse.RegisterItem(item); } }
大家还有什么其他想法、建议或更好的方法吗?
Warehouse
和Item
的概述,并了解其规则。 - user1342582