Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It looks like the use of the <a href="http://en.wikipedia.org/wiki/Adapter_pattern" rel="nofollow">Adapter pattern</a>. The idea is to create a "view" of a class given another class, or adapt one type of class to act as another.</p> <p>A simple real world example can be that of electrical sockets. In different countries different types of sockets are used. So you use adapters to plug in your phone into an electrical socket it normally doesn't "recognize".</p> <p>This can of course be modelled using object oriented programming and the adapter pattern as well. Using your IModel interface but naming it IAdaptable it could be used like this.</p> <pre><code>public interface IAdaptable { &lt;T&gt; T adaptAs(Class&lt;T&gt; clazz); } public interface IChargeAmerican { void chargePhoneInAmerica(); } public interface IChargeEurope { void chargePhoneInEurope(); } public class EuropeanSocket implements IAdaptable, IChargeEurope { public &lt;T&gt; T adaptAs(Class&lt;T&gt; clazz) { if (clazz.equals(IChargeAmerican.class)) { return new EuropeanSocketToAmericanSocketAdapter(this); } throw new RuntimeException("unknown"); } public void chargePhoneInEurope() { ; } } public class AmericanSocket implements IChargeAmerican { public void chargePhoneInAmerica() { ; } } public class EuropeanSocketToAmericanSocketAdapter implements IChargeAmerican { private EuropeanSocket socket; public EuropeanSocketToAmericanSocketAdapter(EuropeanSocket socket) { this.socket = socket; } public void chargePhoneInAmerica() { socket.chargePhoneInEurope(); } } </code></pre> <p>And to use it one would simply adapt the european socket to an american one, sort of like plugging in an adapter in between the two.</p> <pre><code>public void foo() { EuropeanSocket europe = new EuropeanSocket(); IChargeAmerican murica = europe.adaptAs(IChargeAmerican.class); murica.chargePhoneInAmerica(); } </code></pre> <p>This example shows how the adaptAs method creates a link between the two interfaces IChargeAmerican and IChargeEurope. Even though they don't have anything in common the adapter can act as they do.</p> <p>Now, the EuropeanSocket implements the IAdaptable interface in order to "convert" itself to another known socket. Usually though the class should not be responsible for this. As the example at wikipedia shows, a factory or provider is better suited for this.</p>
 

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