0

Can someone give me the name of the following OOP concept (if it is indeed, an OOP concept at all!):

I have two classes: A & B. Both have say, 2 methods each (all different). Now I create a third class, C. Now I want to expose all of A & B's methods to C. Here is some sort of demonstration:

class A
    int method_in_A_one() {
    }

    int method_in_A_two() {
    }
end

class B
    int method_in_B_one() {
    }

    int method_in_B_two() {
    }
end

class C
    C() {
        A an_instance_of_a;
        B an_instance_of_b;
    }
}

Now I want to be able to do this:

C instance_of_c = new C;

insance_of_c.method_in_A_one();
insance_of_c.method_in_A_two();
insance_of_c.method_in_B_one();
insance_of_c.method_in_B_two();

I don't really have a use for this yet, but I'm sure theres a specific concept dealing with it. Thanks in advance, ell.

Ell
  • 4,238
  • 6
  • 34
  • 60

3 Answers3

3

This is about object composition and delegation:

  • object composition is when your class is composed by other classes (in the example - C is composed by A and B)
  • delegation is when there a method in the owning class that delegates to methods of the composing classes

In the languages I know, delegation is achieved manually - you have to declare the method in C and invoke the underlying object's respective method.

Note that there's another option to achieve this - multiple inheritance, although your example does not show exactly that. This means that C is both A and B. Some languages prohibit that though, and object composition is considered a better practice anyway.

Community
  • 1
  • 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
3

So there's a few things going on here. Your C type was created by composition of the A and B types, which is a common alternative to subclassing.

If the intention of C is to provide a simpler interface to working with A and B, that would be an example of the facade pattern.

If C provides additional functionality to its wrapped objects (say, by having its implementation of method_in_A_one do some additional work before calling it on the wrapped object) that would be an example of the decorator pattern.

If C translates concepts in A/B into a form that another library expects (example: wrapping a C++ std::map in an NSDictionary subclass for use in Cocoa), that would be the adaptor pattern.

Catfish_Man
  • 41,261
  • 11
  • 67
  • 84
0

Sounds like multiple inheritance, or a common interface. But not quite as you encapsulate both A and B in C while not exposing either as a base class.

leppie
  • 115,091
  • 17
  • 196
  • 297