gpt4 book ai didi

java - 这不是工厂模式吗?

转载 作者:行者123 更新时间:2023-12-01 06:31:08 24 4
gpt4 key购买 nike

我正在和老师争论这是否是工厂模式。我可以得到你们的一些意见吗?

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;
}
}

最佳答案

它在结构上看起来与工厂类似,但我想说它忽略了工厂模式的要点。理想情况下,工厂是可实例化和可重写的(例如具有用于创建的虚拟方法)。我建议采用一种设计,其中 UrlFactory 是一个带有虚拟 fetchConnection 方法的非静态类。然后,您可以拥有一个派生类 MockUrlFactory,它重写 fetchConnection 以返回 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);
}
}

关于java - 这不是工厂模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10577008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com