2012-09-05 113 views
1

我有一个问题声明,我需要以运行时决定行为的方式来设计类。建议最适合的设计模式

该等级的等级如下;

     Base 
      ______________|________________ 
     |   |  |   |  
     Drvd-A  DrvdB  DrvdC Drvd-Generic 

类型的实例 “DRVD - 通用” 原则上应继承的任何类 “DRVD-A”, “DRVD-B” 或 “DRVD-C” 在运行时的行为。

实例“Drvd-Generic”的行为将在运行时决定,也可以在运行时更改。例如, ; - 创建的实例Drvd-Generic; - 在特定时间和特定条件下Drvd-Generic应该继承Drvd-A的行为; - 引发一些变化后Drvd-Generic应该继承Drvd-B的行为;

这会在运行时发生某些情况下发生,Drvd-Generic的实例在程序的生命周期中是相同的。

建议最适合的设计模式,以适应案件。

+0

试试[飞镖](http://www.codingthewheel.com/image.axd?picture=design_patterns_dartboard.jpg)。适用于我。 – 2012-09-05 08:04:00

回答

1

看起来像策略模式 w/composition会工作,你有一个Behavior类型的成员。 (伪代码如下)

class Behavior 
{ 
    virtual execute() = 0; 
} 
class BehaviorA 
{ 
    virtual execute(); 
} 
//and others 

class Base 
{ 
    Behavior* behavior; 
} 
class Drvd-A : Base 
{ 
    //set behavior to BehaviorA 
} 
//and others 
class Drvd-Generic 
{ 
    //set & change behavior at runtime 
} 
0

decorator pattern怎么样?

interface Base 
{ 
//This is the interface which specifies the members 
} 
class Drvd-Generic : Base 
{ 
//This implements the base class 
} 
class DrvdA : Base 
{ 
//This class has a member of type Drvd-Generic 
//The constructor accespts the Drvd-Generic object 
//This can define DrvdA specific functions to further work on it. 
//Basically this is the decorator class. 
//As are DrvdB and DrvdC 
} 
class DrvdB : Base 
{ 
} 
class DrvdC : Base 
{ 
} 

希望这可以帮助你。