Wednesday, May 6, 2015

Adapter Pattern example

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.

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) {

    public static void demo() {
        Vector namelist = new Vector();
        Enumeration legacyIterator = namelist.elements();
        Iterator iterator;

        LegacyIteratorAdapter adapter = new LegacyIteratorAdapter(legacyIterator);
        //iterator = legacyIterator;    /* this code will fail */
        iterator = adapter;
        for (; iterator.hasNext();) {

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;

    public boolean hasNext() {
        return legacyIterator.hasMoreElements();

    public Object next() {
        return legacyIterator.nextElement();

    public void remove() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.

No comments:

Post a Comment