I have a superclass “Entity” in a logic-tier project within existing 3-tier “core” application code, from which 2 concrete classes “RiskEntity” and “PolicyEntity” inherit (in that same core project). The superclass possesses a public property “Loss” which is not overridden by the 2 subclasses. This property is used by other code within this core project. The implementation of that property refers to other classes/properties within that core project.
For a particular use case, I require the propery’s getter to be implemented differently. If possible, I’d like that bespoke implementation to exist outside of the “core” C# project mentioned above, and I’d like the application to be configurable so as to instruct it to use that bespoke implementation whenever that property is referenced from within my core project.
Can anyone point me to an elegant pattern/technique to achieve this? I’ve wondered about using a helper interface within the getter, and using reflection to instantiate the correct implementation of that interface, based on (say) a project setting. But even if this is along the right lines, I’m not sure how the bespoke implementation could live outside of the core project code.
Alternative suggestions also welcome. Thanks.
Since you are describing having different implementations of how the
Lossproperty is calculated this suggests to me the Strategy pattern. You can ensure that the baseEntityclass uses the default implementation but that theEntitysub-classes can be constructed using alternative replacement implementations. I would therefore start by defining an interface in your core project that can be implemented in assemblies outside the core assembly provided they have a reference to it. There’s numerous variations on this theme and knowing which fits your situation is difficult to know precisely without seeing more of the code but the following gives a broad outline.First, the Strategy interface and default implementation in your core project:
Next, the
Entityclass and derived classes, again in the core project.The client code that constructs the
Entityderived objects can now push in different implementations of theILossCalculatorinterface, even when the implementation is defined outside the core project. To achieve selecting theILossCalculatorimplementation to use from configuration I would probably create aFactorythat you would use to constructEntitysubclasses which could be configured so that when anEntitygets created it would use a custom implementation of theILossCalculator. The client’s view would be something like: