Skip to content

Instantly share code, notes, and snippets.

@arttuladhar
Created July 16, 2018 00:31
Show Gist options
  • Save arttuladhar/606ffd1fc94b756581a6880436fd950a to your computer and use it in GitHub Desktop.
Save arttuladhar/606ffd1fc94b756581a6880436fd950a to your computer and use it in GitHub Desktop.
Adapter Design Pattern Example
package com.art.head_first.turkeyadapter;
public interface Duck {
public void quack();
public void fly();
}
package com.art.head_first.turkeyadapter;
import org.junit.Test;
public class DuckTestDrive {
@Test
public void testTurkeyAdapter(){
MallardDuck duck = new MallardDuck();
WildTurkey turkey = new WildTurkey();
System.out.println("**************************************************");
System.out.println("Turkey Says: ");
turkey.gobble();
turkey.fly();
System.out.println("**************************************************");
System.out.println("Duck Says");
performDuckActions(duck);
System.out.println("**************************************************");
System.out.println("Turkey Adapter Says: ");
Duck turkeyAdapter = new TurkeyAdapter(turkey);
performDuckActions(turkeyAdapter);
}
private void performDuckActions(Duck duck){
duck.quack();
duck.fly();
}
}
package com.art.head_first.turkeyadapter;
public class MallardDuck implements Duck{
@Override
public void quack() {
System.out.println("Quack");
}
@Override
public void fly() {
System.out.println("I'm Flying");
}
}
package com.art.head_first.turkeyadapter;
public interface Turkey {
public void gobble();
public void fly();
}
package com.art.head_first.turkeyadapter;
public class TurkeyAdapter implements Duck {
Turkey turkey;
public TurkeyAdapter(Turkey turkey) {
this.turkey = turkey;
}
@Override
public void quack() {
turkey.gobble();
}
@Override
public void fly() {
for (int i=0; i<5; i++){
turkey.fly();
}
}
}
package com.art.head_first.turkeyadapter;
public class WildTurkey implements Turkey{
@Override
public void gobble() {
System.out.println("Gobble Gobble");
}
@Override
public void fly() {
System.out.println("I'm flying short distance");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment