From 14c494ffdde5fdb39c1db3a03ba1ac75fc8cbc96 Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Fri, 21 Apr 2017 14:38:12 +0100 Subject: [PATCH] Condition: remove unnecessare object instantiation Only one each, true and false, Condition object needed. --- .../net/kemitix/conditional/Condition.java | 25 ++++++++++++++++--- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/src/main/java/net/kemitix/conditional/Condition.java b/src/main/java/net/kemitix/conditional/Condition.java index 4df41e0..7a5f313 100644 --- a/src/main/java/net/kemitix/conditional/Condition.java +++ b/src/main/java/net/kemitix/conditional/Condition.java @@ -21,6 +21,9 @@ package net.kemitix.conditional; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + /** * If-then-else in a functional-style. * @@ -37,9 +40,9 @@ public interface Condition { */ static Condition where(final boolean clause) { if (clause) { - return new TrueCondition(); + return TrueCondition.getInstance(); } - return new FalseCondition(); + return FalseCondition.getInstance(); } /** @@ -123,14 +126,21 @@ public interface Condition { /** * A {@code Condition} that has evaluated to {@code true}. */ + @NoArgsConstructor(access = AccessLevel.PRIVATE) class TrueCondition implements Condition { + private static final Condition INSTANCE = new TrueCondition(); + + private static Condition getInstance() { + return INSTANCE; + } + @Override public Condition and(final boolean clause) { if (clause) { return this; } - return new FalseCondition(); + return FalseCondition.getInstance(); } @Override @@ -153,8 +163,15 @@ public interface Condition { /** * A {@code Condition} that has evaluated to {@code false}. */ + @NoArgsConstructor(access = AccessLevel.PRIVATE) class FalseCondition implements Condition { + private static final Condition INSTANCE = new FalseCondition(); + + private static Condition getInstance() { + return INSTANCE; + } + @Override public Condition and(final boolean clause) { return this; @@ -163,7 +180,7 @@ public interface Condition { @Override public Condition or(final boolean secondClause) { if (secondClause) { - return new TrueCondition(); + return TrueCondition.getInstance(); } return this; }