Skip to content

Instantly share code, notes, and snippets.

@grofit
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grofit/e70a6beb1bb6b6c83381 to your computer and use it in GitHub Desktop.
Save grofit/e70a6beb1bb6b6c83381 to your computer and use it in GitHub Desktop.
An example of why inheritance is a poor substitute for composition
/*
This is a Path calculator which uses an A* approach
*/
public class AStarPathCalculator : IPathCalculator
{
IEnumerable<Vector3> FindPathTo(Vector3 startPosition, Vector3 endPosition)
{
var path = ABPath.Construct(startPosition, endPosition);
return path.vectorList;
}
}
/*
This is a Path calculator which relies upon using a FloodFill approach for calculating a path.
*/
public class FloodFillPathCalculator : IPathCalculator
{
private int _floodFillDistance;
public FloodFillPathCalculator(int floorFillDistance)
{
_floodFillDistance = floodFillDistance;
}
IEnumerable<Vector3> FindPathTo(Vector3 startPosition, Vector3 endPosition)
{
var flood = SomeFloodFiller.FloodFill(startPosition, endPosition, _floodFillDistance);
var path = flood.getPath(startPosition, endPosition);
return path.vectorList;
}
}
/*
This is an interface which abstracts away the actual Path calculation implementation
*/
public interface IPathCalculator
{
IEnumerable<Vector3> FindPathTo(Vector3 startPosition, Vector3 endPositiong);
}
/*
This entity uses IoC and composition which makes it easy to test as you can mock dependencies.
Also you can easily change the IPathCalculator provided, be it a manual argument pass or via a dependency injector,
this ultimately allows you to have more flexibility than you would if you were to use inheritance.
*/
public class SomeEntity
{
private IPathCalculator _pathCalculator;
private IPathFollower _pathFollower;
private Vector3 _position;
public SomeEntity(IPathCalculator pathCalculator, ISomePathFollower)
{
_pathCalculator = pathCalculator;
_pathFollower = pathFollower;
}
public void MoveTo(Vector3 destination)
{
var vectorList = _pathCalculator.FindPathTo(_position, destination);
_pathFollower.FollowPath(vectorList, this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment