Studyon Minte9.com
Head First (Patterns)




Adapter Pattern



The Adapter Pattern converts the interface of a class into another interfece the client expects.

	%java
		package testapptmp;

		public class Testapptmp {
		    
		    public static void main(String[] args) {        
			
			WildTurkey turkey = new WildTurkey();
			
			/* --- Look Here --- */
			
			Duck turkeyAdapter = new TurkeyAdapter(turkey); 
			turkeyAdapter.quack();
			    // Output: gobble
		    }
		}

		interface Duck {
		    public void quack();
		}

		interface Turkey {
		    public void gobble();
		}

		class WildTurkey implements Turkey {
		    
		    @Override
		    public void gobble() {
			System.out.println("gobble");
		    }
		}

		class TurkeyAdapter implements Duck {
		    Turkey turkey;
		    
		    public TurkeyAdapter(Turkey turkey) {
			this.turkey = turkey;
		    }
		    
		    @Override
		    public void quack() {
			turkey.gobble();
		    }
		}


We are often face with old code that expose the Enumeration interface, yet we'd like for our new code to 
only use Iterators.

	%java
		package testapptmp;

		import java.util.Enumeration;
		import java.util.Vector;
		import java.util.Iterator;

		public class Testapptmp {
		    
		    public static void main(String[] args) {        
			
			Vector names = new Vector();
			names.add("John");
			names.add("Mary");
			
			// Enumeration (old code)
			Enumeration A = names.elements();
			while (A.hasMoreElements()) {
			    System.out.println("A: " + A.nextElement());
			}
			
			// Iterator (new code)
			Iterator B = names.iterator();
			while (B.hasNext()) {
			    System.out.println("B: " + B.next());
			}

			/* --- Look Here --- */
				
			// Adaptor (using old objects with new code)
			Enumeration C = names.elements();
			EnumerationIterator CC = new EnumerationIterator(C);
			while (CC.hasNext()) {
			    System.out.println("C: " + CC.next());
			}
			
			/* Output:
				A: John
				A: Mary
				B: John
				B: Mary
				C: John
				C: Mary */
			
		    }
		}

		class EnumerationIterator implements Iterator {
		    
		    Enumeration e;
		    
		    public EnumerationIterator(Enumeration e) {
			this.e = e;
		    }
		    
		    @Override
		    public void remove() {
			throw new UnsupportedOperationException();
		    }
		    
		    @Override
		    public Object next() {
			return e.nextElement();
		    }
		    
		    @Override
		    public boolean hasNext() {
			return e.hasMoreElements();
		    }
		}