I am arguing a bit with my teacher about if this is a factory pattern or not. can i get some of your guys input?
public class UrlFactory {
private static boolean testMode;
private static long testDate;
public static URLConnection fetchConnection(String url)
throws IOException
{
URL address = new URL(url);
if(testMode)
return new MockURLConnection(address, testDate);
return address.openConnection();
}
public static void SetTestMode(long testDate)
{
UrlFactory.testMode = true;
UrlFactory.testDate = testDate;
}
public static void UnSetTestMode()
{
UrlFactory.testMode = false;
}
}
It looks structurally similar to a factory, but I would say it misses the point of the factory pattern. Ideally, a factory is instantiable and overrideable (e.g. has a virtual method for creation). I would recommend a design where UrlFactory
is a non-static class with a virtual fetchConnection
method. You can then have a derived class MockUrlFactory
which overrides fetchConnection
to return a MockURLConnection
.
Example:
public class UrlFactory {
public URLConnection fetchConnection(String url)
throws IOException {
URL address = new URL(url);
return address.openConnection();
}
}
public class MockUrlFactory extends UrlFactory {
private long testDate;
public MockUrlFactory(long testDate) {
this.testDate = testDate;
}
public URLConnection fetchConnection(String url)
throws IOException {
URL address = new URL(url);
return new MockURLConnection(address, testDate);
}
}