I would recommend creating a normal class containing this behavior, and then let this class implement an interface extracted from the members of the class.
Whenever you need to call these methods, you add an interface to the user (rather than a specific class). This allows you to change two independently of each other.
It may sound like more work, but it's just a Strategy design template.
This will also simplify unit test code because the code is looser bound.
Here is an example in C #.
Interface:
public interface ITimeMachine { IStopwatch CreateStopwatch(); DateTimeOffset GetNow(); }
Production Implementation:
public class RealTimeMachine : ITimeMachine { #region ITimeMachine Members public IStopwatch CreateStopwatch() { return new StopwatchAdapter(); } public DateTimeOffset GetNow() { return DateTimeOffset.Now; } #endregion }
and here is the user interface:
public abstract class PerformanceRecordingSession : IDisposable { private readonly IStopwatch watch; protected PerformanceRecordingSession(ITimeMachine timeMachine) { if (timeMachine == null) { throw new ArgumentNullException("timeMachine"); } this.watch = timeMachine.CreateStopwatch(); this.watch.Start(); } public abstract void Record(long elapsedTicks); public virtual void StopRecording() { this.watch.Stop(); this.Record(this.watch.ElapsedTicks); } }
Mark seemann
source share