Decipher Eclipse Architecture: IAdaptable – Part 2 – Simple Example

Adapter Design Pattern

How Adapter design pattern is used in Eclipse platform? Eclipse Platform Runtime has a good example of this pattern.

First of all, Adapter design pattern has a simple idea behind – wrapping the object and making it to be compatible to another interface clients expect. You can take a look at the simplest adapter idea in my previous post.

How adapters are used in eclipse are slightly different and more complex. In the following example, classes and interfaces are put in one file for simplicity purpose.

The class hierarchy is shown in the diagram below.

Eclipse IAdaptable

When we want to go from oranges to apples, adapter comes into place. The following code shows what it does, no complex work flow from Eclipse.

interface IAdaptable{
	public Object getAdapter(Class adapter);
}
 
interface IApple extends IAdaptable{ }
 
interface IOrange{ }
 
class Orange implements IOrange{ }
 
interface IPear{ }
 
class Pear implements IPear{ }
 
public class Apple implements IApple{	
	@Override
	public Object getAdapter(Class adapter) {
		//the real story should be forwarding the request to the platform to get adapter
		return PlatformAdapterManager.getAdapter(this, adapter);
	}	
}
 
class PlatformAdapterManager{
	public static Object getAdapter(Object o, Class adapter){
		if(adapter == IOrange.class){
			if(o instanceof Apple){
				return new Orange(); //Read code use an adapter to wrap the apple object and return an adapter object which implements IApple interface
			}
		}else if(adapter == IPear.class){
			if(o instanceof Apple){
				return new Pear();
			}
		}
		return null; //return null when the class does not implement the interface.
	}
}

PlatformAdapterManager class is totally made up, real story in eclipse is platform get adapter manager to return a proper adapter.

public class Main {	
	public static void main(String args[]){
		IApple apple = new Apple();
		IOrange orange = (IOrange)apple.getAdapter(IOrange.class);
 
		if(orange == null){
			System.out.println("null");
		}else{
			System.out.println(orange);
		}
 
		IPear pear = (IPear)apple.getAdapter(IPear.class);	
		if(pear == null){
			System.out.println("null");
		}else{
			System.out.println(pear);
		}
	}
}

Output:
Orange@4fe5e2c3
Pear@23fc4bec

This is the approach of implementing the getAdapter() method in the class itself. This approach does not require registration with class, since implementation is in the getAdapter() method.

In another way that is used in Eclipse, no code changes in class are required, getAdapter method is contributed by a factory. Check out this post to see the real story.

References:

corner article.

Leave a Comment