c++ - 可选成员对象

标签 c++ design-patterns refactoring

好的,所以您在系统的主类周围散布了很多方法。所以你做正确的事并通过创建一个新类重构并将移动方法执行到一个新类中。新类(class)只有一个职责,世界又恢复正常了:

class Feature
{
public:
    Feature(){};

    void doSomething();
    void doSomething1();
    void doSomething2();   
};

所以现在你原来的类有一个对象类型的成员变量:

  Feature _feature;

您将在主类中调用它。现在,如果您多次执行此操作,您的主类中将有许多成员对象。

现在可能需要或不需要这些功能取决于配置,因此在某种程度上,拥有所有这些可能需要或不需要的对象的成本很高。

谁能提出改进方法?


编辑:根据使用空对象设计模式的建议,我想出了这个:

定义功能接口(interface)的抽象类:

class IFeature
{
public:
    virtual void doSomething()=0;
    virtual void doSomething1()=0;
    virtual void doSomething2()=0;

    virtual ~IFeature(){}
};

然后我定义了两个实现接口(interface)的类,一个是真正的实现,一个是空对象:

class RealFeature:public IFeature
{
public:
    RealFeature(){};

    void doSomething(){std::cout<<"RealFeature doSomething()"<<std::endl;}
    void doSomething1(){std::cout<<"RealFeature doSomething()"<<std::endl;}
    void doSomething2(){std::cout<<"RealFeature doSomething()"<<std::endl;}
}; 

class NullFeature:public IFeature
{
public:
    NullFeature(){};

    void doSomething(){std::cout<<"NULL doSomething()"<<std::endl;};
    void doSomething1(){std::cout<<"NULL doSomething1()"<<std::endl;};
    void doSomething2(){std::cout<<"NULL doSomething2()"<<std::endl;};


};

然后我定义了一个 Proxy 类,它将根据配置委托(delegate)给真实对象或空对象:

class Feature:public IFeature
{
public:
    Feature();
    ~Feature();

    void doSomething();
    void doSomething1();
    void doSomething2();

private:
    std::auto_ptr<IFeature> _feature;
};

实现:

   Feature::Feature()
    {
        std::cout<<"Feature() CTOR"<<std::endl;
        if(configuration::isEnabled() )
        {
            _feature = auto_ptr<IFeature>( new RealFeature() );
        }
        else
        {
            _feature = auto_ptr<IFeature>( new NullFeature() );
        }
    }


    void Feature::doSomething()
    {
        _feature->doSomething();
    }

    //And so one for each of the implementation methods

然后我在主类中(或任何需要的地方)使用代理类:

Feature _feature;

_feature.doSomething();

最佳答案

如果缺少某个功能,而正确的做法是忽略该事实而不做任何事情,您可以使用 Null Object pattern 取消检查:

class MainThing {
    IFeature _feature;

    void DoStuff() {
        _feature.Method1();
        _feature.Method2();
}

interface IFeature {
    void Method1();
    void Method2();
}

class SomeFeature { /* ... */ }

class NullFeature {
    void Method1() { /* do nothing */ }
    void Method2() { /* do nothing */ }
}

现在,在 MainThing 中,如果不存在可选功能,您可以为其提供对 NullFeature 的引用,而不是实际的 null 引用。这样,MainThing 始终可以安全地假设 _feature 不是 null

关于c++ - 可选成员对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3027067/

相关文章:

C++ 帮助 - getline

c# - 需要设计模式建议

javascript - 用于将 block 写入文件的事件驱动模式 - JS

c# - 失控的 switch 语句的最佳替代方法是什么?

java - 将读取两个文件的两种方法合并为用一种方法读取一个文件

c# - 如何在不进行大量重写的情况下在现有的 asp.net-mvc 站点上添加新路由?

c++ - 通过 union 合法访问 __m128 变量的字节吗?

c++ - 使用 glUniformMatrix2fv 传递 glm::vec2 类型时出现 DEBUG_TYPE_ERROR

language-agnostic - 如何解决违反迪米特法则的问题?

c++ - C++中的大量线程和效率