3

假设我有一个执行某些任务的函数(这是在 Python 伪代码中):

def doTask():
    ...

但是我在平台上有几个可选功能,导致代码看起来像这样:

def doTask():
    ...
    if FEATURE_1_ENABLED:
        ...
    if FEATURE_2_ENABLED:
        ...
    ...

不幸的是,这变得相当混乱,许多不同的可选功能相互一致。什么样的设计模式可以解决这个问题?

4

2 回答 2

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 )

您可以组合特征、委托特征、继承特征。这对于一组可扩展的可选功能非常有效。

于 2009-08-25T02:10:52.627 回答
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();
}

}

我认为这叫做策略模式

语法可能不准确

于 2009-08-25T02:10:15.030 回答