0

我知道标题不是很清楚。

我有一个名为 Plot 的类,并且有 2 个类继承自 Plot。

class Plot
{
}

class DynamicPlot : public Plot
{
}

class StaticPlot : public Plot
{
}

我想添加一些名为 PhasePlot、RPMPlot 的类。我还希望这些类可以是动态的或静态的。

所以,我首先想到的是:

class DynamicPhasePlot : public DynamicPlot 
{
}

class DynamicRPMPlot : public DynamicPlot 
{
}

class StaticPhasePlot : public StaticPlot 
{
}

class StaticRPMPlot : public StaticPlot 
{
}

这似乎不是一个很好的解决方案。我搜索了装饰器模式,但我认为它不符合我的需要。但是,我不太确定。

4

2 回答 2

1

不幸的是,您没有提供绘图的用例(以及动态/静态的上下文或关注点)。但是,InterfaceDecoratorComposition over Inheritance (strategy pattern)这里适用。

接口:

interface IPlot //this is optional
interface IDynamicPlot : IPlot
interface IStaticPlot : IPlot
// depending on context, the IPhasePlot can be defined as 
// IDynamicPhasePlot inherited from IDynamicPlot. Same as for static.
interface IPhasePlot : IPlot
interface IRPMPlot : IPlot
class Plot : IPlot
class DynamicPlot : IDynamicPlot
//etc

策略模式:

如果派生图依赖于Dynamic或,请使用此选项Static。它充当外观类。

class DynamicRPMPlot{
    IDynamicPlot dynamicPlot = new DynamicPlot(); //you can do constructor injection here
    IRPMPlot rPMPlot = new RPMPlot(); //you can do constructor injection here

    public void DoSomething(){
        dynamicPlot.DoSomething();
        // you can also migrate the implementation of RPMPlot to here,
        //if it has different cases for dynamic or static
        rPMPlot.DoSomething();
    }
}

装饰图案:

如果RPManddynamic被关注,请使用此选项。

class RPMPlot : IRPMPlot {
    RPMPlot(IPlot decorated){
        // can place null guard here
        this.decorated = decorated;
    }
    IPlot decorated;

    public void DoSomething(){
        decorated.DoSomething(); //you can change the sequence
        //implementation of rpmplot
    }
}

void ConsumePlot(){
    IPlot plot = new RPMPlot(new DynamicPlot());
    plot.DoSomething();
}
于 2013-08-05T16:31:48.283 回答
0

动态或静态是绘图的行为。因此,DynamicPlot 是具有动态行为的 Plot,而 StaticPlot 是具有静态行为的 Plot。可以使用 StrategyPattern 动态设置此行为,而不是创建诸如 DynamicPlot 或 StaticPlot 之类的新类。

public enum PlotBehavior
{
   None,
   Dynamic,
   Static
}

public class Plot
{
   private PlotBehavior m_Behavior;
   public Plot()
   {
   }
   public SetBehavior(PlotBehavior ieBehavior)
   {
     this.m_Behavior = ieBhavior;
   }
}

现在,我们的 Plot 类可以被实例化并用作动态或静态图。现在,我们可以将其子类化为更具体的类,如下所示。

public PhasePlot: public Plot
{
}

public RPMPlot: public Plot
{
}

你明白了!

于 2013-08-05T14:38:11.587 回答