Monday, 22 June 2015

Java: One use-case for having a singleton class

Let's consider the following class:

class StringLengthComparator {
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
}

The StringLengthComparator class is stateless: it has no fields, hence all instances of the class are functionally equivalent.
Thus it should be a singleton to save on unnecessary object creation costs:

class StringLengthComparator {
private StringLengthComparator() {
}

public static final StringLengthComparator INSTANCE = new StringLengthComparator();

public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
}

Improvement:
-----------------
To be able to work with other comaprison strategies, we go with intaerface approach as follows:

// Strategy interface
public interface Comparator<T> {
public int compare(T t1, T t2);
}

The Comparator interface is generic so that it's applicable to comparators for objects other than strings

class StringLengthComparator implements Comparator<String> {
... // class body is identical to the one shown above
}

No comments:

Post a Comment