Originally the code is like this:
public interface IApplicableSystem
{
string Name { get; }
void Apply ( );
}
public class Effector
{
public string Name { get; set; }
}
public class EffectSystem : IApplicableSystem
{
Effector Internal { get; set; }
public string Name
{
get { return this.Internal.Name; }
}
RelayCommand applyCommand;
public ICommand ApplyCommand
{
get
{
if ( applyCommand == null )
applyCommand = new RelayCommand ( p => this.Apply ( ) );
return applyCommand;
}
}
public void Apply ( )
{
}
public EffectSystem ( Effector value )
{
this.Internal = value;
}
}
So there are many different types implementing IApplicableSystem, all where they differ is their Name property, Apply method and the type of the private Internal property that’s used inside the class.
Should I use generic to make them like this?:
Is this reasonable? Mainly this reduces the amount of code in the other types implementing IApplicableSystem.
public abstract class GenericSystem<T> : IApplicableSystem
{
protected T Internal { get; set; }
public virtual string Name
{
get { return String.Empty; }
}
RelayCommand applyCommand;
public ICommand ApplyCommand
{
get
{
if ( applyCommand == null )
applyCommand = new RelayCommand ( p => this.Apply ( ) );
return applyCommand;
}
}
public virtual void Apply ( )
{
}
public GenericSystem ( T value )
{
this.Internal = value;
}
}
public class EffectSystemGeneric : GenericSystem<Effector>
{
public override string Name
{
get { return GetUniqueName ( base.Internal.Name ); }
}
public override void Apply ( )
{
Console.WriteLine ( "Do something" );
}
}
Yes, this is reasonable, but when overriding a virtual method, you have to use the override keyword, not virtual. You may want to make the generic base class abstract instead, to force implementers to provide an implementation.