You can first extract the common behavior(s) into simple classes which only implement IFollow
:
public sealed class FollowTarget : IFollow
{
public Transform Target {get; set;}
public void LateUpdate() { //follow the target }
}
public sealed class FollowSomethingElse : IFollow
{
public Transform Target {get; set;}
public void LateUpdate() { //follow something else }
}
Then use the required implementation in A
, B
, C
:
public sealed A : Monobehaviour , IFollow {
private readonly IFollow _follow;
public A() => _follow = new FollowTarget();
public Transform Target {get => _follow.Target; set => _follow.Target = value; }
public void LateUpdate() => _follow.LateUpdate();
}
public sealed B : Monobehaviour , IFollow {
private readonly IFollow _follow;
public B() => _follow = new FollowTarget();
public Transform Target {get => _follow.Target; set => _follow.Target = value; }
public void LateUpdate() => _follow.LateUpdate();
}
public sealed C : Monobehaviour , IFollow {
private readonly IFollow _follow;
public C() => _follow = new FollowSomethingElse();
public Transform Target {get => _follow.Target; set => _follow.Target = value; }
public void LateUpdate() => _follow.LateUpdate();
}
Then at this point you may see that A
/C
or B
/C
share the same implementation except that you don't instanciate the same _follow
. In this case you can require an IFollow
in the constructor and refactor (simplify) your code like this:
public sealed AorC : Monobehaviour , IFollow {
private readonly IFollow _follow;
public AorC(IFollow follow) => _follow = follow;
public Transform Target {get => _follow.Target; set => _follow.Target = value; }
public void LateUpdate() => _follow.LateUpdate();
}
public sealed B : Monobehaviour , IFollow {
private readonly IFollow _follow;
public B() => _follow = new FollowTarget();
public Transform Target {get => _follow.Target; set => _follow.Target = value; }
public void LateUpdate() => _follow.LateUpdate();
}
Usage beeing
var a = new AorC(new FollowTarget());
var c = new AorC(new FollowSomethingElse());
This approach is usually named Decorator and is a specialized form of composition which fosters a more composable code.
is an
setup for a base class then.