Throughout a couple of projects I've found myself using this bizarre design pattern that I can't find the name of. Does it have a name? Perhaps it's just bad practice, you tell me.
The Design Pattern
With this pattern, you would have...
- An abstract base class (without abstract methods, we can discuss this later).
- Many "implementations" of the base class. However, these implementations would only serve to invoke the constructor of the base class.
A Java Example (with hypothetical scenario)
I will define a hypothetical scenario to provide some context.
Scenario:
Bob is writing a small API for scanning source code. He wants to be able to check if a comment starts/ends at a given index within the source code.
Here is Bob's code.
1. The Abstract Base Class
public abstract class CommentDetector {
private final String startPattern;
private final String endPattern;
protected CommentDetector(String startPattern, String endPattern) {
this.startPattern = startPattern;
this.endPattern = endPattern;
}
public boolean commentStartsAt(int index, String sourceCode) {
// ...
}
public boolean commentEndsAt(int index, String sourceCode) {
// ...
}
}
You may be wondering why it is abstract but has no abstract methods. This is simply because Bob doesn't want you to instantiate it directly. Bob wants you to write an implementation of CommentDetector
and then instantiate that instead. Here are two of Bob's implementations...
2. Some Implementations
One for multi-line comments in Java:
public class JavaMultiLineCommentDetector extends CommentDetector {
public JavaMultiLineCommentDetector() {
super("/*", "*/");
}
}
One for single-line comments in Java:
public class JavaSingleLineCommentDetector extends CommentDetector {
public JavaSingleLineCommentDetector() {
super("//", "\n");
}
}
Bob has written these implementations for us so that we can write new JavaMultiLineCommentDetector()
instead of new CommentDetector("/*", "*/")
.
Bob also encourages you to write your own implementations for other languages if need be.
Summary
-
It feels like the intent of this design pattern is to improve readability of the code by pre-defining constructor calls.
-
This design pattern gives a polymorphic feel to the code (even though it may/may not be truly polymorphic).
-
Writing new implementations is quick and easy.
Does this design pattern have a name?
Thank you.
Aucun commentaire:
Enregistrer un commentaire