Skip to content

Instantly share code, notes, and snippets.

@adammb86
Created November 10, 2018 03:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adammb86/17df21d73e274a740b516eb1f406f7f8 to your computer and use it in GitHub Desktop.
Save adammb86/17df21d73e274a740b516eb1f406f7f8 to your computer and use it in GitHub Desktop.
Design Pattern - Adapter - Sample Case
(Adapter) Langkah Pembuatan :
1. Interface Bird.java dan ToyDuck.java
2. Class Sparrow.java dan PlasticToyDuck.java
3. BirdAdapter.java
4. AdapterClient.java
public class AdapterClient {
public static void main(String[] args) {
Sparrow sparrow = new Sparrow();
PlasticToyDuck toyDuck = new PlasticToyDuck();
// Bungkus bird dengan birdAdapter sehingga bertingkah laku seperti toy duck
ToyDuck birdAdapter = new BirdAdapter(sparrow);
System.out.println("Sparrow...");
sparrow.fly();
sparrow.makeSound();
System.out.println("ToyDuck...");
toyDuck.squeak();
// bird bertingkah laku seperti toy duck
System.out.println("BirdAdapter...");
birdAdapter.squeak();
}
}
public interface Bird {
public void fly();
public void makeSound();
}
public class BirdAdapter implements ToyDuck {
Bird bird;
public BirdAdapter(Bird bird) {
this.bird = bird;
}
@Override
public void squeak() {
bird.makeSound();
}
}
public class PlasticToyDuck implements ToyDuck{
@Override
public void squeak() {
System.out.printf("Squeak");
}
}
public class Sparrow implements Bird {
@Override
public void fly() {
System.out.printf("Flying");
}
@Override
public void makeSound() {
System.out.printf("Chirp chirp");
}
}
public interface ToyDuck {
public void squeak();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment