Elegant design of simulating a read-only object
I am currently developing an GUI
to an embedded system. (I am using GUI to descripe my app opposed to interface to avoid confusion with the progamatic meaning)
Context
I have created a class which simulates the embedded system. I do all my communications through a Connection
class I have designed which can communicate via TCP/Serial or a virtual connection between two Connection
objects.
All this works nicely and as expec开发者_StackOverflow社区ted, my simulated object and GUI
communicate via the virtual connection.
I have a Diagnostic
packet which is sent from the device
(real or simulated) and read by the GUI
. This fits nicely into a class which I have called ControllerDiagnostic
.
Question
My question relates to the ControllerDiagnostic
class. On the GUI
side all properties should be read-only (DeSerialization is done via reflection on the private fields directly). On the simulation side they clearly need to be mutable. So how do I handle this elegantly? I've considered:
- Creating a completely new class which mimics
ControllerDiagnostic
but exposes setting of the fields. - Creating all fields in
ControllerDiagnostic
protected then inheriting into a private nested class which provides accessors to these fields within the simulation class. - Creating an assembly with just two classes and using an
Internal
setter. - Leave the properties as read/write and document the
GUI
should not modify them. - Re-writing C# so I could use
friend
in the same way I can in C++.
None of these seem ideal to me.
Thanks
You could write an interface which exposes all properties of your class with getters and setters and a second interface which only exposes the getters for all your properties. Then have a single class implement both interfaces and use the getter-only interface in the GUI.
In code that could look somewhat like this:
public interface IReadWrite
{
string SomeString { get; set; }
}
public interface IReadOnly
{
string SomeString { get; }
}
public class TestClass : IReadWrite, IReadOnly
{
public string SomeString { get; set; }
}
精彩评论