Combine Singleton + Adapter

master
Hammy 4 years ago
parent e1f7667f0a
commit baff959dd3

@ -2,12 +2,22 @@ package adapter.animal;
public class BirdAdapter implements ToyDuck { public class BirdAdapter implements ToyDuck {
private final Bird bird; private Bird bird;
private static BirdAdapter instance;
public BirdAdapter(Bird bird) { private BirdAdapter(Bird bird) {
this.bird = bird; this.bird = bird;
} }
public static BirdAdapter getInstance(Bird bird) {
if (instance == null) {
instance = new BirdAdapter(bird);
} else if (!instance.bird.equals(bird)) {
instance.bird = bird;
}
return instance;
}
@Override @Override
public void squeak() { public void squeak() {
bird.makeSound(); bird.makeSound();

@ -14,7 +14,7 @@ public class Main {
plasticToyDuck.squeak(); plasticToyDuck.squeak();
System.out.println("\nBirdAdapter..."); System.out.println("\nBirdAdapter...");
ToyDuck birdAdapter = new BirdAdapter(sparrow); ToyDuck birdAdapter = BirdAdapter.getInstance(sparrow);
birdAdapter.squeak(); birdAdapter.squeak();
} }

@ -13,7 +13,7 @@ class BirdAdapterTest {
@Test @Test
void verifyMakeSoundIsCalled() { void verifyMakeSoundIsCalled() {
Bird mockedSparrow = mock(Sparrow.class); Bird mockedSparrow = mock(Sparrow.class);
ToyDuck birdAdapter = new BirdAdapter(mockedSparrow); ToyDuck birdAdapter = BirdAdapter.getInstance(mockedSparrow);
birdAdapter.squeak(); birdAdapter.squeak();
verify(mockedSparrow, times(1)).makeSound(); verify(mockedSparrow, times(1)).makeSound();

Loading…
Cancel
Save