I have the following type :
// incomplete class definition
public class Person
{
private string name;
public string Name
{
get { return this.name; }
}
}
I want this type to be created and updated with some sort of dedicated controller/builder, but I want it to remain read-only for other types.
This object also needs to fire an event every time it is updated by its controller/builder.
To summary, according to the previous type definition skeleton :
Person
could only be instantiated by a specific controllerPerson
(name
field) at any timePerson
need to send a notification to the rest of the world when it occursPerson
attributesHow should I implement this ? I'm talking about a controller/builder here, but all others solutions are welcome.
Note : I would be able to rely on the internal
modifier, but ideally all my stuff should be in the same assembly.
Create an interface IReadOnlyPerson which exposes only get accessors. Have Person implement IReadOnlyPerson. Store the reference to Person in your controller. Give other clients only the read only version.
This will protect against mistakes, but not fraud, as with most OO features. Clients can runtime cast to Person if they happen to know (or suspect) IReadOnlyPerson is implemented by Person.
Update, per the comment:
The Read Only interface may also expose an event delegate, just like any other object. The idiom generally used in C# doesn't prevent clients from messing with the list of listeners, but convention is only to add listeners, so that should be adequate. Inside any set accessor or function with state-changing side effects, just call the event delegate with a guard for the null (no listeners) case.
I like to have a read-only interface. Then the builder/controller/whatever can reference the object directly, but when you expose this object to the outside you show only the interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With