I'm creating a series of Interfaces/Abstract classes that contain basic properties and I would like to have computed Properties and multiple inheritance.
public abstract class /interface Modifiable
{
public DateTime ModifiedDate {get; set;}
public boo ModifiedToday
{
get { return DateTime.Now.AddDays(-1).CompareTo(ModifiedDate) >= 0; }
}
public bool ModifiedInLastWeek
{
get { return DateTime.Now.AddDays(-7).CompareTo(ModifiedDate) >= 0; }
}
}
public abstract class /interface Deletable
{
public DateTime DeletionDate {get; set;}
public bool Deleted
{
get { return DeletionDate != default(DateTime) }
}
}
Then I have a class that inherits from these two Interfaces/Abstract classes.
public class Something : Modifiable, Deletable
{
//
}
But a class cannot inherit from two abstract classes. So I then need to use interfaces, but with interfaces I cannot have method bodies. I then have to define the same exact functions across multiple classes to implement these simple bool properties using interfaces.
I also don't want to have Modifiable inherit from Deletable because I might want something to be Modifiable but not Deletable. These specific classes aren't my problem, I'm simply using them to illustrate my problem.
Is there a design pattern that mimics an abstract class by allowing function bodies, but allows multiple inheritors like an interface?
It's not multiple inheritance, but something that comes to mind is Extension methods.
public interface IModifiable
{
DateTime ModifiedDate {get; set;}
}
public static class ModifiableExtensions
{
public bool ModifiedToday(this IModifiable m)
{
return DateTime.Now.AddDays(-1).CompareTo(m.ModifiedDate) >= 0;
}
public bool ModifiedInLastWeek(this IModifiable m)
{
return DateTime.Now.AddDays(-7).CompareTo(m.ModifiedDate) >= 0;
}
}
That gives the "feel" of helper methods that are baked into the type, but they happen to be declared elsewhere. Take this class:
public class MyModifiable :IModifiable
{
public ModifiedDate {get; set;}
}
And you can do this:
MyModifiable m = new MyModifiable;
m.ModifiedDate = DateTime.Now;
bool isToday = m.ModifiedToday();
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