sách gpt4 ai đã đi

Tôi có nên sử dụng giao diện hay nhà máy (và giao diện) để triển khai đa nền tảng không?

In lại 作者:行者123 更新时间:2023-12-04 19:21:34 31 4
mua khóa gpt4 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();
} khác {
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();
} khác {
return new FooPlatformB();
}
}
}

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

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

1 Câu trả lời

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

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

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

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

31 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com