0

Suppose that I have multiple instances I1, I2, I3, etc. of a set of classes C1, C2, etc. Suppose that these classes are all inheriting from a super-class S.

Suppose that there is an operation O(a, b) that takes two instances of S and see if they are compatible (compatible in some since.) In order to check for compatibility, however, O has to know the type of a, and b (C1, or C2, ...) and the operation can only be done once the types are known.

The basic way to implement O would be to write if statements everywhere to check the types, and then run the operation. This is not ideal because there are many cases to cover and because it is not extendable.

Is there a pattern associated with these sorts of problems? Away to write an extendable operation that is based on types?

  • 1
    What language are you using? – Emerson Cardoso Oct 18 '17 at 18:53
  • You don't need inheritance then. Just pass instances of expected type. – Fabio Oct 18 '17 at 19:10
  • Since you tagged it "SOLID" it is worth to mention that your design violates the DI principle. Your operation O should depend on abstractions and not care about the concrete implementations. – Stop harming Monica Oct 18 '17 at 19:31
  • 1
    Double dispatch is the usual technique. – Frank Hileman Oct 18 '17 at 22:20
1

I think the pattern you are looking for is the Visitor Pattern along with double-dispatch

A good SO Question I found here applies

The gist of it is that you have an object with an 'Accept' method which has a 'visitor' object as a parameter. Here's a C++ example (sorry if this isn't what you're using)

//each subtype of object will override this function and will have the same body
virtual Object::Accept(Visitor* v){
    v->visit(this);
}

Object passes itself to the visitor's method Visit. Here's the cool part

class Visitor{
   Vist(ObjectSub1* s);
   Vist(ObjectSub2* s);
   Vist(ObjectSub3* s);
}

The key is that Object::Accept is overloaded for each subtype to pass 'this' (which returns a pointer to the current subtype). Basically, each subtype knows what subtype it is, so when it passes itself to the overloaded visitor function "Visit" the correct function is called

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.