Simple Object State Awareness

Through the implementation of two custom interfaces (IClonable<T> and IStateAware) and one from the .NET framework (IEquatable<T>) it becomes pretty simple to create a class that’s state-aware. The IClonable<T> interface is simply a representation of the Prototype Pattern that I have made a sample of on my website previously.
 
Here are the two custom interfaces:
 
     public interface IClonable<T> {
          T Clone();
     }
 
     public interface IStateAware {
          void StoreCurrentState();
          bool HasChanged { get;  }
     } 
 
Here’s a sample implementation:
 

     public class MyClass : IClonable<MyClass>, IEquatable<MyClass>, IStateAware {

          MyClass currentState;

 

          public string FirstName { get; set; }

          public string LastName { get; set; }

 

          public MyClass Clone() {

               return (MyClass) MemberwiseClone();

          }

 

          public bool Equals(MyClass other) {

               return other.FirstName == FirstName &&

                         other.LastName == LastName;
          }
    

         public void StoreCurrentState() {

               currentState = Clone();
          }

 

          public bool HasChanged {

               get {

                    if(currentState == null) return false;

                    return !Equals(currentState);

               }
          }

     }

 
Now I can take a snapshot of the object at any time and determine if it has changed later on.
 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s