Java Adapter Pattern Exercise

1. The old interface

package adapter;

public interface OldInterface {
      /**
       * old plan
       */
       public void oldPlan();
}

2. The old interface implementation class

package adapter;

public class OldImp implements OldInterface{

     @Override
     public void oldPlan() {
          System.err.println("This is an old plan!");
     }

}

3. New interface

package adapter;

public interface NewInterface {
       /**
       * new plan
       */
       public void newPlan();
}

4. New interface implementation class

package adapter;

public class NewImp implements NewInterface {

   @Override
   public void newPlan() {
         System.err.println("This is a new plan!");
   }

}

5. Adapter

package adapter;

public class Adapter implements OldInterface {

    private NewInterface newImp;
    
    public Adapter (NewInterface newImp){
          this.newImp = newImp;
    }
    
   @Override
   public void oldPlan() {
         newImp.newPlan();
   }

}

6. Test

package adapter;

public class demo {

     public static void main(String[] args) {
            NewInterface newi = new NewImp();
            Adapter exists = new Adapter(newi);
            exist.oldPlan();
     }
     
}

7. As a result, the old method is called to implement the new plan


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325886683&siteId=291194637