【问题标题】:Is there a good design pattern for implementing optional features?是否有实现可选功能的良好设计模式?
【发布时间】:2009-08-25 02:02:38
【问题描述】:
假设我有一个执行某些任务的函数(这是 Python 伪代码):
def doTask():
...
但我在平台上有几个可选功能,导致代码看起来像这样:
def doTask():
...
if FEATURE_1_ENABLED:
...
if FEATURE_2_ENABLED:
...
...
不幸的是,这相当与许多不同的可选功能相互吻合。什么样的设计模式可以解决这个问题?
【问题讨论】:
标签:
design-patterns
options
【解决方案1】:
这就是 Command 和 Strategy 的全部意义所在。以及作曲。
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 )
您可以组合特征、委托特征、继承特征。这对于一组可扩展的可选功能非常有效。
【解决方案2】:
interface Feature{
void execute_feature();
}
class Feature1 implements Feature{
void execute_feature(){}
}
class Feature2 implements Feature{
void execute_feature(){}
}
public static void main(String argv[]){
List<Feature> my_list = new List<Feature>();
my_list.Add(new Feature1());
my_list.Add(new Feature2());
for (Feature f : my_list){
f.execute_feature();
}
}
我认为这叫策略模式
语法可能不准确