Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would use the Strategy design pattern as you mentioned, but perhaps in a different context. The problem with trying to "shoe-horn" both <code>Foo</code> and <code>Component</code> into one class is that you could have combinations of implementations that would require duplicating code.</p> <p>For example, imagine you have the following implementations of <code>Component</code>: (Its been too long since Ive used Swing, these classes may not exist)</p> <ul> <li>JPanel</li> <li>JButton</li> <li>JMenu</li> </ul> <p>And you also had the following implementations of <code>Foo</code></p> <ul> <li>MyFoo</li> <li>HisFoo</li> <li>OurFoo</li> <li>WhatTheFoo</li> </ul> <p>And Imagine all the combinations of those: that's whats called a class explosion. This is the classic justification for the Strategy pattern.</p> <p>I would create a sort of container class that uses a <code>HAS-A</code> relationship for each of the needed classes instead of using the <code>IS-A</code> relationship as follows: (Im a c++ programmer, so you'll have to excuse the hybrid code :)</p> <pre><code>class ComponentFooHandler { Component component_; Foo fooImpl_; inline Foo getFoo() {return fooImpl_;} void setFoo(Foo f) {fooImpl_ = f;} Component getComponent() {return component_;} void setComponent(Component c) {component_ = c;} void doAction() { component_.someAction(); fooImpl_.anotherAction(); } } </code></pre> <p>You would then have to create different implementations of <code>Foo</code> seperately. Then the <code>Component</code> and <code>Foo</code> implementations can be combined as needed with out having to duplicate Foo impl code. Notice also that you can call methods that like <code>doAction()</code> that can operate on both <code>Foo</code> and <code>Component</code> without knowing their details, similar to a Template Pattern.</p> <p>To solve the issues with your original question:</p> <ul> <li>When a <code>Component</code> is needed, call <code>getComponent()</code> on a handler instance</li> <li>When a <code>Foo</code> is needed, call <code>getFoo()</code> on a handler instance</li> <li>I would avoid creating methods that need both in one and split the method args into 2</li> <li>Or just consider passing around a <code>ComponentFooHandler</code></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload