ATul Singh
ATul Singh

Reputation: 522

Single Copy of data to be accesed by different classes

I have a class containing lots of data members and functions , where each function has some own functionality and does some job using member variables of the class .

The major problem is there as the functions are added to the class , class code is growing bigger making it difficult to maintain.

Here this class is the interface which gets called and outputs some result.

I thought to make this class as base and make a derived class for each of the functions, which is independent of each other and can use common data members from the base class. But the problem here is that , every derived class will contain a separate copy of data members moreover the other module should have no knowledge of these derived class.

I know this may be a simpler problem , but can anyone point me out which design pattern can be referenced here.

Upvotes: 0

Views: 40

Answers (1)

Jens
Jens

Reputation: 9406

Implementation sharing should be better done by composition instead of inheritance. Inheritance models a is-a-relationship (Liskov substitution principle). From the description, it sounds like the class should be split into smaller classes with hopefully one single responsibility (single responsibility principle). Then, pass the classes to your client code as parameters in the constructor or in functions which need them. Sharing the object between more than one class can then be done by holding a pointer, reference or - recommended - a shared_ptr.

class BigClass {
public:
// lots of functions here
};

class Client1 {
public:
    Client1(std::shared_ptr<BigClass> b): mBigClass(b) {}

    void member() {
         // do something with mBigClass
    }
private:
    std::shared_ptr<BigClass> mBigClass;
};

But I recommend strongly thinking about splitting it (see interface segregation principle).

Upvotes: 1

Related Questions