假设我有一个执行某项任务的函数(这是Python伪代码):
def doTask():
...
但是我在平台上有几个可选功能,导致代码看起来像这样:
def doTask():
...
if FEATURE_1_ENABLED:
...
if FEATURE_2_ENABLED:
...
...
不幸的是,这会让许多不同的可选功能彼此重合,从而导致相当混乱。什么样的设计模式解决了这个问题?
答案 0 :(得分:4)
这就是命令和策略的全部内容。以及撰写。
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 )
您可以撰写功能,委派功能,继承功能。这对于一组可扩展的可选功能非常有用。
答案 1 :(得分:1)
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();
}
}
我认为它叫战略模式
语法可能不准确