- * Marker interface vs annotation
- * Marker interfaces and marker annotations both have their uses,
- * neither of them is obsolete or always better then the other one.
- * If you want to define a type that does not have any new methods associated with it,
- * a marker interface is the way to go.
- * If you want to mark program elements other than classes and interfaces,
- * to allow for the possibility of adding more information to the marker in the future,
- * or to fit the marker into a framework that already makes heavy use of annotation types,
- * then a marker annotation is the correct choice
+ * Created by Alexis on 28-Apr-17. With Marker interface idea is to make empty interface and extend
+ * it. Basically it is just to identify the special objects from normal objects. Like in case of
+ * serialization , objects that need to be serialized must implement serializable interface (it is
+ * empty interface) and down the line writeObject() method must be checking if it is a instance of
+ * serializable or not.
+ *
+ *
Marker interface vs annotation Marker interfaces and marker annotations both have their uses,
+ * neither of them is obsolete or always better then the other one. If you want to define a type
+ * that does not have any new methods associated with it, a marker interface is the way to go. If
+ * you want to mark program elements other than classes and interfaces, to allow for the possibility
+ * of adding more information to the marker in the future, or to fit the marker into a framework
+ * that already makes heavy use of annotation types, then a marker annotation is the correct choice
*/
public class App {
/**
- * Program entry point
+ * Program entry point.
*
* @param args command line args
*/
diff --git a/marker/src/main/java/Guard.java b/marker/src/main/java/Guard.java
index d135d54598f4..9a57e15fdfb3 100644
--- a/marker/src/main/java/Guard.java
+++ b/marker/src/main/java/Guard.java
@@ -25,7 +25,7 @@
import org.slf4j.LoggerFactory;
/**
- * Class defining Guard
+ * Class defining Guard.
*/
public class Guard implements Permission {
diff --git a/marker/src/main/java/Permission.java b/marker/src/main/java/Permission.java
index e1b45e99f7f4..5395ccadf9a1 100644
--- a/marker/src/main/java/Permission.java
+++ b/marker/src/main/java/Permission.java
@@ -22,8 +22,7 @@
*/
/**
- * Interface without any methods
- * Marker interface is based on that assumption
+ * Interface without any methods Marker interface is based on that assumption.
*/
public interface Permission {
}
diff --git a/marker/src/main/java/Thief.java b/marker/src/main/java/Thief.java
index 155a974c19d3..341eae3777d9 100644
--- a/marker/src/main/java/Thief.java
+++ b/marker/src/main/java/Thief.java
@@ -25,7 +25,7 @@
import org.slf4j.LoggerFactory;
/**
- * Class defining Thief
+ * Class defining Thief.
*/
public class Thief {
diff --git a/master-worker-pattern/README.md b/master-worker-pattern/README.md
index 4d2aa0e38d95..f8b5509369ff 100644
--- a/master-worker-pattern/README.md
+++ b/master-worker-pattern/README.md
@@ -3,7 +3,7 @@ layout: pattern
title: Master-Worker
folder: master-worker-pattern
permalink: /patterns/master-worker-pattern/
-categories: Centralised Parallel Processing
+categories: Other
tags:
- Java
- Difficulty-Intermediate
diff --git a/master-worker-pattern/pom.xml b/master-worker-pattern/pom.xml
index 8ce79ed7f7c5..7ace130d8a9e 100644
--- a/master-worker-pattern/pom.xml
+++ b/master-worker-pattern/pom.xml
@@ -27,7 +27,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTmaster-worker-pattern
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/App.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/App.java
index e3ffd08c4d44..b8036b91199a 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/App.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/App.java
@@ -28,30 +28,37 @@
import org.slf4j.LoggerFactory;
/**
- *
The Master-Worker pattern is used when the problem at hand can be solved by dividing into
- * multiple parts which need to go through the same computation and may need to be aggregated to get final result.
- * Parallel processing is performed using a system consisting of a master and some number of workers, where a
- * master divides the work among the workers, gets the result back from them and assimilates all the results to
- * give final result. The only communication is between the master and the worker - none of the workers communicate
- * among one another and the user only communicates with the master to get required job done.
- *
In our example, we have generic abstract classes {@link MasterWorker}, {@link Master} and {@link Worker} which
- * have to be extended by the classes which will perform the specific job at hand (in this case finding transpose of
- * matrix, done by {@link ArrayTransposeMasterWorker}, {@link ArrayTransposeMaster} and {@link ArrayTransposeWorker}).
- * The Master class divides the work into parts to be given to the workers, collects the results from the workers and
- * aggregates it when all workers have responded before returning the solution. The Worker class extends the Thread
- * class to enable parallel processing, and does the work once the data has been received from the Master. The
- * MasterWorker contains a reference to the Master class, gets the input from the App and passes it on to the Master.
- * These 3 classes define the system which computes the result. We also have 2 abstract classes {@link Input} and
- * {@link Result}, which contain the input data and result data respectively. The Input class also has an abstract
- * method divideData which defines how the data is to be divided into segments. These classes are extended by
- * {@link ArrayInput} and {@link ArrayResult}.
+ *
The Master-Worker pattern is used when the problem at hand can be solved by
+ * dividing into
+ * multiple parts which need to go through the same computation and may need to be aggregated to get
+ * final result. Parallel processing is performed using a system consisting of a master and some
+ * number of workers, where a master divides the work among the workers, gets the result back from
+ * them and assimilates all the results to give final result. The only communication is between the
+ * master and the worker - none of the workers communicate among one another and the user only
+ * communicates with the master to get required job done.
+ *
In our example, we have generic abstract classes {@link MasterWorker}, {@link Master} and
+ * {@link Worker} which
+ * have to be extended by the classes which will perform the specific job at hand (in this case
+ * finding transpose of matrix, done by {@link ArrayTransposeMasterWorker}, {@link
+ * ArrayTransposeMaster} and {@link ArrayTransposeWorker}). The Master class divides the work into
+ * parts to be given to the workers, collects the results from the workers and aggregates it when
+ * all workers have responded before returning the solution. The Worker class extends the Thread
+ * class to enable parallel processing, and does the work once the data has been received from the
+ * Master. The MasterWorker contains a reference to the Master class, gets the input from the App
+ * and passes it on to the Master. These 3 classes define the system which computes the result. We
+ * also have 2 abstract classes {@link Input} and {@link Result}, which contain the input data and
+ * result data respectively. The Input class also has an abstract method divideData which defines
+ * how the data is to be divided into segments. These classes are extended by {@link ArrayInput} and
+ * {@link ArrayResult}.
*/
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
+
/**
* Program entry point.
+ *
* @param args command line args
*/
@@ -59,9 +66,9 @@ public static void main(String[] args) {
ArrayTransposeMasterWorker mw = new ArrayTransposeMasterWorker();
int rows = 10;
int columns = 20;
- int[][] inputMatrix = ArrayUtilityMethods.createRandomIntMatrix(rows,columns);
+ int[][] inputMatrix = ArrayUtilityMethods.createRandomIntMatrix(rows, columns);
ArrayInput input = new ArrayInput(inputMatrix);
- ArrayResult result = (ArrayResult) mw.getResult(input);
+ ArrayResult result = (ArrayResult) mw.getResult(input);
if (result != null) {
ArrayUtilityMethods.printMatrix(inputMatrix);
ArrayUtilityMethods.printMatrix(result.data);
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayInput.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayInput.java
index df2d691b26eb..cd03a0a21895 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayInput.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayInput.java
@@ -27,8 +27,7 @@
import java.util.Arrays;
/**
- *Class ArrayInput extends abstract class {@link Input} and contains data
- *of type int[][].
+ * Class ArrayInput extends abstract class {@link Input} and contains data of type int[][].
*/
public class ArrayInput extends Input {
@@ -36,7 +35,7 @@ public class ArrayInput extends Input {
public ArrayInput(int[][] data) {
super(data);
}
-
+
static int[] makeDivisions(int[][] data, int num) {
int initialDivision = data.length / num; //equally dividing
int[] divisions = new int[num];
@@ -81,6 +80,6 @@ public ArrayList divideData(int num) {
}
}
return result;
- }
- }
+ }
+ }
}
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayResult.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayResult.java
index dbe4f7477c12..a26472e80445 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayResult.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayResult.java
@@ -24,8 +24,7 @@
package com.iluwatar.masterworker;
/**
- *Class ArrayResult extends abstract class {@link Result} and contains data
- *of type int[][].
+ * Class ArrayResult extends abstract class {@link Result} and contains data of type int[][].
*/
public class ArrayResult extends Result {
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java
index 04db66492a13..525bed003e70 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java
@@ -23,23 +23,23 @@
package com.iluwatar.masterworker;
+import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Random;
-
/**
- *Class ArrayUtilityMethods has some utility methods for matrices and arrays.
+ * Class ArrayUtilityMethods has some utility methods for matrices and arrays.
*/
public class ArrayUtilityMethods {
private static final Logger LOGGER = LoggerFactory.getLogger(ArrayUtilityMethods.class);
-
+
private static final Random RANDOM = new Random();
+
/**
- * Method arraysSame compares 2 arrays @param a1 and @param a2
- * and @return whether their values are equal (boolean).
+ * Method arraysSame compares 2 arrays @param a1 and @param a2 and @return whether their values
+ * are equal (boolean).
*/
public static boolean arraysSame(int[] a1, int[] a2) {
@@ -61,10 +61,10 @@ public static boolean arraysSame(int[] a1, int[] a2) {
}
/**
- * Method matricesSame compares 2 matrices @param m1 and @param m2
- * and @return whether their values are equal (boolean).
+ * Method matricesSame compares 2 matrices @param m1 and @param m2 and @return whether their
+ * values are equal (boolean).
*/
-
+
public static boolean matricesSame(int[][] m1, int[][] m2) {
if (m1.length != m2.length) {
return false;
@@ -81,12 +81,12 @@ public static boolean matricesSame(int[][] m1, int[][] m2) {
return answer;
}
}
-
+
/**
- * Method createRandomIntMatrix creates a random matrix of size @param rows
- * and @param columns @return it (int[][]).
+ * Method createRandomIntMatrix creates a random matrix of size @param rows and @param columns.
+ *
+ * @return it (int[][]).
*/
-
public static int[][] createRandomIntMatrix(int rows, int columns) {
int[][] matrix = new int[rows][columns];
for (int i = 0; i < rows; i++) {
@@ -97,11 +97,11 @@ public static int[][] createRandomIntMatrix(int rows, int columns) {
}
return matrix;
}
-
+
/**
* Method printMatrix prints input matrix @param matrix.
*/
-
+
public static void printMatrix(int[][] matrix) {
//prints out int[][]
for (int i = 0; i < matrix.length; i++) {
@@ -111,5 +111,5 @@ public static void printMatrix(int[][] matrix) {
LOGGER.info("");
}
}
-
+
}
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Input.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Input.java
index d0d0c2ddeac4..6a957ae804c3 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Input.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Input.java
@@ -26,18 +26,19 @@
import java.util.ArrayList;
/**
- *The abstract Input class, having 1 public field which contains input data,
- *and abstract method divideData.
+ * The abstract Input class, having 1 public field which contains input data, and abstract method
+ * divideData.
+ *
* @param T will be type of data.
*/
public abstract class Input {
-
+
public final T data;
-
+
public Input(T data) {
this.data = data;
}
-
+
public abstract ArrayList divideData(int num);
}
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Result.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Result.java
index 1bc729aa9228..79bc14604012 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Result.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Result.java
@@ -24,13 +24,13 @@
package com.iluwatar.masterworker;
/**
- *The abstract Result class, which contains 1 public field containing result
- *data.
+ * The abstract Result class, which contains 1 public field containing result data.
+ *
* @param T will be type of data.
*/
public abstract class Result {
-
+
public final T data;
public Result(T data) {
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java
index 76e9ff35ab08..86c1a5700d95 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java
@@ -27,8 +27,8 @@
import com.iluwatar.masterworker.system.systemmaster.Master;
/**
- *Class ArrayTransposeMasterWorker extends abstract class {@link MasterWorker} and
- *specifically solves the problem of finding transpose of input array.
+ * Class ArrayTransposeMasterWorker extends abstract class {@link MasterWorker} and specifically
+ * solves the problem of finding transpose of input array.
*/
public class ArrayTransposeMasterWorker extends MasterWorker {
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java
index 009faf106536..2b16cbf7628f 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java
@@ -28,7 +28,7 @@
import com.iluwatar.masterworker.system.systemmaster.Master;
/**
- *The abstract MasterWorker class which contains reference to master.
+ * The abstract MasterWorker class which contains reference to master.
*/
public abstract class MasterWorker {
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java
index 0a3ab79b7cc1..ffa64572ce64 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java
@@ -23,16 +23,15 @@
package com.iluwatar.masterworker.system.systemmaster;
-import java.util.ArrayList;
-import java.util.Enumeration;
import com.iluwatar.masterworker.ArrayResult;
import com.iluwatar.masterworker.system.systemworkers.ArrayTransposeWorker;
import com.iluwatar.masterworker.system.systemworkers.Worker;
+import java.util.ArrayList;
+import java.util.Enumeration;
/**
- *Class ArrayTransposeMaster extends abstract class {@link Master} and contains
- *definition of aggregateData, which will obtain final result from all
- *data obtained and for setWorkers.
+ * Class ArrayTransposeMaster extends abstract class {@link Master} and contains definition of
+ * aggregateData, which will obtain final result from all data obtained and for setWorkers.
*/
public class ArrayTransposeMaster extends Master {
@@ -43,26 +42,29 @@ public ArrayTransposeMaster(int numOfWorkers) {
@Override
ArrayList setWorkers(int num) {
ArrayList ws = new ArrayList(num);
- for (int i = 0; i < num ; i++) {
+ for (int i = 0; i < num; i++) {
ws.add(new ArrayTransposeWorker(this, i + 1));
//i+1 will be id
}
return ws;
}
-
+
@Override
ArrayResult aggregateData() {
- //number of rows in final result is number of rows in any of obtained results obtained from workers
- int rows = ((ArrayResult) this.getAllResultData().get(this.getAllResultData().keys().nextElement())).data.length;
- int columns = 0; //number of columns is sum of number of columns in all results obtained from workers
- for (Enumeration e = this.getAllResultData().keys(); e.hasMoreElements();) {
+ // number of rows in final result is number of rows in any of obtained results from workers
+ int rows = ((ArrayResult) this.getAllResultData()
+ .get(this.getAllResultData().keys().nextElement())).data.length;
+ int columns =
+ 0; //number of columns is sum of number of columns in all results obtained from workers
+ for (Enumeration e = this.getAllResultData().keys(); e.hasMoreElements(); ) {
columns += ((ArrayResult) this.getAllResultData().get(e.nextElement())).data[0].length;
}
int[][] resultData = new int[rows][columns];
int columnsDone = 0; //columns aggregated so far
for (int i = 0; i < this.getExpectedNumResults(); i++) {
//result obtained from ith worker
- int[][] work = ((ArrayResult) this.getAllResultData().get(this.getWorkers().get(i).getWorkerId())).data;
+ int[][] work =
+ ((ArrayResult) this.getAllResultData().get(this.getWorkers().get(i).getWorkerId())).data;
for (int m = 0; m < work.length; m++) {
//m = row number, n = columns number
for (int n = 0; n < work[0].length; n++) {
@@ -73,5 +75,5 @@ ArrayResult aggregateData() {
}
return new ArrayResult(resultData);
}
-
+
}
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java
index 7e7d796eb718..2466df256f0c 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java
@@ -23,18 +23,17 @@
package com.iluwatar.masterworker.system.systemmaster;
-import java.util.ArrayList;
-import java.util.Hashtable;
import com.iluwatar.masterworker.Input;
import com.iluwatar.masterworker.Result;
import com.iluwatar.masterworker.system.systemworkers.Worker;
+import java.util.ArrayList;
+import java.util.Hashtable;
/**
- *The abstract Master class which contains private fields numOfWorkers
- *(number of workers), workers (arraylist of workers), expectedNumResults
- *(number of divisions of input data, same as expected number of results),
- *allResultData (hashtable of results obtained from workers, mapped by
- *their ids) and finalResult (aggregated from allResultData).
+ * The abstract Master class which contains private fields numOfWorkers (number of workers), workers
+ * (arraylist of workers), expectedNumResults (number of divisions of input data, same as expected
+ * number of results), allResultData (hashtable of results obtained from workers, mapped by their
+ * ids) and finalResult (aggregated from allResultData).
*/
public abstract class Master {
@@ -43,7 +42,7 @@ public abstract class Master {
private int expectedNumResults;
private Hashtable allResultData;
private Result finalResult;
-
+
Master(int numOfWorkers) {
this.numOfWorkers = numOfWorkers;
this.workers = setWorkers(numOfWorkers);
@@ -51,46 +50,46 @@ public abstract class Master {
this.allResultData = new Hashtable(numOfWorkers);
this.finalResult = null;
}
-
+
public Result getFinalResult() {
return this.finalResult;
}
-
+
Hashtable getAllResultData() {
return this.allResultData;
}
-
+
int getExpectedNumResults() {
return this.expectedNumResults;
}
-
+
ArrayList getWorkers() {
return this.workers;
}
-
+
abstract ArrayList setWorkers(int num);
-
+
public void doWork(Input input) {
divideWork(input);
}
-
+
private void divideWork(Input input) {
ArrayList dividedInput = input.divideData(numOfWorkers);
if (dividedInput != null) {
this.expectedNumResults = dividedInput.size();
- for (int i = 0; i < this.expectedNumResults; i++) {
+ for (int i = 0; i < this.expectedNumResults; i++) {
//ith division given to ith worker in this.workers
this.workers.get(i).setReceivedData(this, dividedInput.get(i));
this.workers.get(i).run();
}
}
}
-
+
public void receiveData(Result data, Worker w) {
//check if can receive..if yes:
collectResult(data, w.getWorkerId());
}
-
+
private void collectResult(Result data, int workerId) {
this.allResultData.put(workerId, data);
if (this.allResultData.size() == this.expectedNumResults) {
@@ -98,6 +97,6 @@ private void collectResult(Result data, int workerId) {
this.finalResult = aggregateData();
}
}
-
+
abstract Result aggregateData();
}
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java
index 1d06fcc875da..37d8ba005699 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java
@@ -28,8 +28,8 @@
import com.iluwatar.masterworker.system.systemmaster.Master;
/**
- *Class ArrayTransposeWorker extends abstract class {@link Worker} and defines method
- *executeOperation(), to be performed on data received from master.
+ * Class ArrayTransposeWorker extends abstract class {@link Worker} and defines method
+ * executeOperation(), to be performed on data received from master.
*/
public class ArrayTransposeWorker extends Worker {
@@ -41,12 +41,14 @@ public ArrayTransposeWorker(Master master, int id) {
@Override
ArrayResult executeOperation() {
//number of rows in result matrix is equal to number of columns in input matrix and vice versa
- int[][] resultData = new int[((ArrayInput) this.getReceivedData()).data[0].length]
- [((ArrayInput) this.getReceivedData()).data.length];
- for (int i = 0; i < ((ArrayInput) this.getReceivedData()).data.length; i++) {
- for (int j = 0; j < ((ArrayInput) this.getReceivedData()).data[0].length; j++) {
+ ArrayInput arrayInput = (ArrayInput) this.getReceivedData();
+ final int rows = arrayInput.data[0].length;
+ final int cols = arrayInput.data.length;
+ int[][] resultData = new int[rows][cols];
+ for (int i = 0; i < cols; i++) {
+ for (int j = 0; j < rows; j++) {
//flipping element positions along diagonal
- resultData[j][i] = ((ArrayInput) this.getReceivedData()).data[i][j];
+ resultData[j][i] = arrayInput.data[i][j];
}
}
return new ArrayResult(resultData);
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java
index fff38e953216..bfe226ee0211 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java
@@ -28,9 +28,8 @@
import com.iluwatar.masterworker.system.systemmaster.Master;
/**
- *The abstract Worker class which extends Thread class to enable parallel
- *processing. Contains fields master(holding reference to master), workerId
- *(unique id) and receivedData(from master).
+ * The abstract Worker class which extends Thread class to enable parallel processing. Contains
+ * fields master(holding reference to master), workerId (unique id) and receivedData(from master).
*/
public abstract class Worker extends Thread {
@@ -61,7 +60,7 @@ public void setReceivedData(Master m, Input i) {
private void sendToMaster(Result data) {
this.master.receiveData(data, this);
- }
+ }
public void run() { //from Thread class
Result work = executeOperation();
diff --git a/mediator/pom.xml b/mediator/pom.xml
index 7fba84dd11ab..2c0bfd4135b6 100644
--- a/mediator/pom.xml
+++ b/mediator/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTmediator
diff --git a/mediator/src/main/java/com/iluwatar/mediator/Action.java b/mediator/src/main/java/com/iluwatar/mediator/Action.java
index dc89bcfdcd88..66e1f42c4672 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/Action.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/Action.java
@@ -24,15 +24,15 @@
package com.iluwatar.mediator;
/**
- *
* Action enumeration.
- *
*/
public enum Action {
- HUNT("hunted a rabbit", "arrives for dinner"), TALE("tells a tale", "comes to listen"), GOLD(
- "found gold", "takes his share of the gold"), ENEMY("spotted enemies", "runs for cover"), NONE(
- "", "");
+ HUNT("hunted a rabbit", "arrives for dinner"),
+ TALE("tells a tale", "comes to listen"),
+ GOLD("found gold", "takes his share of the gold"),
+ ENEMY("spotted enemies", "runs for cover"),
+ NONE("", "");
private String title;
private String description;
diff --git a/mediator/src/main/java/com/iluwatar/mediator/App.java b/mediator/src/main/java/com/iluwatar/mediator/App.java
index 9af600f7cc5e..9dbedb4abf69 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/App.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/App.java
@@ -24,32 +24,31 @@
package com.iluwatar.mediator;
/**
- *
* The Mediator pattern defines an object that encapsulates how a set of objects interact. This
* pattern is considered to be a behavioral pattern due to the way it can alter the program's
* running behavior.
- *
- * Usually a program is made up of a large number of classes. So the logic and computation is
+ *
+ *
Usually a program is made up of a large number of classes. So the logic and computation is
* distributed among these classes. However, as more classes are developed in a program, especially
* during maintenance and/or refactoring, the problem of communication between these classes may
* become more complex. This makes the program harder to read and maintain. Furthermore, it can
* become difficult to change the program, since any change may affect code in several other
* classes.
- *
- * With the Mediator pattern, communication between objects is encapsulated with a mediator object.
- * Objects no longer communicate directly with each other, but instead communicate through the
- * mediator. This reduces the dependencies between communicating objects, thereby lowering the
+ *
+ *
With the Mediator pattern, communication between objects is encapsulated with a mediator
+ * object. Objects no longer communicate directly with each other, but instead communicate through
+ * the mediator. This reduces the dependencies between communicating objects, thereby lowering the
* coupling.
- *
- * In this example the mediator encapsulates how a set of objects ({@link PartyMember}) interact.
- * Instead of referring to each other directly they use the mediator ({@link Party}) interface.
- *
+ *
+ *
In this example the mediator encapsulates how a set of objects ({@link PartyMember})
+ * interact. Instead of referring to each other directly they use the mediator ({@link Party})
+ * interface.
*/
public class App {
/**
- * Program entry point
- *
+ * Program entry point.
+ *
* @param args command line args
*/
public static void main(String[] args) {
diff --git a/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java b/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java
index 1ddec27ab3a9..1e1d53fc30dc 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java
@@ -24,9 +24,7 @@
package com.iluwatar.mediator;
/**
- *
* Hobbit party member.
- *
*/
public class Hobbit extends PartyMemberBase {
diff --git a/mediator/src/main/java/com/iluwatar/mediator/Hunter.java b/mediator/src/main/java/com/iluwatar/mediator/Hunter.java
index ed73c1684ccb..0711acf70fff 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/Hunter.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/Hunter.java
@@ -24,9 +24,7 @@
package com.iluwatar.mediator;
/**
- *
* Hunter party member.
- *
*/
public class Hunter extends PartyMemberBase {
diff --git a/mediator/src/main/java/com/iluwatar/mediator/Party.java b/mediator/src/main/java/com/iluwatar/mediator/Party.java
index c28b063f35b8..52d91e21d135 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/Party.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/Party.java
@@ -24,9 +24,7 @@
package com.iluwatar.mediator;
/**
- *
* Party interface.
- *
*/
public interface Party {
diff --git a/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java b/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java
index a2a755408620..6384a21872cf 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java
@@ -27,9 +27,7 @@
import java.util.List;
/**
- *
* Party implementation.
- *
*/
public class PartyImpl implements Party {
diff --git a/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java b/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java
index a45b37b17cd3..c233a051af42 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java
@@ -24,9 +24,7 @@
package com.iluwatar.mediator;
/**
- *
* Interface for party members interacting with {@link Party}.
- *
*/
public interface PartyMember {
diff --git a/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java b/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java
index 7ff3535e85d4..2d025db0c4ef 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java
@@ -27,9 +27,7 @@
import org.slf4j.LoggerFactory;
/**
- *
* Abstract base class for party members.
- *
*/
public abstract class PartyMemberBase implements PartyMember {
diff --git a/mediator/src/main/java/com/iluwatar/mediator/Rogue.java b/mediator/src/main/java/com/iluwatar/mediator/Rogue.java
index 226bd8f04c4f..568510236d4c 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/Rogue.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/Rogue.java
@@ -24,9 +24,7 @@
package com.iluwatar.mediator;
/**
- *
* Rogue party member.
- *
*/
public class Rogue extends PartyMemberBase {
diff --git a/mediator/src/main/java/com/iluwatar/mediator/Wizard.java b/mediator/src/main/java/com/iluwatar/mediator/Wizard.java
index 33d7d6dce511..c138f0265115 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/Wizard.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/Wizard.java
@@ -24,9 +24,7 @@
package com.iluwatar.mediator;
/**
- *
* Wizard party member.
- *
*/
public class Wizard extends PartyMemberBase {
diff --git a/memento/pom.xml b/memento/pom.xml
index 260cb4c58016..07e4f0b839e5 100644
--- a/memento/pom.xml
+++ b/memento/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTmemento
diff --git a/memento/src/main/java/com/iluwatar/memento/App.java b/memento/src/main/java/com/iluwatar/memento/App.java
index fc6dffb06cb6..af57d8d4a2b7 100644
--- a/memento/src/main/java/com/iluwatar/memento/App.java
+++ b/memento/src/main/java/com/iluwatar/memento/App.java
@@ -23,36 +23,33 @@
package com.iluwatar.memento;
+import java.util.Stack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Stack;
-
/**
- *
* The Memento pattern is a software design pattern that provides the ability to restore an object
* to its previous state (undo via rollback).
- *
- * The Memento pattern is implemented with three objects: the originator, a caretaker and a memento.
- * The originator is some object that has an internal state. The caretaker is going to do something
- * to the originator, but wants to be able to undo the change. The caretaker first asks the
- * originator for a memento object. Then it does whatever operation (or sequence of operations) it
- * was going to do. To roll back to the state before the operations, it returns the memento object
- * to the originator. The memento object itself is an opaque object (one which the caretaker cannot,
- * or should not, change). When using this pattern, care should be taken if the originator may
- * change other objects or resources - the memento pattern operates on a single object.
- *
- * In this example the object ({@link Star}) gives out a "memento" ({@link StarMemento}) that
+ *
+ *
The Memento pattern is implemented with three objects: the originator, a caretaker and a
+ * memento. The originator is some object that has an internal state. The caretaker is going to do
+ * something to the originator, but wants to be able to undo the change. The caretaker first asks
+ * the originator for a memento object. Then it does whatever operation (or sequence of operations)
+ * it was going to do. To roll back to the state before the operations, it returns the memento
+ * object to the originator. The memento object itself is an opaque object (one which the caretaker
+ * cannot, or should not, change). When using this pattern, care should be taken if the originator
+ * may change other objects or resources - the memento pattern operates on a single object.
+ *
+ *
In this example the object ({@link Star}) gives out a "memento" ({@link StarMemento}) that
* contains the state of the object. Later on the memento can be set back to the object restoring
* the state.
- *
*/
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/**
- * Program entry point
+ * Program entry point.
*/
public static void main(String[] args) {
Stack states = new Stack<>();
diff --git a/memento/src/main/java/com/iluwatar/memento/Star.java b/memento/src/main/java/com/iluwatar/memento/Star.java
index 0e235752ec4e..ebeea28f291b 100644
--- a/memento/src/main/java/com/iluwatar/memento/Star.java
+++ b/memento/src/main/java/com/iluwatar/memento/Star.java
@@ -24,9 +24,7 @@
package com.iluwatar.memento;
/**
- *
* Star uses "mementos" to store and restore state.
- *
*/
public class Star {
@@ -35,7 +33,7 @@ public class Star {
private int massTons;
/**
- * Constructor
+ * Constructor.
*/
public Star(StarType startType, int startAge, int startMass) {
this.type = startType;
@@ -44,7 +42,7 @@ public Star(StarType startType, int startAge, int startMass) {
}
/**
- * Makes time pass for the star
+ * Makes time pass for the star.
*/
public void timePasses() {
ageYears *= 2;
@@ -96,9 +94,7 @@ public String toString() {
}
/**
- *
- * StarMemento implementation
- *
+ * StarMemento implementation.
*/
private static class StarMementoInternal implements StarMemento {
diff --git a/memento/src/main/java/com/iluwatar/memento/StarMemento.java b/memento/src/main/java/com/iluwatar/memento/StarMemento.java
index b94f5996a9db..7b7ccd3ec304 100644
--- a/memento/src/main/java/com/iluwatar/memento/StarMemento.java
+++ b/memento/src/main/java/com/iluwatar/memento/StarMemento.java
@@ -24,9 +24,7 @@
package com.iluwatar.memento;
/**
- *
* External interface to memento.
- *
*/
public interface StarMemento {
diff --git a/memento/src/main/java/com/iluwatar/memento/StarType.java b/memento/src/main/java/com/iluwatar/memento/StarType.java
index 29da625799ce..507cd506b60a 100644
--- a/memento/src/main/java/com/iluwatar/memento/StarType.java
+++ b/memento/src/main/java/com/iluwatar/memento/StarType.java
@@ -24,9 +24,7 @@
package com.iluwatar.memento;
/**
- *
- * StarType enumeration
- *
+ * StarType enumeration.
*/
public enum StarType {
diff --git a/model-view-controller/pom.xml b/model-view-controller/pom.xml
index 035a6a27bb95..4759bf2d3158 100644
--- a/model-view-controller/pom.xml
+++ b/model-view-controller/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTmodel-view-controller
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java
index b4bc8f6ca4a6..4607f009df61 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java
@@ -24,27 +24,25 @@
package com.iluwatar.model.view.controller;
/**
- *
* Model-View-Controller is a pattern for implementing user interfaces. It divides the application
* into three interconnected parts namely the model, the view and the controller.
- *
- * The central component of MVC, the model, captures the behavior of the application in terms of its
- * problem domain, independent of the user interface. The model directly manages the data, logic and
- * rules of the application. A view can be any output representation of information, such as a chart
- * or a diagram The third part, the controller, accepts input and converts it to commands for the
- * model or view.
- *
- * In this example we have a giant ({@link GiantModel}) with statuses for health, fatigue and
- * nourishment. {@link GiantView} can display the giant with its current status.
- * {@link GiantController} receives input affecting the model and delegates redrawing the giant to
- * the view.
*
+ *
The central component of MVC, the model, captures the behavior of the application in terms of
+ * its problem domain, independent of the user interface. The model directly manages the data, logic
+ * and rules of the application. A view can be any output representation of information, such as a
+ * chart or a diagram The third part, the controller, accepts input and converts it to commands for
+ * the model or view.
+ *
+ *
In this example we have a giant ({@link GiantModel}) with statuses for health, fatigue and
+ * nourishment. {@link GiantView} can display the giant with its current status. {@link
+ * GiantController} receives input affecting the model and delegates redrawing the giant to the
+ * view.
*/
public class App {
/**
- * Program entry point
- *
+ * Program entry point.
+ *
* @param args command line args
*/
public static void main(String[] args) {
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java
index 7f0fd293741c..b1663df1f3c1 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java
@@ -24,9 +24,7 @@
package com.iluwatar.model.view.controller;
/**
- *
- * Fatigue enumeration
- *
+ * Fatigue enumeration.
*/
public enum Fatigue {
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java
index e420ec890870..e66608117479 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java
@@ -24,9 +24,7 @@
package com.iluwatar.model.view.controller;
/**
- *
* GiantController can update the giant data and redraw it using the view.
- *
*/
public class GiantController {
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java
index 4ae2c4c195ba..c80d0dba028d 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java
@@ -24,9 +24,7 @@
package com.iluwatar.model.view.controller;
/**
- *
- * GiantModel contains the giant data
- *
+ * GiantModel contains the giant data.
*/
public class GiantModel {
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java
index 9590d609d61f..da14b7c08b60 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java
@@ -27,9 +27,7 @@
import org.slf4j.LoggerFactory;
/**
- *
- * GiantView displays the giant
- *
+ * GiantView displays the giant.
*/
public class GiantView {
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java
index c8b9374bf43b..30b3b2b90aeb 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java
@@ -24,9 +24,7 @@
package com.iluwatar.model.view.controller;
/**
- *
- * Health enumeration
- *
+ * Health enumeration.
*/
public enum Health {
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java
index 9810b201565b..3ced564cc15a 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java
@@ -24,9 +24,7 @@
package com.iluwatar.model.view.controller;
/**
- *
- * Nourishment enumeration
- *
+ * Nourishment enumeration.
*/
public enum Nourishment {
diff --git a/model-view-presenter/pom.xml b/model-view-presenter/pom.xml
index 14de90aed9e8..21ba3f14c56d 100644
--- a/model-view-presenter/pom.xml
+++ b/model-view-presenter/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTmodel-view-presentermodel-view-presenter
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java
index 9b6e6cde833f..43984e8475f8 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java
@@ -24,31 +24,29 @@
package com.iluwatar.model.view.presenter;
/**
- *
- * The Model-View-Presenter(MVP) architectural pattern, helps us achieve what is called
- * "The separation of concerns" principle. This is accomplished by separating the application's
- * logic (Model), GUIs (View), and finally the way that the user's actions update the application's
- * logic (Presenter).
- *
- * In the following example, The {@link FileLoader} class represents the app's logic, the
- * {@link FileSelectorJFrame} is the GUI and the {@link FileSelectorPresenter} is responsible to
- * respond to users' actions.
- *
- * Finally, please notice the wiring between the Presenter and the View and between the Presenter
- * and the Model.
- *
+ * The Model-View-Presenter(MVP) architectural pattern, helps us achieve what is called "The
+ * separation of concerns" principle. This is accomplished by separating the application's logic
+ * (Model), GUIs (View), and finally the way that the user's actions update the application's logic
+ * (Presenter).
+ *
+ *
In the following example, The {@link FileLoader} class represents the app's logic, the {@link
+ * FileSelectorJFrame} is the GUI and the {@link FileSelectorPresenter} is responsible to respond to
+ * users' actions.
+ *
+ *
Finally, please notice the wiring between the Presenter and the View and between the
+ * Presenter and the Model.
*/
public class App {
/**
- * Program entry point
- *
+ * Program entry point.
+ *
* @param args command line args
*/
public static void main(String[] args) {
FileLoader loader = new FileLoader();
- FileSelectorJFrame jFrame = new FileSelectorJFrame();
- FileSelectorPresenter presenter = new FileSelectorPresenter(jFrame);
+ FileSelectorJFrame frame = new FileSelectorJFrame();
+ FileSelectorPresenter presenter = new FileSelectorPresenter(frame);
presenter.setLoader(loader);
presenter.start();
}
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java
index 980c0b56c2e9..9c01b2044f2d 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java
@@ -27,23 +27,22 @@
import java.io.File;
import java.io.FileReader;
import java.io.Serializable;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Every instance of this class represents the Model component in the Model-View-Presenter
* architectural pattern.
- *
- * It is responsible for reading and loading the contents of a given file.
+ *
+ *
It is responsible for reading and loading the contents of a given file.
*/
public class FileLoader implements Serializable {
/**
- * Generated serial version UID
+ * Generated serial version UID.
*/
private static final long serialVersionUID = -4745803872902019069L;
-
+
private static final Logger LOGGER = LoggerFactory.getLogger(FileLoader.class);
/**
@@ -81,7 +80,7 @@ public String loadData() {
/**
* Sets the path of the file to be loaded, to the given value.
- *
+ *
* @param fileName The path of the file to be loaded.
*/
public void setFileName(String fileName) {
@@ -89,6 +88,8 @@ public void setFileName(String fileName) {
}
/**
+ * Gets the path of the file to be loaded.
+ *
* @return fileName The path of the file to be loaded.
*/
public String getFileName() {
@@ -96,6 +97,8 @@ public String getFileName() {
}
/**
+ * Returns true if the given file exists.
+ *
* @return True, if the file given exists, false otherwise.
*/
public boolean fileExists() {
@@ -103,6 +106,8 @@ public boolean fileExists() {
}
/**
+ * Returns true if the given file is loaded.
+ *
* @return True, if the file is loaded, false otherwise.
*/
public boolean isLoaded() {
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java
index 3d9bc035a5ad..77523ccaa7be 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java
@@ -26,7 +26,6 @@
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
-
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
@@ -82,7 +81,7 @@ public class FileSelectorJFrame extends JFrame implements FileSelectorView, Acti
private JPanel panel;
/**
- * The Presenter component that the frame will interact with
+ * The Presenter component that the frame will interact with.
*/
private FileSelectorPresenter presenter;
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java
index a9cf1ba80a4c..35e1c0076712 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java
@@ -28,13 +28,13 @@
/**
* Every instance of this class represents the Presenter component in the Model-View-Presenter
* architectural pattern.
- *
- * It is responsible for reacting to the user's actions and update the View component.
+ *
+ *
It is responsible for reacting to the user's actions and update the View component.
*/
public class FileSelectorPresenter implements Serializable {
/**
- * Generated serial version UID
+ * Generated serial version UID.
*/
private static final long serialVersionUID = 1210314339075855074L;
@@ -49,8 +49,8 @@ public class FileSelectorPresenter implements Serializable {
private FileLoader loader;
/**
- * Constructor
- *
+ * Constructor.
+ *
* @param view The view component that the presenter will interact with.
*/
public FileSelectorPresenter(FileSelectorView view) {
@@ -59,7 +59,7 @@ public FileSelectorPresenter(FileSelectorView view) {
/**
* Sets the {@link FileLoader} object, to the value given as parameter.
- *
+ *
* @param loader The new {@link FileLoader} object(the Model component).
*/
public void setLoader(FileLoader loader) {
@@ -82,7 +82,7 @@ public void fileNameChanged() {
}
/**
- * Ok button handler
+ * Ok button handler.
*/
public void confirmed() {
if (loader.getFileName() == null || loader.getFileName().equals("")) {
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java
index d034bcb04563..1d3aa07fbfcf 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java
@@ -26,12 +26,12 @@
/**
* Every instance of this class represents the Stub component in the Model-View-Presenter
* architectural pattern.
- *
- * The stub implements the View interface and it is useful when we want the test the reaction to
+ *
+ *
The stub implements the View interface and it is useful when we want the test the reaction to
* user events, such as mouse clicks.
- *
- * Since we can not test the GUI directly, the MVP pattern provides this functionality through the
- * View's dummy implementation, the Stub.
+ *
+ *
Since we can not test the GUI directly, the MVP pattern provides this functionality through
+ * the View's dummy implementation, the Stub.
*/
public class FileSelectorStub implements FileSelectorView {
@@ -61,7 +61,7 @@ public class FileSelectorStub implements FileSelectorView {
private boolean dataDisplayed;
/**
- * Constructor
+ * Constructor.
*/
public FileSelectorStub() {
this.opened = false;
@@ -124,6 +124,8 @@ public int getMessagesSent() {
}
/**
+ * Returns true, if the data were displayed.
+ *
* @return True if the data where displayed, false otherwise.
*/
public boolean dataDisplayed() {
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java
index 3deec63d9692..e381784c53b4 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java
@@ -42,44 +42,50 @@ public interface FileSelectorView extends Serializable {
void close();
/**
+ * Returns true if view is opened.
+ *
* @return True, if the view is opened, false otherwise.
*/
boolean isOpened();
/**
* Sets the presenter component, to the one given as parameter.
- *
+ *
* @param presenter The new presenter component.
*/
void setPresenter(FileSelectorPresenter presenter);
/**
+ * Gets presenter component.
+ *
* @return The presenter Component.
*/
FileSelectorPresenter getPresenter();
/**
* Sets the file's name, to the value given as parameter.
- *
+ *
* @param name The new name of the file.
*/
void setFileName(String name);
/**
+ * Gets the name of file.
+ *
* @return The name of the file.
*/
String getFileName();
/**
* Displays a message to the users.
- *
+ *
* @param message The message to be displayed.
*/
void showMessage(String message);
/**
* Displays the data to the view.
- *
+ *
* @param data The data to be written.
*/
void displayData(String data);
diff --git a/module/pom.xml b/module/pom.xml
index 0a60960b53c6..d30353070a15 100644
--- a/module/pom.xml
+++ b/module/pom.xml
@@ -28,7 +28,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTmodule
diff --git a/module/src/main/java/com/iluwatar/module/App.java b/module/src/main/java/com/iluwatar/module/App.java
index af0432afb9af..1b6cbbd23aa2 100644
--- a/module/src/main/java/com/iluwatar/module/App.java
+++ b/module/src/main/java/com/iluwatar/module/App.java
@@ -31,10 +31,9 @@
* An object that applies this pattern can provide the equivalent of a namespace, providing the
* initialization and finalization process of a static class or a class with static members with
* cleaner, more concise syntax and semantics.
- *
- * The below example demonstrates a use case for testing two different modules: File Logger and
+ *
+ *
The below example demonstrates a use case for testing two different modules: File Logger and
* Console Logger
- *
*/
public class App {
@@ -42,10 +41,10 @@ public class App {
public static ConsoleLoggerModule consoleLoggerModule;
/**
- * Following method performs the initialization
- *
+ * Following method performs the initialization.
+ *
* @throws FileNotFoundException if program is not able to find log files (output.txt and
- * error.txt)
+ * error.txt)
*/
public static void prepare() throws FileNotFoundException {
@@ -55,7 +54,7 @@ public static void prepare() throws FileNotFoundException {
}
/**
- * Following method performs the finalization
+ * Following method performs the finalization.
*/
public static void unprepare() {
@@ -65,8 +64,8 @@ public static void unprepare() {
}
/**
- * Following method is main executor
- *
+ * Following method is main executor.
+ *
* @param args for providing default program arguments
*/
public static void execute(final String... args) {
@@ -82,10 +81,10 @@ public static void execute(final String... args) {
/**
* Program entry point.
- *
+ *
* @param args command line args.
* @throws FileNotFoundException if program is not able to find log files (output.txt and
- * error.txt)
+ * error.txt)
*/
public static void main(final String... args) throws FileNotFoundException {
prepare();
diff --git a/module/src/main/java/com/iluwatar/module/ConsoleLoggerModule.java b/module/src/main/java/com/iluwatar/module/ConsoleLoggerModule.java
index 6e6d0539d0ba..7ca0d873d46d 100644
--- a/module/src/main/java/com/iluwatar/module/ConsoleLoggerModule.java
+++ b/module/src/main/java/com/iluwatar/module/ConsoleLoggerModule.java
@@ -23,16 +23,15 @@
package com.iluwatar.module;
+import java.io.PrintStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.PrintStream;
-
/**
- * The ConsoleLoggerModule is responsible for showing logs on System Console
- *
- * The below example demonstrates a Console logger module, which can print simple and error messages
- * in two designated formats
+ * The ConsoleLoggerModule is responsible for showing logs on System Console.
+ *
+ *
The below example demonstrates a Console logger module, which can print simple and error
+ * messages in two designated formats
*/
public final class ConsoleLoggerModule {
@@ -43,11 +42,12 @@ public final class ConsoleLoggerModule {
public PrintStream output = null;
public PrintStream error = null;
- private ConsoleLoggerModule() {}
+ private ConsoleLoggerModule() {
+ }
/**
- * Static method to get single instance of class
- *
+ * Static method to get single instance of class.
+ *
* @return singleton instance of ConsoleLoggerModule
*/
public static ConsoleLoggerModule getSingleton() {
@@ -60,7 +60,7 @@ public static ConsoleLoggerModule getSingleton() {
}
/**
- * Following method performs the initialization
+ * Following method performs the initialization.
*/
public ConsoleLoggerModule prepare() {
@@ -73,7 +73,7 @@ public ConsoleLoggerModule prepare() {
}
/**
- * Following method performs the finalization
+ * Following method performs the finalization.
*/
public void unprepare() {
@@ -93,8 +93,8 @@ public void unprepare() {
}
/**
- * Used to print a message
- *
+ * Used to print a message.
+ *
* @param value will be printed on console
*/
public void printString(final String value) {
@@ -102,8 +102,8 @@ public void printString(final String value) {
}
/**
- * Used to print a error message
- *
+ * Used to print a error message.
+ *
* @param value will be printed on error console
*/
public void printErrorString(final String value) {
diff --git a/module/src/main/java/com/iluwatar/module/FileLoggerModule.java b/module/src/main/java/com/iluwatar/module/FileLoggerModule.java
index e461b31d7572..185bd0ae267d 100644
--- a/module/src/main/java/com/iluwatar/module/FileLoggerModule.java
+++ b/module/src/main/java/com/iluwatar/module/FileLoggerModule.java
@@ -23,18 +23,17 @@
package com.iluwatar.module;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
- * The FileLoggerModule is responsible for showing logs on File System
- *
- * The below example demonstrates a File logger module, which can print simple and error messages in
- * two designated files
+ * The FileLoggerModule is responsible for showing logs on File System.
+ *
+ *
The below example demonstrates a File logger module, which can print simple and error
+ * messages in two designated files
*/
public final class FileLoggerModule {
@@ -48,11 +47,12 @@ public final class FileLoggerModule {
public PrintStream output = null;
public PrintStream error = null;
- private FileLoggerModule() {}
+ private FileLoggerModule() {
+ }
/**
- * Static method to get single instance of class
- *
+ * Static method to get single instance of class.
+ *
* @return singleton instance of FileLoggerModule
*/
public static FileLoggerModule getSingleton() {
@@ -65,10 +65,10 @@ public static FileLoggerModule getSingleton() {
}
/**
- * Following method performs the initialization
- *
+ * Following method performs the initialization.
+ *
* @throws FileNotFoundException if program is not able to find log files (output.txt and
- * error.txt)
+ * error.txt)
*/
public FileLoggerModule prepare() throws FileNotFoundException {
@@ -81,7 +81,7 @@ public FileLoggerModule prepare() throws FileNotFoundException {
}
/**
- * Following method performs the finalization
+ * Following method performs the finalization.
*/
public void unprepare() {
@@ -101,8 +101,8 @@ public void unprepare() {
}
/**
- * Used to print a message
- *
+ * Used to print a message.
+ *
* @param value will be printed in file
*/
public void printString(final String value) {
@@ -110,8 +110,8 @@ public void printString(final String value) {
}
/**
- * Used to print a error message
- *
+ * Used to print a error message.
+ *
* @param value will be printed on error file
*/
public void printErrorString(final String value) {
diff --git a/monad/pom.xml b/monad/pom.xml
index 67768a5d52b3..868cc871059b 100644
--- a/monad/pom.xml
+++ b/monad/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTmonad
diff --git a/monad/src/main/java/com/iluwatar/monad/App.java b/monad/src/main/java/com/iluwatar/monad/App.java
index 94e46548744c..ccb42edd027e 100644
--- a/monad/src/main/java/com/iluwatar/monad/App.java
+++ b/monad/src/main/java/com/iluwatar/monad/App.java
@@ -23,26 +23,27 @@
package com.iluwatar.monad;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
- * The Monad pattern defines a monad structure, that enables chaining operations
- * in pipelines and processing data step by step.
- * Formally, monad consists of a type constructor M and two operations:
+ * The Monad pattern defines a monad structure, that enables chaining operations in pipelines and
+ * processing data step by step. Formally, monad consists of a type constructor M and two
+ * operations:
* bind - that takes monadic object and a function from plain object to the
* monadic value and returns monadic value.
* return - that takes plain type object and returns this object wrapped in a monadic value.
- *
- * In the given example, the Monad pattern is represented as a {@link Validator} that takes an instance
- * of a plain object with {@link Validator#of(Object)}
- * and validates it {@link Validator#validate(Function, Predicate, String)} against given predicates.
- *
As a validation result {@link Validator#get()} it either returns valid object {@link Validator#t}
- * or throws a list of exceptions {@link Validator#exceptions} collected during validation.
+ *
+ *
In the given example, the Monad pattern is represented as a {@link Validator} that takes an
+ * instance of a plain object with {@link Validator#of(Object)} and validates it {@link
+ * Validator#validate(Function, Predicate, String)} against given predicates.
+ *
+ *
As a validation result {@link Validator#get()} it either returns valid object {@link
+ * Validator#t} or throws a list of exceptions {@link Validator#exceptions} collected during
+ * validation.
*/
public class App {
@@ -58,6 +59,7 @@ public static void main(String[] args) {
LOGGER.info(Validator.of(user).validate(User::getName, Objects::nonNull, "name is null")
.validate(User::getName, name -> !name.isEmpty(), "name is empty")
.validate(User::getEmail, email -> !email.contains("@"), "email doesn't containt '@'")
- .validate(User::getAge, age -> age > 20 && age < 30, "age isn't between...").get().toString());
+ .validate(User::getAge, age -> age > 20 && age < 30, "age isn't between...").get()
+ .toString());
}
}
diff --git a/monad/src/main/java/com/iluwatar/monad/Sex.java b/monad/src/main/java/com/iluwatar/monad/Sex.java
index 960711656021..cc772c340009 100644
--- a/monad/src/main/java/com/iluwatar/monad/Sex.java
+++ b/monad/src/main/java/com/iluwatar/monad/Sex.java
@@ -24,7 +24,7 @@
package com.iluwatar.monad;
/**
- * Enumeration of Types of Sex
+ * Enumeration of Types of Sex.
*/
public enum Sex {
MALE, FEMALE
diff --git a/monad/src/main/java/com/iluwatar/monad/User.java b/monad/src/main/java/com/iluwatar/monad/User.java
index 9ecaa527539c..77766d1aa25f 100644
--- a/monad/src/main/java/com/iluwatar/monad/User.java
+++ b/monad/src/main/java/com/iluwatar/monad/User.java
@@ -24,7 +24,7 @@
package com.iluwatar.monad;
/**
- * User Definition
+ * User Definition.
*/
public class User {
@@ -34,6 +34,8 @@ public class User {
private String email;
/**
+ * Constructor.
+ *
* @param name - name
* @param age - age
* @param sex - sex
diff --git a/monad/src/main/java/com/iluwatar/monad/Validator.java b/monad/src/main/java/com/iluwatar/monad/Validator.java
index b5618f91c390..2d1f1bdab177 100644
--- a/monad/src/main/java/com/iluwatar/monad/Validator.java
+++ b/monad/src/main/java/com/iluwatar/monad/Validator.java
@@ -30,18 +30,18 @@
import java.util.function.Predicate;
/**
- * Class representing Monad design pattern. Monad is a way of chaining operations on the
- * given object together step by step. In Validator each step results in either success or
- * failure indicator, giving a way of receiving each of them easily and finally getting
- * validated object or list of exceptions.
+ * Class representing Monad design pattern. Monad is a way of chaining operations on the given
+ * object together step by step. In Validator each step results in either success or failure
+ * indicator, giving a way of receiving each of them easily and finally getting validated object or
+ * list of exceptions.
*
* @param Placeholder for an object.
*/
public class Validator {
/**
- * Object that is validated
+ * Object that is validated.
*/
- private final T t;
+ private final T obj;
/**
* List of exception thrown during validation.
@@ -50,14 +50,15 @@ public class Validator {
/**
* Creates a monadic value of given object.
- * @param t object to be validated
+ *
+ * @param obj object to be validated
*/
- private Validator(T t) {
- this.t = t;
+ private Validator(T obj) {
+ this.obj = obj;
}
/**
- * Creates validator against given object
+ * Creates validator against given object.
*
* @param t object to be validated
* @param object's type
@@ -68,25 +69,27 @@ public static Validator of(T t) {
}
/**
- * @param validation one argument boolean-valued function that
- * represents one step of validation. Adds exception to main validation exception
- * list when single step validation ends with failure.
+ * Checks if the validation is successful.
+ *
+ * @param validation one argument boolean-valued function that represents one step of validation.
+ * Adds exception to main validation exception list when single step validation
+ * ends with failure.
* @param message error message when object is invalid
* @return this
*/
public Validator validate(Predicate validation, String message) {
- if (!validation.test(t)) {
+ if (!validation.test(obj)) {
exceptions.add(new IllegalStateException(message));
}
return this;
}
/**
- * Extension for the {@link Validator#validate(Function, Predicate, String)} method,
- * dedicated for objects, that need to be projected before requested validation.
+ * Extension for the {@link Validator#validate(Function, Predicate, String)} method, dedicated for
+ * objects, that need to be projected before requested validation.
*
- * @param projection function that gets an objects, and returns projection representing
- * element to be validated.
+ * @param projection function that gets an objects, and returns projection representing element to
+ * be validated.
* @param validation see {@link Validator#validate(Function, Predicate, String)}
* @param message see {@link Validator#validate(Function, Predicate, String)}
* @param see {@link Validator#validate(Function, Predicate, String)}
@@ -105,7 +108,7 @@ public Validator validate(Function projection, Predicate validat
*/
public T get() throws IllegalStateException {
if (exceptions.isEmpty()) {
- return t;
+ return obj;
}
IllegalStateException e = new IllegalStateException();
exceptions.forEach(e::addSuppressed);
diff --git a/monostate/pom.xml b/monostate/pom.xml
index b39ef2d95b06..0e51fc70084a 100644
--- a/monostate/pom.xml
+++ b/monostate/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTmonostate
diff --git a/monostate/src/main/java/com/iluwatar/monostate/App.java b/monostate/src/main/java/com/iluwatar/monostate/App.java
index 4b6f8b14b64d..64cb384612c1 100644
--- a/monostate/src/main/java/com/iluwatar/monostate/App.java
+++ b/monostate/src/main/java/com/iluwatar/monostate/App.java
@@ -24,28 +24,22 @@
package com.iluwatar.monostate;
-
/**
- *
* The MonoState pattern ensures that all instances of the class will have the same state. This can
* be used a direct replacement of the Singleton pattern.
- *
- *
- * In the following example, The {@link LoadBalancer} class represents the app's logic. It contains
- * a series of Servers, which can handle requests of type {@link Request}. Two instances of
+ *
+ *
In the following example, The {@link LoadBalancer} class represents the app's logic. It
+ * contains a series of Servers, which can handle requests of type {@link Request}. Two instances of
* LoadBalacer are created. When a request is made to a server via the first LoadBalancer the state
* change in the first load balancer affects the second. So if the first LoadBalancer selects the
* Server 1, the second LoadBalancer on a new request will select the Second server. If a third
* LoadBalancer is created and a new request is made to it, then it will select the third server as
* the second load balancer has already selected the second server.
- *
- * .
- *
*/
public class App {
/**
- * Program entry point
- *
+ * Program entry point.
+ *
* @param args command line args
*/
public static void main(String[] args) {
diff --git a/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java b/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java
index ae590be5ee5d..8546ae1777bf 100644
--- a/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java
+++ b/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java
@@ -31,7 +31,6 @@
* receiving a new Request, it delegates the call to the servers in a Round Robin Fashion. Since all
* instances of the class share the same state, all instances will delegate to the same server on
* receiving a new Request.
- *
*/
public class LoadBalancer {
@@ -40,13 +39,13 @@ public class LoadBalancer {
static {
int id = 0;
- for (int port : new int[] {8080, 8081, 8082, 8083, 8084}) {
+ for (int port : new int[]{8080, 8081, 8082, 8083, 8084}) {
SERVERS.add(new Server("localhost", port, ++id));
}
}
/**
- * Add new server
+ * Add new server.
*/
public final void addServer(Server server) {
synchronized (SERVERS) {
@@ -64,7 +63,7 @@ public int getLastServedId() {
}
/**
- * Handle request
+ * Handle request.
*/
public synchronized void serverRequest(Request request) {
if (lastServedId >= SERVERS.size()) {
@@ -73,5 +72,5 @@ public synchronized void serverRequest(Request request) {
Server server = SERVERS.get(lastServedId++);
server.serve(request);
}
-
+
}
diff --git a/monostate/src/main/java/com/iluwatar/monostate/Request.java b/monostate/src/main/java/com/iluwatar/monostate/Request.java
index 5a7429998ac1..d7e4fcf8f9a5 100644
--- a/monostate/src/main/java/com/iluwatar/monostate/Request.java
+++ b/monostate/src/main/java/com/iluwatar/monostate/Request.java
@@ -24,9 +24,7 @@
package com.iluwatar.monostate;
/**
- *
* The Request class. A {@link Server} can handle an instance of a Request.
- *
*/
public class Request {
diff --git a/monostate/src/main/java/com/iluwatar/monostate/Server.java b/monostate/src/main/java/com/iluwatar/monostate/Server.java
index fa809864cb83..cd08b2b29613 100644
--- a/monostate/src/main/java/com/iluwatar/monostate/Server.java
+++ b/monostate/src/main/java/com/iluwatar/monostate/Server.java
@@ -27,10 +27,8 @@
import org.slf4j.LoggerFactory;
/**
- *
* The Server class. Each Server sits behind a LoadBalancer which delegates the call to the servers
* in a simplistic Round Robin fashion.
- *
*/
public class Server {
@@ -41,7 +39,7 @@ public class Server {
public final int id;
/**
- * Constructor
+ * Constructor.
*/
public Server(String host, int port, int id) {
this.host = host;
@@ -59,6 +57,6 @@ public int getPort() {
public void serve(Request request) {
LOGGER.info("Server ID {} associated to host : {} and port {}. Processed request with value {}",
- id, host, port, request.value);
+ id, host, port, request.value);
}
}
diff --git a/multiton/pom.xml b/multiton/pom.xml
index cd827aa6de27..39deb9e4dcbe 100644
--- a/multiton/pom.xml
+++ b/multiton/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTmultiton
diff --git a/multiton/src/main/java/com/iluwatar/multiton/App.java b/multiton/src/main/java/com/iluwatar/multiton/App.java
index 8fb226625eae..eb3e0313fe1f 100644
--- a/multiton/src/main/java/com/iluwatar/multiton/App.java
+++ b/multiton/src/main/java/com/iluwatar/multiton/App.java
@@ -27,26 +27,24 @@
import org.slf4j.LoggerFactory;
/**
- *
* Whereas Singleton design pattern introduces single globally accessible object the Multiton
* pattern defines many globally accessible objects. The client asks for the correct instance from
* the Multiton by passing an enumeration as parameter.
- *
- * There is more than one way to implement the multiton design pattern. In the first example
- * {@link Nazgul} is the Multiton and we can ask single {@link Nazgul} from it using {@link NazgulName}.
- * The {@link Nazgul}s are statically initialized and stored in concurrent hash map.
- *
- * In the enum implementation {@link NazgulEnum} is the multiton. It is static and mutable because
- * of the way java supports enums.
*
+ *
There is more than one way to implement the multiton design pattern. In the first example
+ * {@link Nazgul} is the Multiton and we can ask single {@link Nazgul} from it using {@link
+ * NazgulName}. The {@link Nazgul}s are statically initialized and stored in concurrent hash map.
+ *
+ *
In the enum implementation {@link NazgulEnum} is the multiton. It is static and mutable
+ * because of the way java supports enums.
*/
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/**
- * Program entry point
- *
+ * Program entry point.
+ *
* @param args command line args
*/
public static void main(String[] args) {
@@ -60,7 +58,7 @@ public static void main(String[] args) {
LOGGER.info("ADUNAPHEL={}", Nazgul.getInstance(NazgulName.ADUNAPHEL));
LOGGER.info("REN={}", Nazgul.getInstance(NazgulName.REN));
LOGGER.info("UVATHA={}", Nazgul.getInstance(NazgulName.UVATHA));
-
+
// enum multiton
LOGGER.info("KHAMUL={}", NazgulEnum.KHAMUL);
LOGGER.info("MURAZOR={}", NazgulEnum.MURAZOR);
diff --git a/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java b/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java
index 52a25e00d665..f55f85aca722 100644
--- a/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java
+++ b/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java
@@ -27,9 +27,7 @@
import java.util.concurrent.ConcurrentHashMap;
/**
- *
* Nazgul is a Multiton class. Nazgul instances can be queried using {@link #getInstance} method.
- *
*/
public final class Nazgul {
diff --git a/multiton/src/main/java/com/iluwatar/multiton/NazgulEnum.java b/multiton/src/main/java/com/iluwatar/multiton/NazgulEnum.java
index f119ee68fb59..5b5c48d66ff1 100644
--- a/multiton/src/main/java/com/iluwatar/multiton/NazgulEnum.java
+++ b/multiton/src/main/java/com/iluwatar/multiton/NazgulEnum.java
@@ -24,11 +24,10 @@
package com.iluwatar.multiton;
/**
- * enum based multiton implementation
- *
+ * enum based multiton implementation.
*/
public enum NazgulEnum {
-
+
KHAMUL, MURAZOR, DWAR, JI_INDUR, AKHORAHIL, HOARMURATH, ADUNAPHEL, REN, UVATHA;
}
diff --git a/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java b/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java
index 5fe2a5a0f427..c7865dceb0a9 100644
--- a/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java
+++ b/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java
@@ -24,9 +24,7 @@
package com.iluwatar.multiton;
/**
- *
* Each Nazgul has different {@link NazgulName}.
- *
*/
public enum NazgulName {
diff --git a/mute-idiom/pom.xml b/mute-idiom/pom.xml
index aeb18dc5ce6e..91f5063a7a0e 100644
--- a/mute-idiom/pom.xml
+++ b/mute-idiom/pom.xml
@@ -30,7 +30,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTmute-idiom
diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/App.java b/mute-idiom/src/main/java/com/iluwatar/mute/App.java
index 28649e24990a..d4f140bf089e 100644
--- a/mute-idiom/src/main/java/com/iluwatar/mute/App.java
+++ b/mute-idiom/src/main/java/com/iluwatar/mute/App.java
@@ -23,19 +23,17 @@
package com.iluwatar.mute;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.SQLException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
- * Mute pattern is utilized when we need to suppress an exception due to an API flaw or in
- * situation when all we can do to handle the exception is to log it.
- * This pattern should not be used everywhere. It is very important to logically handle the
- * exceptions in a system, but some situations like the ones described above require this pattern,
- * so that we don't need to repeat
+ * Mute pattern is utilized when we need to suppress an exception due to an API flaw or in situation
+ * when all we can do to handle the exception is to log it. This pattern should not be used
+ * everywhere. It is very important to logically handle the exceptions in a system, but some
+ * situations like the ones described above require this pattern, so that we don't need to repeat
*
*
* try {
@@ -45,7 +43,6 @@
* }
*
*
every time we need to ignore an exception.
- *
*/
public class App {
@@ -53,7 +50,7 @@ public class App {
/**
* Program entry point.
- *
+ *
* @param args command line args.
* @throws Exception if any exception occurs
*/
@@ -65,7 +62,7 @@ public static void main(String[] args) throws Exception {
}
/*
- * Typically used when the API declares some exception but cannot do so. Usually a
+ * Typically used when the API declares some exception but cannot do so. Usually a
* signature mistake.In this example out is not supposed to throw exception as it is a
* ByteArrayOutputStream. So we utilize mute, which will throw AssertionError if unexpected
* exception occurs.
@@ -98,7 +95,7 @@ private static void utilizeResource(Resource resource) throws SQLException {
private static Resource acquireResource() throws SQLException {
return new Resource() {
-
+
@Override
public void close() throws IOException {
throw new IOException("Error in closing resource: " + this);
diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java b/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java
index d5fdaaec2b34..f15153d0083d 100644
--- a/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java
+++ b/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java
@@ -25,12 +25,12 @@
/**
* A runnable which may throw exception on execution.
- *
*/
@FunctionalInterface
public interface CheckedRunnable {
/**
* Same as {@link Runnable#run()} with a possibility of exception in execution.
+ *
* @throws Exception if any exception occurs.
*/
void run() throws Exception;
diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java b/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java
index 87a1f651e77f..30e1698d5d1b 100644
--- a/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java
+++ b/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java
@@ -30,17 +30,18 @@
* A utility class that allows you to utilize mute idiom.
*/
public final class Mute {
-
+
// The constructor is never meant to be called.
- private Mute() {}
+ private Mute() {
+ }
/**
- * Executes the runnable and throws the exception occurred within a {@link AssertionError}.
- * This method should be utilized to mute the operations that are guaranteed not to throw an exception.
- * For instance {@link ByteArrayOutputStream#write(byte[])} declares in it's signature that it can throw
- * an {@link IOException}, but in reality it cannot. This is because the bulk write method is not overridden
- * in {@link ByteArrayOutputStream}.
- *
+ * Executes the runnable and throws the exception occurred within a {@link
+ * AssertionError}. This method should be utilized to mute the operations that are guaranteed not
+ * to throw an exception. For instance {@link ByteArrayOutputStream#write(byte[])} declares in
+ * it's signature that it can throw an {@link IOException}, but in reality it cannot. This is
+ * because the bulk write method is not overridden in {@link ByteArrayOutputStream}.
+ *
* @param runnable a runnable that should never throw an exception on execution.
*/
public static void mute(CheckedRunnable runnable) {
@@ -52,11 +53,11 @@ public static void mute(CheckedRunnable runnable) {
}
/**
- * Executes the runnable and logs the exception occurred on {@link System#err}.
- * This method should be utilized to mute the operations about which most you can do is log.
- * For instance while closing a connection to database, or cleaning up a resource,
- * all you can do is log the exception occurred.
- *
+ * Executes the runnable and logs the exception occurred on {@link System#err}. This
+ * method should be utilized to mute the operations about which most you can do is log. For
+ * instance while closing a connection to database, or cleaning up a resource, all you can do is
+ * log the exception occurred.
+ *
* @param runnable a runnable that may throw an exception on execution.
*/
public static void loggedMute(CheckedRunnable runnable) {
diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java b/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java
index a10fe4617605..e56025ce4ea8 100644
--- a/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java
+++ b/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java
@@ -26,9 +26,8 @@
import java.io.Closeable;
/**
- * Represents any resource that the application might acquire and that must be closed
- * after it is utilized. Example of such resources can be a database connection, open
- * files, sockets.
+ * Represents any resource that the application might acquire and that must be closed after it is
+ * utilized. Example of such resources can be a database connection, open files, sockets.
*/
public interface Resource extends Closeable {
diff --git a/mutex/pom.xml b/mutex/pom.xml
index 05f9295eead8..c1cad3d8aae4 100644
--- a/mutex/pom.xml
+++ b/mutex/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTmutex
diff --git a/mutex/src/main/java/com/iluwatar/mutex/App.java b/mutex/src/main/java/com/iluwatar/mutex/App.java
index 827307d0f884..e4a952ef9f46 100644
--- a/mutex/src/main/java/com/iluwatar/mutex/App.java
+++ b/mutex/src/main/java/com/iluwatar/mutex/App.java
@@ -25,19 +25,17 @@
/**
* A Mutex prevents multiple threads from accessing a resource simultaneously.
- *
- * In this example we have two thieves who are taking beans from a jar.
- * Only one thief can take a bean at a time. This is ensured by a Mutex lock
- * which must be acquired in order to access the jar. Each thief attempts to
- * acquire the lock, take a bean and then release the lock. If the lock has
- * already been acquired, the thief will be prevented from continuing (blocked)
- * until the lock has been released. The thieves stop taking beans once there
- * are no beans left to take.
+ *
+ *
In this example we have two thieves who are taking beans from a jar. Only one thief can take
+ * a bean at a time. This is ensured by a Mutex lock which must be acquired in order to access the
+ * jar. Each thief attempts to acquire the lock, take a bean and then release the lock. If the lock
+ * has already been acquired, the thief will be prevented from continuing (blocked) until the lock
+ * has been released. The thieves stop taking beans once there are no beans left to take.
*/
public class App {
/**
- * main method
+ * main method.
*/
public static void main(String[] args) {
Mutex mutex = new Mutex();
diff --git a/mutex/src/main/java/com/iluwatar/mutex/Jar.java b/mutex/src/main/java/com/iluwatar/mutex/Jar.java
index 427907f31d90..f68b266add5f 100644
--- a/mutex/src/main/java/com/iluwatar/mutex/Jar.java
+++ b/mutex/src/main/java/com/iluwatar/mutex/Jar.java
@@ -24,9 +24,8 @@
package com.iluwatar.mutex;
/**
- * A Jar has a resource of beans which can only be accessed by a single Thief
- * (thread) at any one time. A Mutex lock is used to prevent more than one Thief
- * taking a bean simultaneously.
+ * A Jar has a resource of beans which can only be accessed by a single Thief (thread) at any one
+ * time. A Mutex lock is used to prevent more than one Thief taking a bean simultaneously.
*/
public class Jar {
diff --git a/mutex/src/main/java/com/iluwatar/mutex/Mutex.java b/mutex/src/main/java/com/iluwatar/mutex/Mutex.java
index a2ef71f11d1f..6c62cc8ea930 100644
--- a/mutex/src/main/java/com/iluwatar/mutex/Mutex.java
+++ b/mutex/src/main/java/com/iluwatar/mutex/Mutex.java
@@ -34,16 +34,15 @@ public class Mutex implements Lock {
private Object owner;
/**
- * Returns the current owner of the Mutex, or null if available
+ * Returns the current owner of the Mutex, or null if available.
*/
public Object getOwner() {
return owner;
}
-
+
/**
- * Method called by a thread to acquire the lock. If the lock has already
- * been acquired this will wait until the lock has been released to
- * re-attempt the acquire.
+ * Method called by a thread to acquire the lock. If the lock has already been acquired this will
+ * wait until the lock has been released to re-attempt the acquire.
*/
@Override
public synchronized void acquire() throws InterruptedException {
diff --git a/mutex/src/main/java/com/iluwatar/mutex/Thief.java b/mutex/src/main/java/com/iluwatar/mutex/Thief.java
index f88e46d96fab..29caba540ad1 100644
--- a/mutex/src/main/java/com/iluwatar/mutex/Thief.java
+++ b/mutex/src/main/java/com/iluwatar/mutex/Thief.java
@@ -27,20 +27,20 @@
import org.slf4j.LoggerFactory;
/**
- * Thief is a class which continually tries to acquire a jar and take a bean
- * from it. When the jar is empty the thief stops.
+ * Thief is a class which continually tries to acquire a jar and take a bean from it. When the jar
+ * is empty the thief stops.
*/
public class Thief extends Thread {
private static final Logger LOGGER = LoggerFactory.getLogger(Thief.class);
/**
- * The name of the thief.
+ * The name of the thief.
*/
private final String name;
-
+
/**
- * The jar
+ * The jar.
*/
private final Jar jar;
@@ -50,8 +50,7 @@ public Thief(String name, Jar jar) {
}
/**
- * In the run method the thief repeatedly tries to take a bean until none
- * are left.
+ * In the run method the thief repeatedly tries to take a bean until none are left.
*/
@Override
public void run() {
diff --git a/naked-objects/dom/pom.xml b/naked-objects/dom/pom.xml
index 2709edda03f4..dffc1650caad 100644
--- a/naked-objects/dom/pom.xml
+++ b/naked-objects/dom/pom.xml
@@ -30,7 +30,7 @@
com.iluwatarnaked-objects
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTnaked-objects-dom
diff --git a/naked-objects/fixture/pom.xml b/naked-objects/fixture/pom.xml
index 9de092976117..3457ac0a42ab 100644
--- a/naked-objects/fixture/pom.xml
+++ b/naked-objects/fixture/pom.xml
@@ -30,7 +30,7 @@
com.iluwatarnaked-objects
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTnaked-objects-fixture
diff --git a/naked-objects/integtests/pom.xml b/naked-objects/integtests/pom.xml
index 62d25df032c9..f46541f48fb4 100644
--- a/naked-objects/integtests/pom.xml
+++ b/naked-objects/integtests/pom.xml
@@ -30,7 +30,7 @@
com.iluwatarnaked-objects
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTnaked-objects-integtests
diff --git a/naked-objects/pom.xml b/naked-objects/pom.xml
index b035c3894058..0ca5a3ef3cb4 100644
--- a/naked-objects/pom.xml
+++ b/naked-objects/pom.xml
@@ -29,7 +29,7 @@
java-design-patternscom.iluwatar
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTnaked-objectspom
@@ -333,17 +333,17 @@
${project.groupId}naked-objects-dom
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOT${project.groupId}naked-objects-fixture
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOT${project.groupId}naked-objects-webapp
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOT
diff --git a/naked-objects/webapp/pom.xml b/naked-objects/webapp/pom.xml
index e0697b855b31..bdf638cbaa3a 100644
--- a/naked-objects/webapp/pom.xml
+++ b/naked-objects/webapp/pom.xml
@@ -30,7 +30,7 @@
com.iluwatarnaked-objects
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTnaked-objects-webapp
diff --git a/null-object/pom.xml b/null-object/pom.xml
index 7111c8ff9822..d80b97d95734 100644
--- a/null-object/pom.xml
+++ b/null-object/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTnull-object
diff --git a/object-mother/pom.xml b/object-mother/pom.xml
index e59607414c6e..5ac3ce410b6c 100644
--- a/object-mother/pom.xml
+++ b/object-mother/pom.xml
@@ -30,7 +30,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTobject-mother
diff --git a/object-pool/pom.xml b/object-pool/pom.xml
index efbb7ee4047c..fdd247476d12 100644
--- a/object-pool/pom.xml
+++ b/object-pool/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTobject-pool
diff --git a/observer/pom.xml b/observer/pom.xml
index 9a538aa294d9..fc8a53eae564 100644
--- a/observer/pom.xml
+++ b/observer/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTobserver
diff --git a/page-object/pom.xml b/page-object/pom.xml
index 7a3db030ee16..99c67dbc5f38 100644
--- a/page-object/pom.xml
+++ b/page-object/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTpage-objectpom
diff --git a/page-object/sample-application/pom.xml b/page-object/sample-application/pom.xml
index c21e52e9901c..5ded184cc74f 100644
--- a/page-object/sample-application/pom.xml
+++ b/page-object/sample-application/pom.xml
@@ -29,7 +29,7 @@
page-objectcom.iluwatar
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTsample-application
diff --git a/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java b/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java
index aae08c15f80e..e3a86599c3fb 100644
--- a/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java
+++ b/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java
@@ -26,63 +26,60 @@
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Page Object pattern wraps an UI component with an application specific API allowing you to
- * manipulate the UI elements without having to dig around with the underlying UI technology used. This is
- * especially useful for testing as it means your tests will be less brittle. Your tests can concentrate on
- * the actual test cases where as the manipulation of the UI can be left to the internals of the page object
- * itself.
+ * manipulate the UI elements without having to dig around with the underlying UI technology used.
+ * This is especially useful for testing as it means your tests will be less brittle. Your tests can
+ * concentrate on the actual test cases where as the manipulation of the UI can be left to the
+ * internals of the page object itself.
*
- *
- * Due to this reason, it has become very popular within the test automation community.
- * In particular, it is very common in that the page object is used to represent the html pages of a
- * web application that is under test. This web application is referred to as AUT (Application Under Test).
- * A web browser automation tool/framework like Selenium for instance, is then used to drive the automating
- * of the browser navigation and user actions journeys through this web application. Your test class would
- * therefore only be responsible for particular test cases and page object would be used by the test class
- * for UI manipulation required for the tests.
+ *
Due to this reason, it has become very popular within the test automation community. In
+ * particular, it is very common in that the page object is used to represent the html pages of a
+ * web application that is under test. This web application is referred to as AUT (Application Under
+ * Test). A web browser automation tool/framework like Selenium for instance, is then used to drive
+ * the automating of the browser navigation and user actions journeys through this web application.
+ * Your test class would therefore only be responsible for particular test cases and page object
+ * would be used by the test class for UI manipulation required for the tests.
*
- *
- * In this implementation rather than using Selenium, the HtmlUnit library is used as a replacement to
- * represent the specific html elements and to drive the browser. The purpose of this example is just to
- * provide a simple version that showcase the intentions of this pattern and how this pattern is used
- * in order to understand it.
+ *
In this implementation rather than using Selenium, the HtmlUnit library is used as a
+ * replacement to represent the specific html elements and to drive the browser. The purpose of this
+ * example is just to provide a simple version that showcase the intentions of this pattern and how
+ * this pattern is used in order to understand it.
*/
public final class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
+
private App() {
}
/**
* Application entry point
*
- *
- * The application under development is a web application. Normally you would probably have a
- * backend that is probably implemented in an object-oriented language (e.g. Java) that serves
- * the frontend which comprises of a series of HTML, CSS, JS etc...
+ *
The application under development is a web application. Normally you would probably have a
+ * backend that is probably implemented in an object-oriented language (e.g. Java) that serves the
+ * frontend which comprises of a series of HTML, CSS, JS etc...
*
- *
- * For illustrations purposes only, a very simple static html app is used here. This main method
- * just fires up this simple web app in a default browser.
+ *
For illustrations purposes only, a very simple static html app is used here. This main
+ * method just fires up this simple web app in a default browser.
*
* @param args arguments
*/
public static void main(String[] args) {
try {
- File applicationFile = new File(App.class.getClassLoader().getResource("sample-ui/login.html").getPath());
+ File applicationFile =
+ new File(App.class.getClassLoader().getResource("sample-ui/login.html").getPath());
// should work for unix like OS (mac, unix etc...)
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(applicationFile);
} else {
- // java Desktop not supported - above unlikely to work for Windows so try following instead...
+ // java Desktop not supported - above unlikely to work for Windows so try instead...
Runtime.getRuntime().exec("cmd.exe start " + applicationFile);
}
diff --git a/page-object/src/main/java/com/iluwatar/pageobject/App.java b/page-object/src/main/java/com/iluwatar/pageobject/App.java
index c76867e89899..ee9f58504a0b 100644
--- a/page-object/src/main/java/com/iluwatar/pageobject/App.java
+++ b/page-object/src/main/java/com/iluwatar/pageobject/App.java
@@ -29,25 +29,23 @@
/**
* Page Object pattern wraps an UI component with an application specific API allowing you to
- * manipulate the UI elements without having to dig around with the underlying UI technology used. This is
- * especially useful for testing as it means your tests will be less brittle. Your tests can concentrate on
- * the actual test cases where as the manipulation of the UI can be left to the internals of the page object
- * itself.
+ * manipulate the UI elements without having to dig around with the underlying UI technology used.
+ * This is especially useful for testing as it means your tests will be less brittle. Your tests can
+ * concentrate on the actual test cases where as the manipulation of the UI can be left to the
+ * internals of the page object itself.
*
- *
- * Due to this reason, it has become very popular within the test automation community.
- * In particular, it is very common in that the page object is used to represent the html pages of a
- * web application that is under test. This web application is referred to as AUT (Application Under Test).
- * A web browser automation tool/framework like Selenium for instance, is then used to drive the automating
- * of the browser navigation and user actions journeys through this web application. Your test class would
- * therefore only be responsible for particular test cases and page object would be used by the test class
- * for UI manipulation required for the tests.
+ *
Due to this reason, it has become very popular within the test automation community. In
+ * particular, it is very common in that the page object is used to represent the html pages of a
+ * web application that is under test. This web application is referred to as AUT (Application Under
+ * Test). A web browser automation tool/framework like Selenium for instance, is then used to drive
+ * the automating of the browser navigation and user actions journeys through this web application.
+ * Your test class would therefore only be responsible for particular test cases and page object
+ * would be used by the test class for UI manipulation required for the tests.
*
- *
- * In this implementation rather than using Selenium, the HtmlUnit library is used as a replacement to
- * represent the specific html elements and to drive the browser. The purpose of this example is just to
- * provide a simple version that showcase the intentions of this pattern and how this pattern is used
- * in order to understand it.
+ *
In this implementation rather than using Selenium, the HtmlUnit library is used as a
+ * replacement to represent the specific html elements and to drive the browser. The purpose of this
+ * example is just to provide a simple version that showcase the intentions of this pattern and how
+ * this pattern is used in order to understand it.
*/
public final class App {
@@ -57,28 +55,28 @@ private App() {
/**
* Application entry point
*
- *
- * The application under development is a web application. Normally you would probably have a
- * backend that is probably implemented in an object-oriented language (e.g. Java) that serves
- * the frontend which comprises of a series of HTML, CSS, JS etc...
+ *
The application under development is a web application. Normally you would probably have a
+ * backend that is probably implemented in an object-oriented language (e.g. Java) that serves the
+ * frontend which comprises of a series of HTML, CSS, JS etc...
*
- *
- * For illustrations purposes only, a very simple static html app is used here. This main method
- * just fires up this simple web app in a default browser.
+ *
For illustrations purposes only, a very simple static html app is used here. This main
+ * method just fires up this simple web app in a default browser.
*
* @param args arguments
*/
public static void main(String[] args) {
try {
- File applicationFile = new File(App.class.getClassLoader().getResource("sample-ui/login.html").getPath());
+ File applicationFile =
+ new File(App.class.getClassLoader().getResource("sample-ui/login.html").getPath());
- // should work for unix like OS (mac, unix etc...)
+ // Should work for unix like OS (mac, unix etc...)
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(applicationFile);
} else {
- // java Desktop not supported - above unlikely to work for Windows so try following instead...
+ // Java Desktop not supported - above unlikely to work for Windows so try the
+ // following instead...
Runtime.getRuntime().exec("cmd.exe start " + applicationFile);
}
diff --git a/page-object/test-automation/pom.xml b/page-object/test-automation/pom.xml
index 5b275084c4cf..68025f4b82dd 100644
--- a/page-object/test-automation/pom.xml
+++ b/page-object/test-automation/pom.xml
@@ -29,7 +29,7 @@
page-objectcom.iluwatar
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTtest-automation
diff --git a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumListPage.java b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumListPage.java
index feab7838c7bd..2851d24d54c1 100644
--- a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumListPage.java
+++ b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumListPage.java
@@ -26,10 +26,8 @@
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
-
import java.io.IOException;
import java.util.List;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -46,7 +44,7 @@ public class AlbumListPage extends Page {
/**
- * Constructor
+ * Constructor.
*/
public AlbumListPage(WebClient webClient) {
super(webClient);
@@ -54,7 +52,7 @@ public AlbumListPage(WebClient webClient) {
/**
- * Navigates to the Album List Page
+ * Navigates to the Album List Page.
*
* @return {@link AlbumListPage}
*/
@@ -76,7 +74,7 @@ public boolean isAt() {
}
/**
- * Selects an album by the given album title
+ * Selects an album by the given album title.
*
* @param albumTitle the title of the album to click
* @return the album page
diff --git a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumPage.java b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumPage.java
index cf8c50dd74a1..953a47ba2e39 100644
--- a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumPage.java
+++ b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumPage.java
@@ -23,11 +23,6 @@
package com.iluwatar.pageobject;
-import java.io.IOException;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlNumberInput;
import com.gargoylesoftware.htmlunit.html.HtmlOption;
@@ -35,6 +30,9 @@
import com.gargoylesoftware.htmlunit.html.HtmlSelect;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
+import java.io.IOException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Page Object encapsulating the Album Page (album-page.html)
@@ -49,7 +47,7 @@ public class AlbumPage extends Page {
/**
- * Constructor
+ * Constructor.
*/
public AlbumPage(WebClient webClient) {
super(webClient);
@@ -57,7 +55,7 @@ public AlbumPage(WebClient webClient) {
/**
- * Navigates to the album page
+ * Navigates to the album page.
*
* @return {@link AlbumPage}
*/
@@ -81,7 +79,7 @@ public boolean isAt() {
/**
- * Sets the album title input text field
+ * Sets the album title input text field.
*
* @param albumTitle the new album title value to set
* @return {@link AlbumPage}
@@ -94,7 +92,7 @@ public AlbumPage changeAlbumTitle(String albumTitle) {
/**
- * Sets the artist input text field
+ * Sets the artist input text field.
*
* @param artist the new artist value to set
* @return {@link AlbumPage}
@@ -107,7 +105,7 @@ public AlbumPage changeArtist(String artist) {
/**
- * Selects the select's option value based on the year value given
+ * Selects the select's option value based on the year value given.
*
* @param year the new year value to set
* @return {@link AlbumPage}
@@ -121,7 +119,7 @@ public AlbumPage changeAlbumYear(int year) {
/**
- * Sets the album rating input text field
+ * Sets the album rating input text field.
*
* @param albumRating the new album rating value to set
* @return {@link AlbumPage}
@@ -133,20 +131,21 @@ public AlbumPage changeAlbumRating(String albumRating) {
}
/**
- * Sets the number of songs number input field
+ * Sets the number of songs number input field.
*
* @param numberOfSongs the new number of songs value to be set
* @return {@link AlbumPage}
*/
public AlbumPage changeNumberOfSongs(int numberOfSongs) {
- HtmlNumberInput numberOfSongsNumberField = (HtmlNumberInput) page.getElementById("numberOfSongs");
+ HtmlNumberInput numberOfSongsNumberField =
+ (HtmlNumberInput) page.getElementById("numberOfSongs");
numberOfSongsNumberField.setText(Integer.toString(numberOfSongs));
return this;
}
/**
- * Cancel changes made by clicking the cancel button
+ * Cancel changes made by clicking the cancel button.
*
* @return {@link AlbumListPage}
*/
@@ -162,7 +161,7 @@ public AlbumListPage cancelChanges() {
/**
- * Saves changes made by clicking the save button
+ * Saves changes made by clicking the save button.
*
* @return {@link AlbumPage}
*/
diff --git a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/LoginPage.java b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/LoginPage.java
index b139253a77fa..78d3fa329ab5 100644
--- a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/LoginPage.java
+++ b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/LoginPage.java
@@ -29,7 +29,6 @@
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import java.io.IOException;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -45,7 +44,7 @@ public class LoginPage extends Page {
private HtmlPage page;
/**
- * Constructor
+ * Constructor.
*
* @param webClient {@link WebClient}
*/
@@ -54,7 +53,7 @@ public LoginPage(WebClient webClient) {
}
/**
- * Navigates to the Login page
+ * Navigates to the Login page.
*
* @return {@link LoginPage}
*/
@@ -77,7 +76,7 @@ public boolean isAt() {
/**
- * Enters the username into the username input text field
+ * Enters the username into the username input text field.
*
* @param username the username to enter
* @return {@link LoginPage}
@@ -90,23 +89,24 @@ public LoginPage enterUsername(String username) {
/**
- * Enters the password into the password input password field
+ * Enters the password into the password input password field.
*
* @param password the password to enter
* @return {@link LoginPage}
*/
public LoginPage enterPassword(String password) {
- HtmlPasswordInput passwordInputPasswordField = (HtmlPasswordInput) page.getElementById("password");
+ HtmlPasswordInput passwordInputPasswordField =
+ (HtmlPasswordInput) page.getElementById("password");
passwordInputPasswordField.setText(password);
return this;
}
/**
- * Clicking on the login button to 'login'
+ * Clicking on the login button to 'login'.
*
- * @return {@link AlbumListPage}
- * - this is the page that user gets navigated to once successfully logged in
+ * @return {@link AlbumListPage} - this is the page that user gets navigated to once successfully
+ * logged in
*/
public AlbumListPage login() {
HtmlSubmitInput loginButton = (HtmlSubmitInput) page.getElementById("loginButton");
diff --git a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/Page.java b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/Page.java
index 78bc4618c407..ddf7ec63ed54 100644
--- a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/Page.java
+++ b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/Page.java
@@ -26,20 +26,19 @@
import com.gargoylesoftware.htmlunit.WebClient;
/**
- * Encapsulation for a generic 'Page'
+ * Encapsulation for a generic 'Page'.
*/
public abstract class Page {
/**
- * Application Under Test path
- * This directory location is where html web pages are located
+ * Application Under Test path This directory location is where html web pages are located.
*/
public static final String AUT_PATH = "../sample-application/src/main/resources/sample-ui/";
protected final WebClient webClient;
/**
- * Constructor
+ * Constructor.
*
* @param webClient {@link WebClient}
*/
@@ -48,7 +47,7 @@ public Page(WebClient webClient) {
}
/**
- * Checks that the current page is actually the page this page object represents
+ * Checks that the current page is actually the page this page object represents.
*
* @return true if so, otherwise false
*/
diff --git a/partial-response/pom.xml b/partial-response/pom.xml
index bef921f0583a..6bca7007329d 100644
--- a/partial-response/pom.xml
+++ b/partial-response/pom.xml
@@ -29,7 +29,7 @@
java-design-patternscom.iluwatar
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOT4.0.0
diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/App.java b/partial-response/src/main/java/com/iluwatar/partialresponse/App.java
index 314846a3dbe5..5a3e7d950e0d 100644
--- a/partial-response/src/main/java/com/iluwatar/partialresponse/App.java
+++ b/partial-response/src/main/java/com/iluwatar/partialresponse/App.java
@@ -23,18 +23,16 @@
package com.iluwatar.partialresponse;
+import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Map;
-
/**
- * The Partial response pattern is a design pattern in which client specifies fields to fetch to serve.
- * Here {@link App} is playing as client for {@link VideoResource} server.
- * Client ask for specific fields information in video to server.
- *
- *
- * {@link VideoResource} act as server to serve video information.
+ * The Partial response pattern is a design pattern in which client specifies fields to fetch to
+ * serve. Here {@link App} is playing as client for {@link VideoResource} server. Client ask for
+ * specific fields information in video to server.
+ *
+ *
{@link VideoResource} act as server to serve video information.
*/
public class App {
@@ -47,12 +45,12 @@ public class App {
*/
public static void main(String[] args) throws Exception {
Map videos = Map.of(
- 1, new Video(1, "Avatar", 178, "epic science fiction film",
- "James Cameron", "English"),
- 2, new Video(2, "Godzilla Resurgence", 120, "Action & drama movie|",
- "Hideaki Anno", "Japanese"),
- 3, new Video(3, "Interstellar", 169, "Adventure & Sci-Fi",
- "Christopher Nolan", "English"));
+ 1, new Video(1, "Avatar", 178, "epic science fiction film",
+ "James Cameron", "English"),
+ 2, new Video(2, "Godzilla Resurgence", 120, "Action & drama movie|",
+ "Hideaki Anno", "Japanese"),
+ 3, new Video(3, "Interstellar", 169, "Adventure & Sci-Fi",
+ "Christopher Nolan", "English"));
VideoResource videoResource = new VideoResource(new FieldJsonMapper(), videos);
diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java b/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java
index da1d22620c31..f735b4d2b847 100644
--- a/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java
+++ b/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java
@@ -26,11 +26,13 @@
import java.lang.reflect.Field;
/**
- * Map a video to json
+ * Map a video to json.
*/
public class FieldJsonMapper {
/**
+ * Gets json of required fields from video.
+ *
* @param video object containing video information
* @param fields fields information to get
* @return json of required fields from video
diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/Video.java b/partial-response/src/main/java/com/iluwatar/partialresponse/Video.java
index fcfda7497f95..9e3ad5ea3ccb 100644
--- a/partial-response/src/main/java/com/iluwatar/partialresponse/Video.java
+++ b/partial-response/src/main/java/com/iluwatar/partialresponse/Video.java
@@ -24,8 +24,7 @@
package com.iluwatar.partialresponse;
/**
- * {@link Video} is a entity to serve from server.It contains all video related information..
- *
+ * {@link Video} is a entity to serve from server.It contains all video related information.
*/
public class Video {
private final Integer id;
@@ -36,23 +35,27 @@ public class Video {
private final String language;
/**
- * @param id video unique id
- * @param title video title
- * @param length video length in minutes
- * @param description video description by publisher
- * @param director video director name
- * @param language video language {private, public}
+ * Constructor.
+ *
+ * @param id video unique id
+ * @param title video title
+ * @param len video length in minutes
+ * @param desc video description by publisher
+ * @param director video director name
+ * @param lang video language {private, public}
*/
- public Video(Integer id, String title, Integer length, String description, String director, String language) {
+ public Video(Integer id, String title, Integer len, String desc, String director, String lang) {
this.id = id;
this.title = title;
- this.length = length;
- this.description = description;
+ this.length = len;
+ this.description = desc;
this.director = director;
- this.language = language;
+ this.language = lang;
}
/**
+ * ToString.
+ *
* @return json representaion of video
*/
@Override
diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java b/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java
index d0d77af05151..a61a3c429e8a 100644
--- a/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java
+++ b/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java
@@ -26,14 +26,16 @@
import java.util.Map;
/**
- * The resource class which serves video information.
- * This class act as server in the demo. Which has all video details.
+ * The resource class which serves video information. This class act as server in the demo. Which
+ * has all video details.
*/
public class VideoResource {
private FieldJsonMapper fieldJsonMapper;
private Map videos;
/**
+ * Constructor.
+ *
* @param fieldJsonMapper map object to json.
* @param videos initialize resource with existing videos. Act as database.
*/
@@ -43,6 +45,8 @@ public VideoResource(FieldJsonMapper fieldJsonMapper, Map videos
}
/**
+ * Get Details.
+ *
* @param id video id
* @param fields fields to get information about
* @return full response if no fields specified else partial response for given field.
diff --git a/pipeline/pom.xml b/pipeline/pom.xml
index f67e6ad2df16..e7d879d4a5ce 100644
--- a/pipeline/pom.xml
+++ b/pipeline/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTpipeline
diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/App.java b/pipeline/src/main/java/com/iluwatar/pipeline/App.java
index 3298a6eb69b2..1b1e443e6456 100644
--- a/pipeline/src/main/java/com/iluwatar/pipeline/App.java
+++ b/pipeline/src/main/java/com/iluwatar/pipeline/App.java
@@ -24,21 +24,20 @@
package com.iluwatar.pipeline;
/**
- * The Pipeline pattern uses ordered stages to process a sequence of input values.
- * Each implemented task is represented by a stage of the pipeline. You can think of
- * pipelines as similar to assembly lines in a factory, where each item in the assembly
- * line is constructed in stages. The partially assembled item is passed from one assembly
- * stage to another. The outputs of the assembly line occur in the same order as that of the
- * inputs.
+ * The Pipeline pattern uses ordered stages to process a sequence of input values. Each implemented
+ * task is represented by a stage of the pipeline. You can think of pipelines as similar to assembly
+ * lines in a factory, where each item in the assembly line is constructed in stages. The partially
+ * assembled item is passed from one assembly stage to another. The outputs of the assembly line
+ * occur in the same order as that of the inputs.
*
- * Classes used in this example are suffixed with "Handlers", and synonymously refers to the
+ *
Classes used in this example are suffixed with "Handlers", and synonymously refers to the
* "stage".
*/
public class App {
/**
- * Specify the initial input type for the first stage handler and the expected output type
- * of the last stage handler as type parameters for Pipeline. Use the fluent builder by
- * calling addHandler to add more stage handlers on the pipeline.
+ * Specify the initial input type for the first stage handler and the expected output type of the
+ * last stage handler as type parameters for Pipeline. Use the fluent builder by calling
+ * addHandler to add more stage handlers on the pipeline.
*/
public static void main(String[] args) {
/*
diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java b/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java
index 104d81f40b88..365fc1cdc2e4 100644
--- a/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java
+++ b/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java
@@ -23,11 +23,10 @@
package com.iluwatar.pipeline;
+import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Arrays;
-
/**
* Stage handler that converts an input String to its char[] array counterpart.
*/
@@ -38,8 +37,10 @@ class ConvertToCharArrayHandler implements Handler {
@Override
public char[] process(String input) {
char[] characters = input.toCharArray();
- LOGGER.info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s",
- ConvertToCharArrayHandler.class, input, String.class, Arrays.toString(characters), Character[].class));
+ LOGGER
+ .info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s",
+ ConvertToCharArrayHandler.class, input, String.class, Arrays
+ .toString(characters), Character[].class));
return characters;
}
diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/Handler.java b/pipeline/src/main/java/com/iluwatar/pipeline/Handler.java
index 253bc22f5607..5591632e08ba 100644
--- a/pipeline/src/main/java/com/iluwatar/pipeline/Handler.java
+++ b/pipeline/src/main/java/com/iluwatar/pipeline/Handler.java
@@ -24,7 +24,9 @@
package com.iluwatar.pipeline;
/**
- * Forms a contract to all stage handlers to accept a certain type of input and return a processed output.
+ * Forms a contract to all stage handlers to accept a certain type of input and return a processed
+ * output.
+ *
* @param the input type of the handler
* @param the processed output type of the handler
*/
diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/Pipeline.java b/pipeline/src/main/java/com/iluwatar/pipeline/Pipeline.java
index af5c69b1d77c..81b63e6cfdcf 100644
--- a/pipeline/src/main/java/com/iluwatar/pipeline/Pipeline.java
+++ b/pipeline/src/main/java/com/iluwatar/pipeline/Pipeline.java
@@ -24,8 +24,9 @@
package com.iluwatar.pipeline;
/**
- * Main Pipeline class that initially sets the current handler. Processed output
- * of the initial handler is then passed as the input to the next stage handlers.
+ * Main Pipeline class that initially sets the current handler. Processed output of the initial
+ * handler is then passed as the input to the next stage handlers.
+ *
* @param the type of the input for the first stage handler
* @param the final stage handler's output type
*/
diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java
index 930332671c3d..b2ed938cf100 100644
--- a/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java
+++ b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java
@@ -27,7 +27,8 @@
import org.slf4j.LoggerFactory;
/**
- * Stage handler that returns a new instance of String without the alphabet characters of the input string.
+ * Stage handler that returns a new instance of String without the alphabet characters of the input
+ * string.
*/
class RemoveAlphabetsHandler implements Handler {
@@ -47,8 +48,13 @@ public String process(String input) {
}
String inputWithoutAlphabetsStr = inputWithoutAlphabets.toString();
- LOGGER.info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s",
- RemoveAlphabetsHandler.class, input, String.class, inputWithoutAlphabetsStr, String.class));
+ LOGGER.info(
+ String.format(
+ "Current handler: %s, input is %s of type %s, output is %s, of type %s",
+ RemoveAlphabetsHandler.class, input,
+ String.class, inputWithoutAlphabetsStr, String.class
+ )
+ );
return inputWithoutAlphabetsStr;
}
diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java
index 6fd591006c55..450bef7177ea 100644
--- a/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java
+++ b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java
@@ -27,7 +27,8 @@
import org.slf4j.LoggerFactory;
/**
- * Stage handler that returns a new instance of String without the digit characters of the input string.
+ * Stage handler that returns a new instance of String without the digit characters of the input
+ * string.
*/
class RemoveDigitsHandler implements Handler {
@@ -47,8 +48,9 @@ public String process(String input) {
}
String inputWithoutDigitsStr = inputWithoutDigits.toString();
- LOGGER.info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s",
- RemoveDigitsHandler.class, input, String.class, inputWithoutDigitsStr, String.class));
+ LOGGER
+ .info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s",
+ RemoveDigitsHandler.class, input, String.class, inputWithoutDigitsStr, String.class));
return inputWithoutDigitsStr;
}
diff --git a/poison-pill/pom.xml b/poison-pill/pom.xml
index b10b54c008ff..b751fad04837 100644
--- a/poison-pill/pom.xml
+++ b/poison-pill/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTpoison-pill
diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java
index 6d6a41eb9970..7fdf71a09b3b 100644
--- a/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java
+++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java
@@ -30,16 +30,15 @@
* Pill will stop reading messages from the queue. You must also ensure that the Poison Pill will be
* the last message that will be read from the queue (if you have prioritized queue then this can be
* tricky).
- *
- * In simple cases the Poison Pill can be just a null-reference, but holding a unique separate
+ *
+ *
In simple cases the Poison Pill can be just a null-reference, but holding a unique separate
* shared object-marker (with name "Poison" or "Poison Pill") is more clear and self describing.
- *
*/
public class App {
/**
- * Program entry point
- *
+ * Program entry point.
+ *
* @param args command line args
*/
public static void main(String[] args) {
diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java
index 12cc246d8d28..25d2338e1226 100644
--- a/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java
+++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java
@@ -28,10 +28,10 @@
import org.slf4j.LoggerFactory;
/**
- * Class responsible for receiving and handling submitted to the queue messages
+ * Class responsible for receiving and handling submitted to the queue messages.
*/
public class Consumer {
-
+
private static final Logger LOGGER = LoggerFactory.getLogger(Consumer.class);
private final MqSubscribePoint queue;
@@ -43,7 +43,7 @@ public Consumer(String name, MqSubscribePoint queue) {
}
/**
- * Consume message
+ * Consume message.
*/
public void consume() {
while (true) {
diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/Message.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/Message.java
index 9b35bf53a569..b0298e4077cb 100644
--- a/poison-pill/src/main/java/com/iluwatar/poison/pill/Message.java
+++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/Message.java
@@ -65,7 +65,7 @@ private RuntimeException poison() {
};
/**
- * Enumeration of Type of Headers
+ * Enumeration of Type of Headers.
*/
enum Headers {
DATE, SENDER
diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/MessageQueue.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/MessageQueue.java
index ce8005fcebaf..2928e172d5d4 100644
--- a/poison-pill/src/main/java/com/iluwatar/poison/pill/MessageQueue.java
+++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/MessageQueue.java
@@ -24,7 +24,7 @@
package com.iluwatar.poison.pill;
/**
- * Represents abstraction of channel (or pipe) that bounds {@link Producer} and {@link Consumer}
+ * Represents abstraction of channel (or pipe) that bounds {@link Producer} and {@link Consumer}.
*/
public interface MessageQueue extends MqPublishPoint, MqSubscribePoint {
diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/MqPublishPoint.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/MqPublishPoint.java
index b0e086637509..f61a579872a4 100644
--- a/poison-pill/src/main/java/com/iluwatar/poison/pill/MqPublishPoint.java
+++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/MqPublishPoint.java
@@ -24,7 +24,7 @@
package com.iluwatar.poison.pill;
/**
- * Endpoint to publish {@link Message} to queue
+ * Endpoint to publish {@link Message} to queue.
*/
public interface MqPublishPoint {
diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/MqSubscribePoint.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/MqSubscribePoint.java
index bb01e6395f14..b7133de8c845 100644
--- a/poison-pill/src/main/java/com/iluwatar/poison/pill/MqSubscribePoint.java
+++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/MqSubscribePoint.java
@@ -24,7 +24,7 @@
package com.iluwatar.poison.pill;
/**
- * Endpoint to retrieve {@link Message} from queue
+ * Endpoint to retrieve {@link Message} from queue.
*/
public interface MqSubscribePoint {
diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java
index 0b746b31f3e7..679500e43317 100644
--- a/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java
+++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java
@@ -23,15 +23,14 @@
package com.iluwatar.poison.pill;
-import java.util.Date;
-
import com.iluwatar.poison.pill.Message.Headers;
+import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class responsible for producing unit of work that can be expressed as message and submitted to
- * queue
+ * queue.
*/
public class Producer {
@@ -42,7 +41,7 @@ public class Producer {
private boolean isStopped;
/**
- * Constructor
+ * Constructor.
*/
public Producer(String name, MqPublishPoint queue) {
this.name = name;
@@ -51,7 +50,7 @@ public Producer(String name, MqPublishPoint queue) {
}
/**
- * Send message to queue
+ * Send message to queue.
*/
public void send(String body) {
if (isStopped) {
@@ -72,7 +71,7 @@ public void send(String body) {
}
/**
- * Stop system by sending poison pill
+ * Stop system by sending poison pill.
*/
public void stop() {
isStopped = true;
diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java
index efc45fc83bef..8a7af515f7e8 100644
--- a/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java
+++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java
@@ -28,7 +28,7 @@
import java.util.Map;
/**
- * {@link Message} basic implementation
+ * {@link Message} basic implementation.
*/
public class SimpleMessage implements Message {
diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessageQueue.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessageQueue.java
index 7f1b662cde71..f6a50d4ff030 100644
--- a/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessageQueue.java
+++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessageQueue.java
@@ -27,7 +27,7 @@
import java.util.concurrent.BlockingQueue;
/**
- * Bounded blocking queue wrapper
+ * Bounded blocking queue wrapper.
*/
public class SimpleMessageQueue implements MessageQueue {
diff --git a/pom.xml b/pom.xml
index 1ab896068a6b..39582fd93718 100644
--- a/pom.xml
+++ b/pom.xml
@@ -28,7 +28,7 @@
4.0.0com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTpom2014-2019
@@ -187,6 +187,7 @@
sagadouble-buffersharding
+ game-loop
@@ -384,9 +385,6 @@
-
org.apache.maven.pluginsmaven-checkstyle-plugin
@@ -403,7 +401,8 @@
checkstyle-suppressions.xmlUTF-8true
- true
+ warning
+ false
diff --git a/priority-queue/pom.xml b/priority-queue/pom.xml
index 3e5ac50e81ab..3ba564b55583 100644
--- a/priority-queue/pom.xml
+++ b/priority-queue/pom.xml
@@ -31,7 +31,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOT
diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/Application.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/Application.java
index 1e6e44a68564..e803489b28d2 100644
--- a/priority-queue/src/main/java/com/iluwatar/priority/queue/Application.java
+++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/Application.java
@@ -25,16 +25,15 @@
/**
* Prioritize requests sent to services so that requests with a higher priority are received and
- * processed more quickly than those of a lower priority.
- * This pattern is useful in applications that offer different service level guarantees
- * to individual clients.
- * Example :Send multiple message with different priority to worker queue.
- * Worker execute higher priority message first
+ * processed more quickly than those of a lower priority. This pattern is useful in applications
+ * that offer different service level guarantees to individual clients. Example :Send multiple
+ * message with different priority to worker queue. Worker execute higher priority message first
+ *
* @see "https://docs.microsoft.com/en-us/previous-versions/msp-n-p/dn589794(v=pandp.10)"
*/
public class Application {
/**
- * main entry
+ * main entry.
*/
public static void main(String[] args) throws Exception {
diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/Message.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/Message.java
index b874bd677915..a9a3dcfa630c 100644
--- a/priority-queue/src/main/java/com/iluwatar/priority/queue/Message.java
+++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/Message.java
@@ -24,7 +24,7 @@
package com.iluwatar.priority.queue;
/**
- * Message bean
+ * Message bean.
*/
public class Message implements Comparable {
private final String message;
diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/PriorityMessageQueue.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/PriorityMessageQueue.java
index ff73a496ff58..66f4d4f591f6 100644
--- a/priority-queue/src/main/java/com/iluwatar/priority/queue/PriorityMessageQueue.java
+++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/PriorityMessageQueue.java
@@ -23,11 +23,11 @@
package com.iluwatar.priority.queue;
+import static java.util.Arrays.copyOf;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import static java.util.Arrays.copyOf;
-
/**
* Keep high Priority message on top using maxHeap.
*
@@ -50,14 +50,14 @@ public PriorityMessageQueue(T[] queue) {
}
/**
- * Remove top message from queue
+ * Remove top message from queue.
*/
public T remove() {
if (isEmpty()) {
return null;
}
- T root = queue[0];
+ final T root = queue[0];
queue[0] = queue[size - 1];
size--;
maxHeapifyDown();
@@ -65,7 +65,7 @@ public T remove() {
}
/**
- * Add message to queue
+ * Add message to queue.
*/
public void add(T t) {
ensureCapacity();
@@ -75,7 +75,7 @@ public void add(T t) {
}
/**
- * Check queue size
+ * Check queue size.
*/
public boolean isEmpty() {
return size == 0;
diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/QueueManager.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/QueueManager.java
index ade211766c3d..7eca0aca6d3d 100644
--- a/priority-queue/src/main/java/com/iluwatar/priority/queue/QueueManager.java
+++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/QueueManager.java
@@ -24,7 +24,7 @@
package com.iluwatar.priority.queue;
/**
- * Manage priority queue
+ * Manage priority queue.
*/
public class QueueManager {
/*
@@ -37,7 +37,7 @@ public QueueManager(int initialCapacity) {
}
/**
- * Publish message to queue
+ * Publish message to queue.
*/
public void publishMessage(Message message) {
messagePriorityMessageQueue.add(message);
@@ -45,7 +45,7 @@ public void publishMessage(Message message) {
/**
- * recive message from queue
+ * recive message from queue.
*/
public Message receiveMessage() {
if (messagePriorityMessageQueue.isEmpty()) {
diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/Worker.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/Worker.java
index bbeb64b73a7e..18ed16199584 100644
--- a/priority-queue/src/main/java/com/iluwatar/priority/queue/Worker.java
+++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/Worker.java
@@ -27,7 +27,7 @@
import org.slf4j.LoggerFactory;
/**
- * Message Worker
+ * Message Worker.
*/
public class Worker {
@@ -40,7 +40,7 @@ public Worker(QueueManager queueManager) {
}
/**
- * Keep checking queue for message
+ * Keep checking queue for message.
*/
@SuppressWarnings("squid:S2189")
public void run() throws Exception {
@@ -56,7 +56,7 @@ public void run() throws Exception {
}
/**
- * Process message
+ * Process message.
*/
private void processMessage(Message message) {
LOGGER.info(message.toString());
diff --git a/private-class-data/pom.xml b/private-class-data/pom.xml
index da9b510542c6..ecc2933d9ef7 100644
--- a/private-class-data/pom.xml
+++ b/private-class-data/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTprivate-class-data
diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/App.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/App.java
index c5b75eee4a78..367baaf8b86c 100644
--- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/App.java
+++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/App.java
@@ -24,26 +24,24 @@
package com.iluwatar.privateclassdata;
/**
- *
* The Private Class Data design pattern seeks to reduce exposure of attributes by limiting their
* visibility. It reduces the number of class attributes by encapsulating them in single data
* object. It allows the class designer to remove write privilege of attributes that are intended to
* be set only during construction, even from methods of the target class.
- *
- * In the example we have normal {@link Stew} class with some ingredients given in constructor. Then
- * we have methods to enumerate the ingredients and to taste the stew. The method for tasting the
- * stew alters the private members of the {@link Stew} class.
- *
- * The problem is solved with the Private Class Data pattern. We introduce {@link ImmutableStew}
- * class that contains {@link StewData}. The private data members of {@link Stew} are now in
- * {@link StewData} and cannot be altered by {@link ImmutableStew} methods.
*
+ *
In the example we have normal {@link Stew} class with some ingredients given in constructor.
+ * Then we have methods to enumerate the ingredients and to taste the stew. The method for tasting
+ * the stew alters the private members of the {@link Stew} class.
+ *
+ *
The problem is solved with the Private Class Data pattern. We introduce {@link ImmutableStew}
+ * class that contains {@link StewData}. The private data members of {@link Stew} are now in {@link
+ * StewData} and cannot be altered by {@link ImmutableStew} methods.
*/
public class App {
/**
- * Program entry point
- *
+ * Program entry point.
+ *
* @param args command line args
*/
public static void main(String[] args) {
diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java
index 627d744620bd..695424695822 100644
--- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java
+++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java
@@ -27,9 +27,7 @@
import org.slf4j.LoggerFactory;
/**
- *
- * Immutable stew class, protected with Private Class Data pattern
- *
+ * Immutable stew class, protected with Private Class Data pattern.
*/
public class ImmutableStew {
@@ -42,10 +40,11 @@ public ImmutableStew(int numPotatoes, int numCarrots, int numMeat, int numPepper
}
/**
- * Mix the stew
+ * Mix the stew.
*/
public void mix() {
- LOGGER.info("Mixing the immutable stew we find: {} potatoes, {} carrots, {} meat and {} peppers",
- data.getNumPotatoes(), data.getNumCarrots(), data.getNumMeat(), data.getNumPeppers());
+ LOGGER
+ .info("Mixing the immutable stew we find: {} potatoes, {} carrots, {} meat and {} peppers",
+ data.getNumPotatoes(), data.getNumCarrots(), data.getNumMeat(), data.getNumPeppers());
}
}
diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java
index 6618ee5dac95..65ba6c08e568 100644
--- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java
+++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java
@@ -27,9 +27,7 @@
import org.slf4j.LoggerFactory;
/**
- *
- * Mutable stew class
- *
+ * Mutable stew class.
*/
public class Stew {
@@ -41,7 +39,7 @@ public class Stew {
private int numPeppers;
/**
- * Constructor
+ * Constructor.
*/
public Stew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
this.numPotatoes = numPotatoes;
@@ -51,7 +49,7 @@ public Stew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
}
/**
- * Mix the stew
+ * Mix the stew.
*/
public void mix() {
LOGGER.info("Mixing the stew we find: {} potatoes, {} carrots, {} meat and {} peppers",
@@ -59,7 +57,7 @@ public void mix() {
}
/**
- * Taste the stew
+ * Taste the stew.
*/
public void taste() {
LOGGER.info("Tasting the stew");
diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java
index c170a531ef1a..bcdaba3e9ce9 100644
--- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java
+++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java
@@ -24,9 +24,7 @@
package com.iluwatar.privateclassdata;
/**
- *
- * Stew ingredients
- *
+ * Stew ingredients.
*/
public class StewData {
@@ -36,7 +34,7 @@ public class StewData {
private int numPeppers;
/**
- * Constructor
+ * Constructor.
*/
public StewData(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
this.numPotatoes = numPotatoes;
diff --git a/producer-consumer/pom.xml b/producer-consumer/pom.xml
index 1cbf039103ca..479bd321aed2 100644
--- a/producer-consumer/pom.xml
+++ b/producer-consumer/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTproducer-consumer
diff --git a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/App.java b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/App.java
index 853c6fcfe51d..0ead44307b7d 100644
--- a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/App.java
+++ b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/App.java
@@ -23,20 +23,22 @@
package com.iluwatar.producer.consumer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
/**
- * Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces coupling between
- * Producer and Consumer by separating Identification of work with Execution of Work.
- *
- * In producer consumer design pattern a shared queue is used to control the flow and this separation allows you to code
- * producer and consumer separately. It also addresses the issue of different timing require to produce item or
- * consuming item. by using producer consumer pattern both Producer and Consumer Thread can work with different speed.
+ * Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces
+ * coupling between Producer and Consumer by separating Identification of work with
+ * Execution of Work.
+ *
+ *
In producer consumer design pattern a shared queue is used to control the flow and this
+ * separation allows you to code producer and consumer separately. It also addresses the issue
+ * of different timing require to produce item or consuming item. by using producer consumer
+ * pattern both Producer and Consumer Thread can work with different speed.
*
*/
public class App {
@@ -44,7 +46,7 @@ public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/**
- * Program entry point
+ * Program entry point.
*
* @param args
* command line args
diff --git a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java
index 3e4e9aadb3d9..5598f3e45dca 100644
--- a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java
+++ b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java
@@ -27,7 +27,7 @@
import org.slf4j.LoggerFactory;
/**
- * Class responsible for consume the {@link Item} produced by {@link Producer}
+ * Class responsible for consume the {@link Item} produced by {@link Producer}.
*/
public class Consumer {
@@ -43,12 +43,13 @@ public Consumer(String name, ItemQueue queue) {
}
/**
- * Consume item from the queue
+ * Consume item from the queue.
*/
public void consume() throws InterruptedException {
Item item = queue.take();
- LOGGER.info("Consumer [{}] consume item [{}] produced by [{}]", name, item.getId(), item.getProducer());
+ LOGGER.info("Consumer [{}] consume item [{}] produced by [{}]", name,
+ item.getId(), item.getProducer());
}
}
diff --git a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java
index e8c79afd4836..6d4ca0096d6d 100644
--- a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java
+++ b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java
@@ -27,7 +27,7 @@
/**
* Class responsible for producing unit of work that can be expressed as {@link Item} and submitted
- * to queue
+ * to queue.
*/
public class Producer {
@@ -45,7 +45,7 @@ public Producer(String name, ItemQueue queue) {
}
/**
- * Put item in the queue
+ * Put item in the queue.
*/
public void produce() throws InterruptedException {
diff --git a/promise/pom.xml b/promise/pom.xml
index 6ee49075766b..369e95748a87 100644
--- a/promise/pom.xml
+++ b/promise/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTpromise
diff --git a/promise/src/main/java/com/iluwatar/promise/App.java b/promise/src/main/java/com/iluwatar/promise/App.java
index c201d33526c2..c016b67ff0b5 100644
--- a/promise/src/main/java/com/iluwatar/promise/App.java
+++ b/promise/src/main/java/com/iluwatar/promise/App.java
@@ -22,8 +22,6 @@
*/
package com.iluwatar.promise;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
@@ -32,10 +30,12 @@
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
/**
- *
- * The Promise object is used for asynchronous computations. A Promise represents an operation
- * that hasn't completed yet, but is expected in the future.
+ * The Promise object is used for asynchronous computations. A Promise represents an operation
+ * that hasn't completed yet, but is expected in the future.
*
*
A Promise represents a proxy for a value not necessarily known when the promise is created. It
* allows you to associate dependent promises to an asynchronous action's eventual success value or
@@ -49,15 +49,14 @@
*
- * In this application the usage of promise is demonstrated with two examples:
+ *
In this application the usage of promise is demonstrated with two examples:
*
*
Count Lines: In this example a file is downloaded and its line count is calculated.
* The calculated line count is then consumed and printed on console.
*
Lowest Character Frequency: In this example a file is downloaded and its lowest frequency
* character is found and printed on console. This happens via a chain of promises, we start with
- * a file download promise, then a promise of character frequency, then a promise of lowest frequency
- * character which is finally consumed and result is printed on console.
+ * a file download promise, then a promise of character frequency, then a promise of lowest
+ * frequency character which is finally consumed and result is printed on console.
*
*
* @see CompletableFuture
@@ -76,7 +75,7 @@ private App() {
}
/**
- * Program entry point
+ * Program entry point.
* @param args arguments
* @throws InterruptedException if main thread is interrupted.
* @throws ExecutionException if an execution error occurs.
diff --git a/promise/src/main/java/com/iluwatar/promise/Utility.java b/promise/src/main/java/com/iluwatar/promise/Utility.java
index 472f7b0a5234..09c7f6ddc7b3 100644
--- a/promise/src/main/java/com/iluwatar/promise/Utility.java
+++ b/promise/src/main/java/com/iluwatar/promise/Utility.java
@@ -23,9 +23,6 @@
package com.iluwatar.promise;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
@@ -39,8 +36,11 @@
import java.util.Map;
import java.util.Map.Entry;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
/**
- * Utility to perform various operations
+ * Utility to perform various operations.
*/
public class Utility {
@@ -71,7 +71,8 @@ public static Map characterFrequency(String fileLocation) {
}
/**
- * @return the character with lowest frequency if it exists, {@code Optional.empty()} otherwise.
+ * Return the character with the lowest frequency, if exists.
+ * @return the character, {@code Optional.empty()} otherwise.
*/
public static Character lowestFrequencyChar(Map charFrequency) {
Character lowestFrequencyChar = null;
@@ -92,7 +93,8 @@ public static Character lowestFrequencyChar(Map charFrequenc
}
/**
- * @return number of lines in the file at provided location. 0 if file does not exist.
+ * Count the number of lines in a file.
+ * @return number of lines, 0 if file does not exist.
*/
public static Integer countLines(String fileLocation) {
int lineCount = 0;
diff --git a/property/pom.xml b/property/pom.xml
index b04242256f0f..4e1a16a0d9f4 100644
--- a/property/pom.xml
+++ b/property/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTproperty
diff --git a/property/src/main/java/com/iluwatar/property/App.java b/property/src/main/java/com/iluwatar/property/App.java
index a7045e6df6db..d37dd5fd7deb 100644
--- a/property/src/main/java/com/iluwatar/property/App.java
+++ b/property/src/main/java/com/iluwatar/property/App.java
@@ -28,25 +28,23 @@
import org.slf4j.LoggerFactory;
/**
- *
* The Property pattern is also known as Prototype inheritance.
- *
- * In prototype inheritance instead of classes, as opposite to Java class inheritance, objects are
- * used to create another objects and object hierarchies. Hierarchies are created using prototype
- * chain through delegation: every object has link to parent object. Any base (parent) object can be
- * amended at runtime (by adding or removal of some property), and all child objects will be
- * affected as result.
- *
- * In this example we demonstrate {@link Character} instantiation using the Property pattern.
- *
+ *
+ *
In prototype inheritance instead of classes, as opposite to Java class inheritance, objects
+ * are used to create another objects and object hierarchies. Hierarchies are created using
+ * prototype chain through delegation: every object has link to parent object. Any base (parent)
+ * object can be amended at runtime (by adding or removal of some property), and all child objects
+ * will be affected as result.
+ *
+ *
In this example we demonstrate {@link Character} instantiation using the Property pattern.
*/
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/**
- * Program entry point
- *
+ * Program entry point.
+ *
* @param args command line args
*/
public static void main(String[] args) {
diff --git a/property/src/main/java/com/iluwatar/property/Character.java b/property/src/main/java/com/iluwatar/property/Character.java
index ef19f01072e6..bbe7014599f2 100644
--- a/property/src/main/java/com/iluwatar/property/Character.java
+++ b/property/src/main/java/com/iluwatar/property/Character.java
@@ -32,7 +32,7 @@
public class Character implements Prototype {
/**
- * Enumeration of Character types
+ * Enumeration of Character types.
*/
public enum Type {
WARRIOR, MAGE, ROGUE
@@ -45,26 +45,28 @@ public enum Type {
private Type type;
/**
- * Constructor
+ * Constructor.
*/
public Character() {
this.prototype = new Prototype() { // Null-value object
- @Override
- public Integer get(Stats stat) {
- return null;
- }
-
- @Override
- public boolean has(Stats stat) {
- return false;
- }
-
- @Override
- public void set(Stats stat, Integer val) {}
-
- @Override
- public void remove(Stats stat) {}
- };
+ @Override
+ public Integer get(Stats stat) {
+ return null;
+ }
+
+ @Override
+ public boolean has(Stats stat) {
+ return false;
+ }
+
+ @Override
+ public void set(Stats stat, Integer val) {
+ }
+
+ @Override
+ public void remove(Stats stat) {
+ }
+ };
}
public Character(Type type, Prototype prototype) {
@@ -73,7 +75,7 @@ public Character(Type type, Prototype prototype) {
}
/**
- * Constructor
+ * Constructor.
*/
public Character(String name, Character prototype) {
this.name = name;
diff --git a/property/src/main/java/com/iluwatar/property/Prototype.java b/property/src/main/java/com/iluwatar/property/Prototype.java
index 9570f66536d8..423863522acd 100644
--- a/property/src/main/java/com/iluwatar/property/Prototype.java
+++ b/property/src/main/java/com/iluwatar/property/Prototype.java
@@ -24,7 +24,7 @@
package com.iluwatar.property;
/**
- * Interface for prototype inheritance
+ * Interface for prototype inheritance.
*/
public interface Prototype {
diff --git a/property/src/main/java/com/iluwatar/property/Stats.java b/property/src/main/java/com/iluwatar/property/Stats.java
index 4015e5693680..2941299d5973 100644
--- a/property/src/main/java/com/iluwatar/property/Stats.java
+++ b/property/src/main/java/com/iluwatar/property/Stats.java
@@ -24,7 +24,7 @@
package com.iluwatar.property;
/**
- * All possible attributes that Character can have
+ * All possible attributes that Character can have.
*/
public enum Stats {
diff --git a/prototype/pom.xml b/prototype/pom.xml
index a715deb79dce..7a8a685cc260 100644
--- a/prototype/pom.xml
+++ b/prototype/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTprototype
diff --git a/prototype/src/main/java/com/iluwatar/prototype/App.java b/prototype/src/main/java/com/iluwatar/prototype/App.java
index 457f4f2a0f5a..9b1d4eb320b3 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/App.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/App.java
@@ -27,41 +27,43 @@
import org.slf4j.LoggerFactory;
/**
- *
* The Prototype pattern is a creational design pattern in software development. It is used when the
* type of objects to create is determined by a prototypical instance, which is cloned to produce
* new objects. This pattern is used to: - avoid subclasses of an object creator in the client
* application, like the abstract factory pattern does. - avoid the inherent cost of creating a new
* object in the standard way (e.g., using the 'new' keyword)
- *
- * In this example we have a factory class ({@link HeroFactoryImpl}) producing objects by cloning
- * the existing ones. The factory's prototype objects are given as constructor parameters.
- *
+ *
+ *
In this example we have a factory class ({@link HeroFactoryImpl}) producing objects by
+ * cloning the existing ones. The factory's prototype objects are given as constructor parameters.
*/
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/**
- * Program entry point
- *
+ * Program entry point.
+ *
* @param args command line args
*/
public static void main(String[] args) {
- HeroFactory factory;
- Mage mage;
- Warlord warlord;
- Beast beast;
-
- factory = new HeroFactoryImpl(new ElfMage("cooking"), new ElfWarlord("cleaning"), new ElfBeast("protecting"));
- mage = factory.createMage();
- warlord = factory.createWarlord();
- beast = factory.createBeast();
+ HeroFactory factory = new HeroFactoryImpl(
+ new ElfMage("cooking"),
+ new ElfWarlord("cleaning"),
+ new ElfBeast("protecting")
+ );
+ Mage mage = factory.createMage();
+ Warlord warlord = factory.createWarlord();
+ Beast beast = factory.createBeast();
LOGGER.info(mage.toString());
LOGGER.info(warlord.toString());
LOGGER.info(beast.toString());
- factory = new HeroFactoryImpl(new OrcMage("axe"), new OrcWarlord("sword"), new OrcBeast("laser"));
+ factory =
+ new HeroFactoryImpl(
+ new OrcMage("axe"),
+ new OrcWarlord("sword"),
+ new OrcBeast("laser")
+ );
mage = factory.createMage();
warlord = factory.createWarlord();
beast = factory.createBeast();
diff --git a/prototype/src/main/java/com/iluwatar/prototype/Beast.java b/prototype/src/main/java/com/iluwatar/prototype/Beast.java
index 3b82cdd9dde1..e3b25b850d19 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/Beast.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/Beast.java
@@ -24,9 +24,7 @@
package com.iluwatar.prototype;
/**
- *
- * Beast
- *
+ * Beast.
*/
public abstract class Beast extends Prototype {
diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java b/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java
index 9ef44b164391..50761964a4ac 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java
@@ -24,12 +24,10 @@
package com.iluwatar.prototype;
/**
- *
- * ElfBeast
- *
+ * ElfBeast.
*/
public class ElfBeast extends Beast {
-
+
private String helpType;
public ElfBeast(String helpType) {
diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java b/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java
index 14b6e6261ba6..014c39bac2e5 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java
@@ -24,15 +24,13 @@
package com.iluwatar.prototype;
/**
- *
- * ElfMage
- *
+ * ElfMage.
*/
public class ElfMage extends Mage {
-
+
private String helpType;
-
+
public ElfMage(String helpType) {
this.helpType = helpType;
}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java b/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java
index 6c5a4a4ffc0a..43cdac7e5747 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java
@@ -24,14 +24,12 @@
package com.iluwatar.prototype;
/**
- *
- * ElfWarlord
- *
+ * ElfWarlord.
*/
public class ElfWarlord extends Warlord {
private String helpType;
-
+
public ElfWarlord(String helpType) {
this.helpType = helpType;
}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/HeroFactory.java b/prototype/src/main/java/com/iluwatar/prototype/HeroFactory.java
index 791671289b4c..2644167971a1 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/HeroFactory.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/HeroFactory.java
@@ -24,9 +24,7 @@
package com.iluwatar.prototype;
/**
- *
* Interface for the factory class.
- *
*/
public interface HeroFactory {
diff --git a/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java b/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java
index 5803ee8efcc6..b9348a3b22b8 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java
@@ -24,9 +24,7 @@
package com.iluwatar.prototype;
/**
- *
* Concrete factory class.
- *
*/
public class HeroFactoryImpl implements HeroFactory {
@@ -35,7 +33,7 @@ public class HeroFactoryImpl implements HeroFactory {
private Beast beast;
/**
- * Constructor
+ * Constructor.
*/
public HeroFactoryImpl(Mage mage, Warlord warlord, Beast beast) {
this.mage = mage;
@@ -44,7 +42,7 @@ public HeroFactoryImpl(Mage mage, Warlord warlord, Beast beast) {
}
/**
- * Create mage
+ * Create mage.
*/
public Mage createMage() {
try {
@@ -55,7 +53,7 @@ public Mage createMage() {
}
/**
- * Create warlord
+ * Create warlord.
*/
public Warlord createWarlord() {
try {
@@ -66,7 +64,7 @@ public Warlord createWarlord() {
}
/**
- * Create beast
+ * Create beast.
*/
public Beast createBeast() {
try {
diff --git a/prototype/src/main/java/com/iluwatar/prototype/Mage.java b/prototype/src/main/java/com/iluwatar/prototype/Mage.java
index 9da5e45baada..27c3bae7a191 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/Mage.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/Mage.java
@@ -24,9 +24,7 @@
package com.iluwatar.prototype;
/**
- *
- * Mage
- *
+ * Mage.
*/
public abstract class Mage extends Prototype {
diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java b/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java
index 2b5fb51599d0..c800b3ac51e6 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java
@@ -24,18 +24,16 @@
package com.iluwatar.prototype;
/**
- *
- * OrcBeast
- *
+ * OrcBeast.
*/
public class OrcBeast extends Beast {
-
+
private String weapon;
public OrcBeast(String weapon) {
this.weapon = weapon;
}
-
+
public OrcBeast(OrcBeast orcBeast) {
this.weapon = orcBeast.weapon;
}
@@ -49,6 +47,6 @@ public Beast copy() {
public String toString() {
return "Orcish wolf attacks with " + weapon;
}
-
+
}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java b/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java
index de15b5e10d91..c71b59d06c54 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java
@@ -24,9 +24,7 @@
package com.iluwatar.prototype;
/**
- *
- * OrcMage
- *
+ * OrcMage.
*/
public class OrcMage extends Mage {
@@ -35,7 +33,7 @@ public class OrcMage extends Mage {
public OrcMage(String weapon) {
this.weapon = weapon;
}
-
+
public OrcMage(OrcMage orcMage) {
this.weapon = orcMage.weapon;
}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java b/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java
index 0b117357fd82..096fd49dc9c0 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java
@@ -24,9 +24,7 @@
package com.iluwatar.prototype;
/**
- *
- * OrcWarlord
- *
+ * OrcWarlord.
*/
public class OrcWarlord extends Warlord {
@@ -35,7 +33,7 @@ public class OrcWarlord extends Warlord {
public OrcWarlord(String weapon) {
this.weapon = weapon;
}
-
+
public OrcWarlord(OrcWarlord orcWarlord) {
this.weapon = orcWarlord.weapon;
}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/Prototype.java b/prototype/src/main/java/com/iluwatar/prototype/Prototype.java
index bae58b026d3e..c74c82f4ad6b 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/Prototype.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/Prototype.java
@@ -24,9 +24,7 @@
package com.iluwatar.prototype;
/**
- *
- * Prototype
- *
+ * Prototype.
*/
public abstract class Prototype implements Cloneable {
diff --git a/prototype/src/main/java/com/iluwatar/prototype/Warlord.java b/prototype/src/main/java/com/iluwatar/prototype/Warlord.java
index 7ce8922e909c..c270ab80bd0d 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/Warlord.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/Warlord.java
@@ -24,9 +24,7 @@
package com.iluwatar.prototype;
/**
- *
- * Warlord
- *
+ * Warlord.
*/
public abstract class Warlord extends Prototype {
diff --git a/proxy/pom.xml b/proxy/pom.xml
index e1df3657a6fa..e08c6ad87b51 100644
--- a/proxy/pom.xml
+++ b/proxy/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTproxy
diff --git a/proxy/src/main/java/com/iluwatar/proxy/App.java b/proxy/src/main/java/com/iluwatar/proxy/App.java
index 4c9d0efaa3f4..ff02a6074fec 100644
--- a/proxy/src/main/java/com/iluwatar/proxy/App.java
+++ b/proxy/src/main/java/com/iluwatar/proxy/App.java
@@ -24,25 +24,23 @@
package com.iluwatar.proxy;
/**
- *
* A proxy, in its most general form, is a class functioning as an interface to something else. The
* proxy could interface to anything: a network connection, a large object in memory, a file, or
* some other resource that is expensive or impossible to duplicate. In short, a proxy is a wrapper
* or agent object that is being called by the client to access the real serving object behind the
* scenes.
- *
- * The Proxy design pattern allows you to provide an interface to other objects by creating a
+ *
+ *
The Proxy design pattern allows you to provide an interface to other objects by creating a
* wrapper class as the proxy. The wrapper class, which is the proxy, can add additional
* functionality to the object of interest without changing the object's code.
- *
- * In this example the proxy ({@link WizardTowerProxy}) controls access to the actual object (
+ *
+ *
In this example the proxy ({@link WizardTowerProxy}) controls access to the actual object (
* {@link IvoryTower}).
- *
*/
public class App {
/**
- * Program entry point
+ * Program entry point.
*/
public static void main(String[] args) {
diff --git a/proxy/src/main/java/com/iluwatar/proxy/IvoryTower.java b/proxy/src/main/java/com/iluwatar/proxy/IvoryTower.java
index 3adb96d86b6c..658b19949080 100644
--- a/proxy/src/main/java/com/iluwatar/proxy/IvoryTower.java
+++ b/proxy/src/main/java/com/iluwatar/proxy/IvoryTower.java
@@ -27,9 +27,7 @@
import org.slf4j.LoggerFactory;
/**
- *
* The object to be proxyed.
- *
*/
public class IvoryTower implements WizardTower {
diff --git a/proxy/src/main/java/com/iluwatar/proxy/Wizard.java b/proxy/src/main/java/com/iluwatar/proxy/Wizard.java
index 031ab8dfd2da..fc77d80df28c 100644
--- a/proxy/src/main/java/com/iluwatar/proxy/Wizard.java
+++ b/proxy/src/main/java/com/iluwatar/proxy/Wizard.java
@@ -24,9 +24,7 @@
package com.iluwatar.proxy;
/**
- *
- * Wizard
- *
+ * Wizard.
*/
public class Wizard {
diff --git a/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java b/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java
index ac83aa6ea54a..c08b49e7dcbb 100644
--- a/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java
+++ b/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java
@@ -24,7 +24,7 @@
package com.iluwatar.proxy;
/**
- * WizardTower interface
+ * WizardTower interface.
*/
public interface WizardTower {
diff --git a/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java b/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java
index 7e6b2acf06d9..e295850de876 100644
--- a/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java
+++ b/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java
@@ -27,9 +27,7 @@
import org.slf4j.LoggerFactory;
/**
- *
* The proxy controlling access to the {@link IvoryTower}.
- *
*/
public class WizardTowerProxy implements WizardTower {
diff --git a/queue-load-leveling/pom.xml b/queue-load-leveling/pom.xml
index be8404c2da25..b77466934933 100644
--- a/queue-load-leveling/pom.xml
+++ b/queue-load-leveling/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTqueue-load-leveling
diff --git a/reactor/pom.xml b/reactor/pom.xml
index 104b52521975..7610804309e5 100644
--- a/reactor/pom.xml
+++ b/reactor/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTreactor
diff --git a/reader-writer-lock/pom.xml b/reader-writer-lock/pom.xml
index 9cde49e389c5..3892e5c62fee 100644
--- a/reader-writer-lock/pom.xml
+++ b/reader-writer-lock/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTreader-writer-lock
diff --git a/repository/pom.xml b/repository/pom.xml
index 906389282945..3bae29a70ba9 100644
--- a/repository/pom.xml
+++ b/repository/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTrepository
diff --git a/resource-acquisition-is-initialization/pom.xml b/resource-acquisition-is-initialization/pom.xml
index d094eff8d052..c368d1b531cc 100644
--- a/resource-acquisition-is-initialization/pom.xml
+++ b/resource-acquisition-is-initialization/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTresource-acquisition-is-initialization
diff --git a/retry/pom.xml b/retry/pom.xml
index 73b25b64b9ee..d1dc9531f71b 100644
--- a/retry/pom.xml
+++ b/retry/pom.xml
@@ -28,7 +28,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTretryjar
diff --git a/role-object/pom.xml b/role-object/pom.xml
index c9feb1419afd..322122897394 100644
--- a/role-object/pom.xml
+++ b/role-object/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTrole-object
diff --git a/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java b/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java
index b8296dabacc6..eb76ef34a522 100644
--- a/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java
+++ b/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java
@@ -20,13 +20,15 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
+
package com.iluwatar.roleobject;
+import static com.iluwatar.roleobject.Role.Borrower;
+import static com.iluwatar.roleobject.Role.Investor;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import static com.iluwatar.roleobject.Role.*;
-
/**
* The Role Object pattern suggests to model context-specific views
* of an object as separate role objects which are
@@ -39,55 +41,60 @@
* investor, respectively. Both roles could as well be played by a single {@link Customer} object.
* The common superclass for customer-specific roles is provided by {@link CustomerRole},
* which also supports the {@link Customer} interface.
- *
- * The {@link CustomerRole} class is abstract and not meant to be instantiated.
- * Concrete subclasses of {@link CustomerRole}, for example {@link BorrowerRole} or {@link InvestorRole},
- * define and implement the interface for specific roles. It is only
+ *
+ *
The {@link CustomerRole} class is abstract and not meant to be instantiated.
+ * Concrete subclasses of {@link CustomerRole}, for example {@link BorrowerRole}
+ * or {@link InvestorRole}, define and implement the interface for specific roles. It is only
* these subclasses which are instantiated at runtime.
- * The {@link BorrowerRole} class defines the context-specific view of {@link Customer} objects as needed by the loan department.
+ * The {@link BorrowerRole} class defines the context-specific view of {@link Customer}
+ * objects as needed by the loan department.
* It defines additional operations to manage the customer’s
* credits and securities. Similarly, the {@link InvestorRole} class adds operations specific
* to the investment department’s view of customers.
- * A client like the loan application may either work with objects of the {@link CustomerRole} class, using the interface class
- * {@link Customer}, or with objects of concrete {@link CustomerRole} subclasses. Suppose the loan application knows a particular
- * {@link Customer} instance through its {@link Customer} interface. The loan application may want to check whether the {@link Customer}
- * object plays the role of Borrower.
- * To this end it calls {@link Customer#hasRole(Role)} with a suitable role specification. For the purpose of
- * our example, let’s assume we can name roles with enum.
- * If the {@link Customer} object can play the role named “Borrower,” the loan application will ask it
- * to return a reference to the corresponding object.
+ * A client like the loan application may either work with objects of the {@link CustomerRole}
+ * class, using the interface class {@link Customer}, or with objects of concrete
+ * {@link CustomerRole} subclasses. Suppose the loan application knows a particular
+ * {@link Customer} instance through its {@link Customer} interface. The loan application
+ * may want to check whether the {@link Customer} object plays the role of Borrower.
+ * To this end it calls {@link Customer#hasRole(Role)} with a suitable role specification. For
+ * the purpose of our example, let’s assume we can name roles with enum.
+ * If the {@link Customer} object can play the role named “Borrower,” the loan application will
+ * ask it to return a reference to the corresponding object.
* The loan application may now use this reference to call Borrower-specific operations.
*/
public class ApplicationRoleObject {
- private static final Logger logger = LoggerFactory.getLogger(Role.class);
-
- public static void main(String[] args) {
- Customer customer = Customer.newCustomer(Borrower, Investor);
-
- logger.info(" the new customer created : {}", customer);
+ private static final Logger logger = LoggerFactory.getLogger(Role.class);
- boolean hasBorrowerRole = customer.hasRole(Borrower);
- logger.info(" customer has a borrowed role - {}", hasBorrowerRole);
- boolean hasInvestorRole = customer.hasRole(Investor);
- logger.info(" customer has an investor role - {}", hasInvestorRole);
+ /**
+ * Main entry point.
+ *
+ * @param args program arguments
+ */
+ public static void main(String[] args) {
+ Customer customer = Customer.newCustomer(Borrower, Investor);
- customer.getRole(Investor, InvestorRole.class)
- .ifPresent(inv -> {
- inv.setAmountToInvest(1000);
- inv.setName("Billy");
- });
- customer.getRole(Borrower, BorrowerRole.class)
- .ifPresent(inv -> inv.setName("Johny"));
+ logger.info(" the new customer created : {}", customer);
- customer.getRole(Investor, InvestorRole.class)
- .map(InvestorRole::invest)
- .ifPresent(logger::info);
+ boolean hasBorrowerRole = customer.hasRole(Borrower);
+ logger.info(" customer has a borrowed role - {}", hasBorrowerRole);
+ boolean hasInvestorRole = customer.hasRole(Investor);
+ logger.info(" customer has an investor role - {}", hasInvestorRole);
- customer.getRole(Borrower, BorrowerRole.class)
- .map(BorrowerRole::borrow)
- .ifPresent(logger::info);
- }
+ customer.getRole(Investor, InvestorRole.class)
+ .ifPresent(inv -> {
+ inv.setAmountToInvest(1000);
+ inv.setName("Billy");
+ });
+ customer.getRole(Borrower, BorrowerRole.class)
+ .ifPresent(inv -> inv.setName("Johny"));
+ customer.getRole(Investor, InvestorRole.class)
+ .map(InvestorRole::invest)
+ .ifPresent(logger::info);
+ customer.getRole(Borrower, BorrowerRole.class)
+ .map(BorrowerRole::borrow)
+ .ifPresent(logger::info);
+ }
}
diff --git a/role-object/src/main/java/com/iluwatar/roleobject/BorrowerRole.java b/role-object/src/main/java/com/iluwatar/roleobject/BorrowerRole.java
index 425d9511d083..19db1c823a79 100644
--- a/role-object/src/main/java/com/iluwatar/roleobject/BorrowerRole.java
+++ b/role-object/src/main/java/com/iluwatar/roleobject/BorrowerRole.java
@@ -20,21 +20,23 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
+
package com.iluwatar.roleobject;
-public class BorrowerRole extends CustomerRole{
- private String name;
+public class BorrowerRole extends CustomerRole {
+
+ private String name;
- public String getName() {
- return name;
- }
+ public String getName() {
+ return name;
+ }
- public void setName(String name) {
- this.name = name;
- }
+ public void setName(String name) {
+ this.name = name;
+ }
- public String borrow(){
- return String.format("Borrower %s wants to get some money.",name);
- }
+ public String borrow() {
+ return String.format("Borrower %s wants to get some money.", name);
+ }
}
diff --git a/role-object/src/main/java/com/iluwatar/roleobject/Customer.java b/role-object/src/main/java/com/iluwatar/roleobject/Customer.java
index ebcddff4b154..1d21c5cc80a9 100644
--- a/role-object/src/main/java/com/iluwatar/roleobject/Customer.java
+++ b/role-object/src/main/java/com/iluwatar/roleobject/Customer.java
@@ -20,6 +20,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
+
package com.iluwatar.roleobject;
import java.util.Optional;
@@ -29,51 +30,52 @@
*/
public abstract class Customer {
- /**
- * Add specific role @see {@link Role}
- *
- * @param role to add
- * @return true if the operation has been successful otherwise false
- */
- public abstract boolean addRole(Role role);
+ /**
+ * Add specific role @see {@link Role}.
+ * @param role to add
+ * @return true if the operation has been successful otherwise false
+ */
+ public abstract boolean addRole(Role role);
- /**
- * Check specific role @see {@link Role}
- *
- * @param role to check
- * @return true if the role exists otherwise false
- */
+ /**
+ * Check specific role @see {@link Role}.
+ * @param role to check
+ * @return true if the role exists otherwise false
+ */
- public abstract boolean hasRole(Role role);
+ public abstract boolean hasRole(Role role);
- /**
- * Remove specific role @see {@link Role}
- *
- * @param role to remove
- * @return true if the operation has been successful otherwise false
- */
- public abstract boolean remRole(Role role);
+ /**
+ * Remove specific role @see {@link Role}.
+ * @param role to remove
+ * @return true if the operation has been successful otherwise false
+ */
+ public abstract boolean remRole(Role role);
- /**
- * Get specific instance associated with this role @see {@link Role}
- *
- * @param role to get
- * @param expectedRole instance class expected to get
- * @return optional with value if the instance exists and corresponds expected class
- */
- public abstract Optional getRole(Role role, Class expectedRole);
+ /**
+ * Get specific instance associated with this role @see {@link Role}.
+ * @param role to get
+ * @param expectedRole instance class expected to get
+ * @return optional with value if the instance exists and corresponds expected class
+ */
+ public abstract Optional getRole(Role role, Class expectedRole);
- public static Customer newCustomer() {
- return new CustomerCore();
- }
+ public static Customer newCustomer() {
+ return new CustomerCore();
+ }
- public static Customer newCustomer(Role... role) {
- Customer customer = newCustomer();
- for (Role r : role) {
- customer.addRole(r);
- }
- return customer;
+ /**
+ * Create {@link Customer} with given roles.
+ * @param role roles
+ * @return Customer
+ */
+ public static Customer newCustomer(Role... role) {
+ Customer customer = newCustomer();
+ for (Role r : role) {
+ customer.addRole(r);
}
+ return customer;
+ }
}
diff --git a/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java b/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java
index 5de27aa9295d..670a53904ef7 100644
--- a/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java
+++ b/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java
@@ -20,56 +20,60 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
+
package com.iluwatar.roleobject;
-import java.util.*;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
/**
- * Core class to store different customer roles
+ * Core class to store different customer roles.
*
- * @see CustomerRole
- * Note: not thread safe
+ * @see CustomerRole Note: not thread safe
*/
public class CustomerCore extends Customer {
- private Map roles;
+ private Map roles;
- public CustomerCore() {
- roles = new HashMap<>();
- }
+ public CustomerCore() {
+ roles = new HashMap<>();
+ }
- @Override
- public boolean addRole(Role role) {
- return role
- .instance()
- .map(inst -> {
- roles.put(role, inst);
- return true;
- })
- .orElse(false);
- }
+ @Override
+ public boolean addRole(Role role) {
+ return role
+ .instance()
+ .map(inst -> {
+ roles.put(role, inst);
+ return true;
+ })
+ .orElse(false);
+ }
- @Override
- public boolean hasRole(Role role) {
- return roles.containsKey(role);
- }
+ @Override
+ public boolean hasRole(Role role) {
+ return roles.containsKey(role);
+ }
- @Override
- public boolean remRole(Role role) {
- return Objects.nonNull(roles.remove(role));
- }
+ @Override
+ public boolean remRole(Role role) {
+ return Objects.nonNull(roles.remove(role));
+ }
- @Override
- public Optional getRole(Role role, Class expectedRole) {
- return Optional
- .ofNullable(roles.get(role))
- .filter(expectedRole::isInstance)
- .map(expectedRole::cast);
- }
+ @Override
+ public Optional getRole(Role role, Class expectedRole) {
+ return Optional
+ .ofNullable(roles.get(role))
+ .filter(expectedRole::isInstance)
+ .map(expectedRole::cast);
+ }
- @Override
- public String toString() {
- String roles = Arrays.toString(this.roles.keySet().toArray());
- return "Customer{roles=" + roles + "}";
- }
+ @Override
+ public String toString() {
+ String roles = Arrays.toString(this.roles.keySet().toArray());
+ return "Customer{roles=" + roles + "}";
+ }
}
diff --git a/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java b/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java
index 40fe2341b3a9..7f1805924fdc 100644
--- a/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java
+++ b/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java
@@ -20,9 +20,11 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
+
package com.iluwatar.roleobject;
/**
- * Key abstraction for segregated roles
+ * Key abstraction for segregated roles.
*/
-public abstract class CustomerRole extends CustomerCore{}
+public abstract class CustomerRole extends CustomerCore{
+}
diff --git a/role-object/src/main/java/com/iluwatar/roleobject/InvestorRole.java b/role-object/src/main/java/com/iluwatar/roleobject/InvestorRole.java
index d6ec6bc42050..d95289a07140 100644
--- a/role-object/src/main/java/com/iluwatar/roleobject/InvestorRole.java
+++ b/role-object/src/main/java/com/iluwatar/roleobject/InvestorRole.java
@@ -20,29 +20,32 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
+
package com.iluwatar.roleobject;
public class InvestorRole extends CustomerRole {
- private String name;
- private long amountToInvest;
- public String getName() {
- return name;
- }
+ private String name;
+
+ private long amountToInvest;
+
+ public String getName() {
+ return name;
+ }
- public void setName(String name) {
- this.name = name;
- }
+ public void setName(String name) {
+ this.name = name;
+ }
- public long getAmountToInvest() {
- return amountToInvest;
- }
+ public long getAmountToInvest() {
+ return amountToInvest;
+ }
- public void setAmountToInvest(long amountToInvest) {
- this.amountToInvest = amountToInvest;
- }
+ public void setAmountToInvest(long amountToInvest) {
+ this.amountToInvest = amountToInvest;
+ }
- public String invest() {
- return String.format("Investor %s has invested %d dollars", name, amountToInvest);
- }
+ public String invest() {
+ return String.format("Investor %s has invested %d dollars", name, amountToInvest);
+ }
}
diff --git a/role-object/src/main/java/com/iluwatar/roleobject/Role.java b/role-object/src/main/java/com/iluwatar/roleobject/Role.java
index f6c739891566..74863ad84051 100644
--- a/role-object/src/main/java/com/iluwatar/roleobject/Role.java
+++ b/role-object/src/main/java/com/iluwatar/roleobject/Role.java
@@ -20,36 +20,41 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
+
package com.iluwatar.roleobject;
+import java.util.Optional;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Optional;
-
/**
- * Possible roles
+ * Possible roles.
*/
public enum Role {
- Borrower(BorrowerRole.class), Investor(InvestorRole.class);
- private Class extends CustomerRole> typeCst;
+ Borrower(BorrowerRole.class), Investor(InvestorRole.class);
- Role(Class extends CustomerRole> typeCst) {
- this.typeCst = typeCst;
- }
+ private Class extends CustomerRole> typeCst;
+
+ Role(Class extends CustomerRole> typeCst) {
+ this.typeCst = typeCst;
+ }
+
+ private static final Logger logger = LoggerFactory.getLogger(Role.class);
- private static final Logger logger = LoggerFactory.getLogger(Role.class);
-
- @SuppressWarnings("unchecked")
- public Optional instance() {
- Class extends CustomerRole> typeCst = this.typeCst;
- try {
- return (Optional) Optional.of(typeCst.newInstance());
- } catch (InstantiationException | IllegalAccessException e) {
- logger.error("error creating an object", e);
- }
- return Optional.empty();
+ /**
+ * Get instance.
+ */
+ @SuppressWarnings("unchecked")
+ public Optional instance() {
+ Class extends CustomerRole> typeCst = this.typeCst;
+ try {
+ return (Optional) Optional.of(typeCst.newInstance());
+ } catch (InstantiationException | IllegalAccessException e) {
+ logger.error("error creating an object", e);
}
+ return Optional.empty();
+ }
}
diff --git a/saga/pom.xml b/saga/pom.xml
index 111f4e7b8134..a22ec9797f61 100644
--- a/saga/pom.xml
+++ b/saga/pom.xml
@@ -30,7 +30,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTsaga
diff --git a/semaphore/pom.xml b/semaphore/pom.xml
index 1ae865f02442..2684289981fa 100644
--- a/semaphore/pom.xml
+++ b/semaphore/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTsemaphore
diff --git a/servant/pom.xml b/servant/pom.xml
index e8c791d613be..db5abe580025 100644
--- a/servant/pom.xml
+++ b/servant/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTservant
diff --git a/serverless/pom.xml b/serverless/pom.xml
index 292df78c55f1..1fb55ec47536 100644
--- a/serverless/pom.xml
+++ b/serverless/pom.xml
@@ -31,7 +31,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOT
diff --git a/service-layer/pom.xml b/service-layer/pom.xml
index 31fc6f625b68..809454907b10 100644
--- a/service-layer/pom.xml
+++ b/service-layer/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTservice-layer
diff --git a/service-locator/pom.xml b/service-locator/pom.xml
index 5232bbd28818..56a11da10b3f 100644
--- a/service-locator/pom.xml
+++ b/service-locator/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTservice-locator
diff --git a/sharding/README.md b/sharding/README.md
index b40f08cfccd5..3184e405ed17 100644
--- a/sharding/README.md
+++ b/sharding/README.md
@@ -1,10 +1,9 @@
-
----
+---
layout: pattern
title: Sharding
-folder: sharding
+folder: sharding
permalink: /patterns/sharding/
-categories: Other
+categories: Other
tags:
- Java
- Difficulty-Beginner
diff --git a/sharding/pom.xml b/sharding/pom.xml
index f0dd01a7c8a2..eb24071fa4d5 100644
--- a/sharding/pom.xml
+++ b/sharding/pom.xml
@@ -29,7 +29,7 @@
java-design-patternscom.iluwatar
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOT4.0.0
diff --git a/singleton/pom.xml b/singleton/pom.xml
index c07183c7fae7..7862cd2a090b 100644
--- a/singleton/pom.xml
+++ b/singleton/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTsingleton
diff --git a/spatial-partition/README.md b/spatial-partition/README.md
index e4270e50b1e0..6e55f9544ff2 100644
--- a/spatial-partition/README.md
+++ b/spatial-partition/README.md
@@ -3,7 +3,7 @@ layout: pattern
title: Spatial Partition
folder: spatial-partition
permalink: /patterns/spatial-partition/
-categories: Game Programming pattern/Optimisation pattern
+categories: Other
tags:
- Java
- Difficulty-Intermediate
diff --git a/spatial-partition/pom.xml b/spatial-partition/pom.xml
index b7d6d4b633b3..4b048714de72 100644
--- a/spatial-partition/pom.xml
+++ b/spatial-partition/pom.xml
@@ -46,7 +46,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTspatial-partition
diff --git a/specification/README.md b/specification/README.md
index a72e253d7e9b..1764f448bb78 100644
--- a/specification/README.md
+++ b/specification/README.md
@@ -31,7 +31,8 @@ Use the Specification pattern when
Real world example
-> There is a pool of different creatures and we often need to select some subset of them. We can write our search specification such as "creatures that can fly" and give it to the party that will perform the filtering.
+> There is a pool of different creatures and we often need to select some subset of them.
+> We can write our search specification such as "creatures that can fly", "creatures heavier than 500 kilograms", or as a combination of other search specifications, and then give it to the party that will perform the filtering.
In Plain Words
@@ -44,6 +45,10 @@ Wikipedia says
**Programmatic Example**
If we look at our creature pool example from above, we have a set of creatures with certain properties.
+Those properties can be part of a pre-defined, limited set (represented here by the enums Size, Movement and Color); but they can also be continuous values (e.g. the mass of a Creature).
+In this case, it is more appropriate to use what we call "parameterized specification", where the property value can be given as an argument when the Creature is instantiated, allowing for more flexibility.
+A third option is to combine pre-defined and/or parameterized properties using boolean logic, allowing for near-endless selection possibilities (this is called "composite specification", see below).
+The pros and cons of each approach are detailed in the table at the end of this document.
```java
public interface Creature {
@@ -51,24 +56,25 @@ public interface Creature {
Size getSize();
Movement getMovement();
Color getColor();
+ Mass getMass();
}
```
-And dragon implementation looks like this.
+And ``Dragon`` implementation looks like this.
```java
public class Dragon extends AbstractCreature {
public Dragon() {
- super("Dragon", Size.LARGE, Movement.FLYING, Color.RED);
+ super("Dragon", Size.LARGE, Movement.FLYING, Color.RED, new Mass(39300.0));
}
}
```
-Now that we want to select some subset of them, we use selectors. To select creatures that fly, we should use MovementSelector.
+Now that we want to select some subset of them, we use selectors. To select creatures that fly, we should use ``MovementSelector``.
```java
-public class MovementSelector implements Predicate {
+public class MovementSelector extends AbstractSelector {
private final Movement movement;
@@ -83,13 +89,107 @@ public class MovementSelector implements Predicate {
}
```
-With these building blocks in place, we can perform a search for red and flying creatures like this.
+On the other hand, when selecting creatures heavier than a chosen amount, we use ``MassGreaterThanSelector``.
```java
- List redAndFlyingCreatures = creatures.stream()
- .filter(new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING))).collect(Collectors.toList());
+public class MassGreaterThanSelector extends AbstractSelector {
+
+ private final Mass mass;
+
+ public MassGreaterThanSelector(double mass) {
+ this.mass = new Mass(mass);
+ }
+
+ @Override
+ public boolean test(Creature t) {
+ return t.getMass().greaterThan(mass);
+ }
+}
+```
+
+With these building blocks in place, we can perform a search for red creatures as follows:
+
+```java
+ List redCreatures = creatures.stream().filter(new ColorSelector(Color.RED))
+ .collect(Collectors.toList());
```
+But we could also use our parameterized selector like this:
+
+```java
+ List heavyCreatures = creatures.stream().filter(new MassGreaterThanSelector(500.0)
+ .collect(Collectors.toList());
+```
+
+Our third option is to combine multiple selectors together. Performing a search for special creatures (defined as red, flying, and not small) could be done as follows:
+
+```java
+ AbstractSelector specialCreaturesSelector =
+ new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING)).and(new SizeSelector(Size.SMALL).not());
+
+ List specialCreatures = creatures.stream().filter(specialCreaturesSelector)
+ .collect(Collectors.toList());
+```
+
+**More on Composite Specification**
+
+In Composite Specification, we will create custom instances of ``AbstractSelector`` by combining other selectors (called "leaves") using the three basic logical operators.
+These are implemented in ``ConjunctionSelector``, ``DisjunctionSelector`` and ``NegationSelector``.
+
+```java
+public abstract class AbstractSelector implements Predicate {
+
+ public AbstractSelector and(AbstractSelector other) {
+ return new ConjunctionSelector<>(this, other);
+ }
+
+ public AbstractSelector or(AbstractSelector other) {
+ return new DisjunctionSelector<>(this, other);
+ }
+
+ public AbstractSelector not() {
+ return new NegationSelector<>(this);
+ }
+}
+```
+
+```java
+public class ConjunctionSelector extends AbstractSelector {
+
+ private List> leafComponents;
+
+ @SafeVarargs
+ ConjunctionSelector(AbstractSelector... selectors) {
+ this.leafComponents = List.of(selectors);
+ }
+
+ /**
+ * Tests if *all* selectors pass the test.
+ */
+ @Override
+ public boolean test(T t) {
+ return leafComponents.stream().allMatch(comp -> (comp.test(t)));
+ }
+}
+```
+
+All that is left to do is now to create leaf selectors (be it hard-coded or parameterized ones) that are as generic as possible,
+and we will be able to instantiate the ``AbstractSelector`` class by combining any amount of selectors, as exemplified above.
+We should be careful though, as it is easy to make a mistake when combining many logical operators; in particular, we should pay attention to the priority of the operations.\
+In general, Composite Specification is a great way to write more reusable code, as there is no need to create a Selector class for each filtering operation.
+Instead, we just create an instance of ``AbstractSelector`` "on the spot", using tour generic "leaf" selectors and some basic boolean logic.
+
+
+**Comparison of the different approaches**
+
+| Pattern | Usage | Pros | Cons |
+|---|---|---|---|
+| Hard-Coded Specification | Selection criteria are few and known in advance | + Easy to implement | - Inflexible |
+| | | + Expressive |
+| Parameterized Specification | Selection criteria are a large range of values (e.g. mass, speed,...) | + Some flexibility | - Still requires special-purpose classes |
+| Composite Specification | There are a lot of selection criteria that can be combined in multiple ways, hence it is not feasible to create a class for each selector | + Very flexible, without requiring many specialized classes | - Somewhat more difficult to comprehend |
+| | | + Supports logical operations | - You still need to create the base classes used as leaves |
+
## Related patterns
* Repository
diff --git a/specification/etc/specification.ucls b/specification/etc/specification.ucls
index 2edbbed0c9cd..54b08cc41d57 100644
--- a/specification/etc/specification.ucls
+++ b/specification/etc/specification.ucls
@@ -117,7 +117,7 @@
-
+
@@ -126,7 +126,7 @@
-
+
@@ -186,13 +186,13 @@
-
-
+
+
-
-
-
-
+
+
+
+
@@ -202,7 +202,7 @@
-
+
diff --git a/specification/pom.xml b/specification/pom.xml
index 9f64b41d71b7..79d81fd5c3a8 100644
--- a/specification/pom.xml
+++ b/specification/pom.xml
@@ -29,7 +29,7 @@
com.iluwatarjava-design-patterns
- 1.22.0-SNAPSHOT
+ 1.23.0-SNAPSHOTspecification
diff --git a/specification/src/main/java/com/iluwatar/specification/app/App.java b/specification/src/main/java/com/iluwatar/specification/app/App.java
index 8ca7283c9216..2f9633313d83 100644
--- a/specification/src/main/java/com/iluwatar/specification/app/App.java
+++ b/specification/src/main/java/com/iluwatar/specification/app/App.java
@@ -32,7 +32,11 @@
import com.iluwatar.specification.creature.Troll;
import com.iluwatar.specification.property.Color;
import com.iluwatar.specification.property.Movement;
+import com.iluwatar.specification.selector.AbstractSelector;
import com.iluwatar.specification.selector.ColorSelector;
+import com.iluwatar.specification.selector.MassEqualSelector;
+import com.iluwatar.specification.selector.MassGreaterThanSelector;
+import com.iluwatar.specification.selector.MassSmallerThanOrEqSelector;
import com.iluwatar.specification.selector.MovementSelector;
import java.util.List;
import java.util.stream.Collectors;
@@ -51,7 +55,7 @@
*