views:

1055

answers:

1

I am a Java beginner and I would appreciate it if someone here can explain how to implement Martin Fowler's plugin pattern in Java.

Thanks in advance.

+6  A: 

Simply, you define an interface for the operations you want to do, and pass an object at run time that implements that interface. So, for example, you might have communications through local shared memory and through remote TCP/IP. You build an interface, call it IConnection that has send() and recv(), and then implement it in two classes, LocalConnection and LongDistanceConnection.

You then have some other class that needs to communicate, let's say TelephoneCall.

To make a local call, you do

TelephoneCall call = new TelephoneCall(new LocalConnection());

To make a long distance call, you do

TelephoneCall call = new TelephoneCall(new LongDistanceConnection());

and the signature of the constructor is

 public TelephoneCall(IConnection connect);
Charlie Martin
@Charlie Martin, thank you.
Happy to help. Tip the wait staff as you leave.
Charlie Martin
This seems not to answer the pattern intent: Links classes during configuration rather than compilation. The same example implemented using let's say Spring DI would do it.
grigory
@grigory, I don't follow. a new happens at run time. if you don't want to do it in the ctor, it's no problem to have another method setConnection(Iconnection), but would that explain the pattern any better?
Charlie Martin
@Charlie: there is nothing else that may happen at runtime except "new LocalConnection()" because it was actually compiled, right. Hence, is my little comment on linking classes during compilation. Using Spring DI (or other DI tool for that matter) we can change this using configuration (say in xml files). No problems other that that.
grigory