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
1 2 3 4 5 | package com.adapterpattern.example; public interface TV { public void watch(); } |
LEDTV.java
1 2 3 4 5 6 7 8 9 10 11 | package com.adapterpattern.example; public class LEDTV implements TV{ @Override public void watch() { System.out.println( "Now are watching LED TV" ); } } |
Phone.java
1 2 3 4 5 6 | package com.adapterpattern.example; public interface Phone { public void call(); } |
SmartPhone.java
1 2 3 4 5 6 7 8 9 | package com.adapterpattern.example; public class SmartPhone implements Phone{ @Override public void call() { System.out.println( "You are making calls using SmartPhone" ); } } |
SmartPhoneTVAdapter.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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