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.
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