Adapter Pattern
It helps to assign/convert one interface (called as source) to another distinct interface (called as target).
Example Description:
The below code helps us to use legacy Enumeration class available in Vector class in place of modern Iterator class.
It helps to assign/convert one interface (called as source) to another distinct interface (called as target).
Example Description:
The below code helps us to use legacy Enumeration class available in Vector class in place of modern Iterator class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | package designpattern; import java.util.Enumeration; import java.util.Iterator; import java.util.Vector; /** * * @author DELL */ public class AdapterPatternExample { public static void main(String[] args) { demo(); } public static void demo() { Vector namelist = new Vector(); namelist.add( "Athiruban" ); namelist.add( "Athinivas" ); Enumeration legacyIterator = namelist.elements(); Iterator iterator; LegacyIteratorAdapter adapter = new LegacyIteratorAdapter(legacyIterator); //iterator = legacyIterator; /* this code will fail */ iterator = adapter; for (; iterator.hasNext();) { System.out.println(iterator.next().toString()); } } } class LegacyIteratorAdapter implements Iterator { /* * The purpose of the class to adapt the legacy Enumeration interface to * modern Iterator interface . */ Enumeration legacyIterator; public LegacyIteratorAdapter(Enumeration e) { legacyIterator = e; } @Override public boolean hasNext() { return legacyIterator.hasMoreElements(); } @Override public Object next() { return legacyIterator.nextElement(); } @Override public void remove() { throw new UnsupportedOperationException( "Not supported yet." ); //To change body of generated methods, choose Tools | Templates. } } |
No comments:
Post a Comment