Have you ever needed to create say a family of builders all with common methods on and also wanted to use a fluent style for the builders?
You may have found yourself doing things like defining protected “do” methods to perform the common functions on the abstract base class and then wrapping those on your concrete subclasses, like this:
It would be super nice if the compiler could magically figure out that I want to return the subclass type… in C++ this is pretty trivial:
Calling DoSomethingFooBuilder will return a pointer to FooBuilder.
But C# and Java are a bit more strict when it comes to type casting… so how does one achieve this in those languages?
C#
Being a little more strict on type casting, the solution in C# is to provide a marker interface that will allow you to constrain your builder type to actually a Builder of the type you want to build.
This way your abstract base class implements the marker interface and constrains R to that type:
This works because it allows you to specify that the type R is type compatible with AbstractBuilder without actually being the AbstractBuilder. The compiler wont allow you to static cast this up to R, but you can use the safe casting which will always work provided your implementing classes specify themselves as type R.
Java
The same trick for C# also works in Java, although there are few Java-isms to to get the equivalent behaviour we have for our C#, specifcally providing the abstract method for getting the instance (although this isn’t really an issue for the pattern).
Bringing it All Together
I’ve provided complete working single file examples for C++, C# and Java below.
C++
C#
Java
Conclusion
I’m not sure if this is a named pattern or not, but it definitely fits what I would consider the description of a design pattern.
The purpose of this design pattern is to be able to share common functions of fluent-like interfaces and might typically be applied to the builder pattern for example.
Intent: Allow a subclass to automatically override the return type of a method on its parent class
The general class diagram for the pattern is:
General:Class diagram for the general case of the pattern.
And in the case of Java like languages:
Java/C#:Class diagram for the pattern in the case of java like languages.