Adapter Pattern: converts the interface of a class into another interface the client expect.
Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
Example
TV.java
package com.adapterpattern.example; public interface TV { public void watch(); }
LEDTV.java
package com.adapterpattern.example; public class LEDTV implements TV{ @Override public void watch() { System.out.println("Now are watching LED TV"); } }
Phone.java
package com.adapterpattern.example; public interface Phone { public void call(); }
SmartPhone.java
package com.adapterpattern.example; public class SmartPhone implements Phone{ @Override public void call() { System.out.println("You are making calls using SmartPhone"); } }
SmartPhoneTVAdapter.java
package com.adapterpattern.example; public class SmartPhoneTVAdapter implements Phone{ TV tv; public SmartPhoneTVAdapter(TV tv) { this.tv = tv; } @Override public void call() { tv.watch(); } }
SmartPhoneTVTestDrive.java
package com.adapterpattern.example; public class SmartPhoneTVTestDrive { public static void main(String[] args) { Phone phone = new SmartPhone(); phone.call(); TV tv = new LEDTV(); /* * TV and Phone are two incompatible interfaces, After implementing * SmartPhoneTVAdapter we are able watch TV in SmartPhone */ Phone smartPhoneTV = new SmartPhoneTVAdapter(tv); smartPhoneTV.call(); } }Home
No comments:
Post a Comment