I have a question similar to this other question
Why aren't design patterns added to the languages constructs?
Why isn't there java.util.Singleton
and then we inherit it? The boilerplate code seems to be always the same.
class Singleton {
private static final Singleton s = new Singleton();
public static Singleton getInstance() {
return s;
}
protected Singleton() {
}
}
class XSingleton extends Singleton {
}
Now if there was a Singleton
built-in to Java then we wouldn't have to include the same boiler-plate over and over in projects. We could just inherit the code that makes the Singleton and just code our specific in our XSingleton
that extends Singleton
.
I suppose the same goes for other design patterns e.g. MVC and similar. Why aren't more design pattern built into the standard libraries?
Best Answer
I want to challenge your basic premise, namely that Design Patterns aren't added to the standard library. For example,
java.util.Iterator<E>
is in the standard library and is an implementation of the Iterator Design Pattern.java.util.Observable
/java.util.Observer
is an implementation of the Publish/Subscribe Design Pattern.java.lang.reflect.Proxy
is an implementation of the Proxy Design Pattern.Looking at other languages, e.g. Ruby has the
delegate
andforwardable
libraries, both implementations of the Proxy Design Pattern, theobserver
library, an implementation of the Publish/Subscribe Pattern, and thesingleton
library, an implementation of the Singleton Design Pattern.