Nic*_*ton 5 factory cross-platform interface
例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();
}
Run Code Online (Sandbox Code Playgroud)
例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();
}
Run Code Online (Sandbox Code Playgroud)
哪个是更好的选择,例如A,B,既不是,也不是"它取决于"?
我会说你明确的工厂选项(选项B)通常更好.
在你的第一个例子中,你的Foo类有效地完成了两个工作,它是一个工厂,它是一个代理.两个工作,一个班,让我感到不安.
你的第二个选择对客户承担更多的责任:他们需要知道使用工厂,但这是一个广泛使用的习语,我认为这不难理解.
A 的问题是你必须在 Foo 中实现 IFoo 的每个方法。如果只有几个,那没什么大不了的,但如果有几十个,那就很痛苦了。如果您正在使用支持工厂方法的语言,例如 Curl,那么您可以将工厂方法放入 IFoo 中:
{define-class abstract IFoo
{method abstract {bar}:void}
{factory {default}:{this-class}
{if platformA? then
{return {FooPlatformA}}
else
{return {FooPlatformB}}
}
}
}
{define-class FooPlatformA {inherits IFoo}
{method {bar}:void}
}
...
def foo = {IFoo}
{foo.bar}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
726 次 |
| 最近记录: |