gpt4 book ai didi

interface - 我应该为跨平台实现使用接口(interface)还是工厂(和接口(interface))?

转载 作者:行者123 更新时间:2023-12-04 19:21:34 30 4
gpt4 key购买 nike

示例 A:

// pseudo code
interface IFoo {
void bar();
}

class FooPlatformA : IFoo {
void bar() { /* ... */ }
}

class FooPlatformB : IFoo {
void bar() { /* ... */ }
}

class Foo : IFoo {
IFoo m_foo;
public Foo() {
if (detectPlatformA()} {
m_foo = new FooPlatformA();
} else {
m_foo = new FooPlatformB();
}
}

// wrapper function - downside is we'd have to create one
// of these for each function, which doesn't seem right.
void bar() {
m_foo.bar();
}
}

Main() {
Foo foo = new Foo();
foo.bar();
}

示例 B:
// pseudo code
interface IFoo {
void bar();
}

class FooPlatformA : IFoo {
void bar() { /* ... */ }
}

class FooPlatformB : IFoo {
void bar() { /* ... */ }
}

class FooFactory {
IFoo newFoo() {
if (detectPlatformA()} {
return new FooPlatformA();
} else {
return new FooPlatformB();
}
}
}

Main() {
FooFactory factory = new FooFactory();
IFoo foo = factory.newFoo();
foo.bar();
}

哪个是更好的选择,例如 A、B、两者都不是,还是“取决于”?

最佳答案

我会说您的显式工厂选项(选项 B)通常更好。

在您的第一个示例中,您的 Foo 类有效地完成了两项工作,它是一个工厂,它是一个代理。两份工作,一个类,让我感到不安。

您的第二个选项让客户承担更多责任:他们需要知道使用工厂,但这是一个如此广泛使用的成语,我认为不难理解。

关于interface - 我应该为跨平台实现使用接口(interface)还是工厂(和接口(interface))?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2997987/

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