假设我有一个执行某些任务的函数(这是在 Python 伪代码中):
def doTask():
...
但我在平台上有几个可选功能,导致代码如下所示:
def doTask():
...
if FEATURE_1_ENABLED:
...
if FEATURE_2_ENABLED:
...
...
不幸的是,由于许多不同的可选功能彼此重合,这变得相当困惑。什么样的设计模式可以解决这个问题?
最佳答案
这就是命令和策略的意义所在。以及组成。
class Command( object ):
def do( self ):
raise NotImplemented
class CompositeCommand( Command, list ):
def do( self ):
for subcommand in self:
subcommand.do()
class Feature_1( Command ):
def do( self, aFoo ):
# some optional feature.
class Feature_2( Command ):
def do( self, aFoo ):
# another optional feature.
class WholeEnchilada( CompositeCommand ):
def __init__( self ):
self.append( Feature_1() )
self.append( Feature_2() )
class Foo( object ):
def __init__( self, feature=None ):
self.feature_command= feature
def bar( self ):
# the good stuff
if self.feature:
self.feature.do( self )
您可以组合功能、委托(delegate)功能、继承功能。这对于一组可扩展的可选功能非常有效。
关于design-patterns - 是否有用于实现可选功能的良好设计模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1325699/