From baff959dd3b3249dd0095073ffb216c1b0a9ebaa Mon Sep 17 00:00:00 2001 From: Hammy Date: Wed, 16 Dec 2020 00:07:53 +0000 Subject: [PATCH] Combine Singleton + Adapter --- .../src/adapter/animal/BirdAdapter.java | 14 ++++++++++++-- Design Patterns/src/adapter/animal/Main.java | 2 +- .../src/adapter/animal/tests/BirdAdapterTest.java | 2 +- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/Design Patterns/src/adapter/animal/BirdAdapter.java b/Design Patterns/src/adapter/animal/BirdAdapter.java index d22bdb9..aeb362c 100644 --- a/Design Patterns/src/adapter/animal/BirdAdapter.java +++ b/Design Patterns/src/adapter/animal/BirdAdapter.java @@ -2,12 +2,22 @@ package adapter.animal; 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; } + 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 public void squeak() { bird.makeSound(); diff --git a/Design Patterns/src/adapter/animal/Main.java b/Design Patterns/src/adapter/animal/Main.java index 2f9fa9e..ac87451 100644 --- a/Design Patterns/src/adapter/animal/Main.java +++ b/Design Patterns/src/adapter/animal/Main.java @@ -14,7 +14,7 @@ public class Main { plasticToyDuck.squeak(); System.out.println("\nBirdAdapter..."); - ToyDuck birdAdapter = new BirdAdapter(sparrow); + ToyDuck birdAdapter = BirdAdapter.getInstance(sparrow); birdAdapter.squeak(); } diff --git a/Design Patterns/src/adapter/animal/tests/BirdAdapterTest.java b/Design Patterns/src/adapter/animal/tests/BirdAdapterTest.java index 69849d8..352f004 100644 --- a/Design Patterns/src/adapter/animal/tests/BirdAdapterTest.java +++ b/Design Patterns/src/adapter/animal/tests/BirdAdapterTest.java @@ -13,7 +13,7 @@ class BirdAdapterTest { @Test void verifyMakeSoundIsCalled() { Bird mockedSparrow = mock(Sparrow.class); - ToyDuck birdAdapter = new BirdAdapter(mockedSparrow); + ToyDuck birdAdapter = BirdAdapter.getInstance(mockedSparrow); birdAdapter.squeak(); verify(mockedSparrow, times(1)).makeSound();