这不是工厂模式吗?

And*_*ome 0 java factory-pattern

我和老师争论这是否是工厂模式.我可以让你的一些人输入吗?

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

bob*_*mcr 12

它看起来在结构上类似于工厂,但我会说它错过了工厂模式的要点.理想情况下,工厂是可实例化和可重写的(例如,具有用于创建的虚拟方法).我建议设计UrlFactory一个带有虚fetchConnection方法的非静态类.然后,您可以拥有一个派生类MockUrlFactory,该类将覆盖fetchConnection返回a MockURLConnection.

例:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)