1

我有一个问题陈述,我需要以一种在运行时决定行为的方式设计类。

类层次结构如下;

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

“Drvd-Generic”类型的实例原则上应该继承任何类“Drvd-A”、“Drvd-B”或“Drvd-C”在运行时的行为。

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

这将在运行时在某些条件下发生,并且 Drvd-Generic 的实例在程序的生命周期内将是相同的。

建议最适合的设计模式以适应这种情况。

4

3 回答 3

2

Drvd-Generic可以实现策略模式,并使用DrvdA/ DrvdBetc 的内部实例来完成它的工作。

于 2012-09-05T07:44:46.253 回答
1

似乎带有组合的策略模式会起作用,其中您有一个 type 成员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
}
于 2012-09-05T07:46:11.833 回答
0

装饰器模式怎么样?

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
{
}

希望这对您有所帮助。

于 2012-09-07T11:02:41.787 回答