Null Object Pattern

Implement the interface

but do Nothing

Example: Employee

Employee e = DB.getEmployee("Bob");
if (e != null && e.isTimeToPay(today))
	e.pay();

Example: Employee

Employee e = DB.getEmployee("Bob");
if (e.isTimeToPay(today))
	e.pay();
public class NullEmployee: Employee{
    public bool isTimeToPay(Date today){
    	return false;
    }
    public void pay(){
    	// do nothing
    }
}

Example: Employee

Example: Simulator

// Scheduler
public void Run()
{
    while (!_cancellationTokenScheduler.IsCancellationRequested &&
           _onSchedulerRunningEvent.WaitOne())
    {
        ...
        var ecr = _simulatorResult.Satellite.Orbit.SatPosKmECR;
        _gpsSimulator.UpdateECEF(currentDateTime, ecr[0], ecr[1], ecr[2]);
        ...
    }
}

Example: Simulator

void init()
{
    _ibManager = new IBManager();
    _subSimulator = new SubSimulator();
    ...
    _gpsSimulator = GpsSimulatorFactory.Create(gpsConfigFile);
}

public interface IGpsSimulator
{
    void Init(DateTime startTime);
    void Start();
    void Stop();
    void UpdateECEF(DateTime currentDateTime, double x, double y, double z);
    TimeSpan GetSimulationElapsedTime();
}
public class NullGpsSimulator : IGpsSimulator
{
    private static NullGpsSimulator _instance = null;

    private NullGpsSimulator() {}

    public static NullGpsSimulator Instance()
    {
        if (_instance == null)
            _instance = new NullGpsSimulator();
        return _instance;
    }

    public void Init(DateTime startTime)
    {
        // Do Nothing
    }
    public void Start()
    {
        // Do Nothing
    }
    public void Stop()
    {
        // Do Nothing
    }
    public void UpdateECEF(DateTime currentDateTime, double x, double y, double z)
    {
        // Do Nothing
    }
    public TimeSpan GetSimulationElapsedTime()
    {
        return TimeSpan.Zero;
    }
}

Applicability

  • When an object requires a collaborator. (like stub)

  • When ignore the difference between a collaborator which provides real behavior and that which does nothing.

  • When you want your clients to behave the same way consistently.

 Use the Null Object pattern when 

Applicability

Adventage

  • Can avoid null check and null exception

  • Simplify the code (readability)

  • Useful

Cost

  • Can hide the real problem

End.

Made with Slides.com