0

我有许多类与基类及其继承形成类层次结构。每个类都相当大,承担了几个职责,尽管这些职责不是耦合的。我将不同的职责放在一个类中,因为我可以很容易地一致地使用它们(我不能很清楚地表达出来,请参阅说明代码)。但这似乎不是一个好的设计。如何在保持易于使用的同时拆分大类?感谢您的建议和意见!下面请找到说明代码。

// Base class.
class Base
{
public:
    // For responsibility A
    virtual void A1();
    virtual void A2();
    ...

    // For responsibility B
    virtual void B1();
    virtual void B2();
    ...

    // More responsibilites.
    ...
};

// Derived class 1.
class Derived_1 : public Base
{...};

// More derived classes.
...

// A function use it.
void Fun()
{
    Base* p = new Derived_1;
    p->A1(); // Here A1 and B1 are binded in the class Base, thus it make sure
    p->B1(); // their uses are consistent. If they are separated, how to ensure it? 
}
4

2 回答 2

2

通过在一个类中拥有多个职责,您就打破了设计的单一职责原则

一般来说,好的设计遵循SOLID原则。

打破你的课程。

  1. 为每个职责定义一个接口。
  2. 尽量不要使用多重继承,而是使用组合

我添加了一些示例代码来说明这个概念:

#include <iostream>

//Interface for A
class ResponsibilityA
{
    public:
    virtual ~ResponsibilityA(){};
        virtual void A1() = 0;
        virtual void A2() = 0;
};


//Interface for B
class ResponsibilityB
{
        public:
    virtual ~ResponsibilityB(){};
        virtual void B1() = 0;
        virtual void B2() = 0;
};

//Concrete classes for each interface
class ResponsibilityAExecutor : public ResponsibilityA
{
        public:
        virtual void A1(){ std::cout<<"A1 executed\n"; };
        virtual void A2(){ std::cout<<"A2 executed\n"; };
};

class ResponsibilityBExecutor : public ResponsibilityB
{
        public:
        virtual void B1(){ std::cout<<"B1 executed\n"; }
        virtual void B2(){ std::cout<<"B2 executed\n"; }
};

// Now we use the interface implementations in a class that needs
// to combine both responsibilities
class PlanExecutor
{
public:
        PlanExecutor( ResponsibilityA& a, ResponsibilityB& b ) : 
        a_(a),
        b_(b)
        {

        }
        void ExecutePlan()
        {
                std::cout<<"Executing first part of the plan:\n";
                a_.A1();
                b_.B1();
                std::cout<<"Executing second part of the plan\n";
                a_.A2();
                b_.B2();
        }
private:
        ResponsibilityA &a_;
        ResponsibilityB &b_;    
};

int main()
{
        ResponsibilityAExecutor a;
        ResponsibilityBExecutor b;
        PlanExecutor p(a,b);
        p.ExecutePlan();
        return 0;
}

最后,我还需要强调命名的重要性。

于 2013-02-05T01:42:29.090 回答
0

我会说,如果 A 和 B 的职责完全不同,则为它们创建单独的类,并让孩子以这种方式实现他们想要的东西,一些孩子只想要 A 或只想要 B 或两者兼而有之,并且它保持可管理和可维护

// Base class.
class Base
{
public:
    // For responsibility A
**Goes to class A**
    virtual void A1();
    virtual void A2();
    ...


**//Goes to class B**
    // For responsibility B
    virtual void B1();
    virtual void B2();
    ...

    // More responsibilites.
    ...
};

// Derived class 1.
class Derived_1 : public Base **//inherits from A**
{...}; 

class Derived_2:Public A,Public B
于 2013-02-05T01:33:57.100 回答