Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some sort of creational pattern needed in C#

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 :

  • The Person could only be instantiated by a specific controller
  • This controller could update the state of the Person (name field) at any time
  • The Person need to send a notification to the rest of the world when it occurs
  • All other types should only be able to read Person attributes

How 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.

like image 571
Romain Verdier Avatar asked Jan 25 '23 02:01

Romain Verdier


2 Answers

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.

like image 79
JasonTrue Avatar answered Jan 28 '23 15:01

JasonTrue


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.

like image 45
Jason Cohen Avatar answered Jan 28 '23 15:01

Jason Cohen