[JAVA-14174] Renamed paterns to paterns-module (#12718)

* [JAVA-14174] Renamed paterns to paterns-module

* [JAVA-14174] naming fixes

Co-authored-by: panagiotiskakos <panagiotis.kakos@libra-is.com>
This commit is contained in:
panos-kakos
2022-09-19 07:44:14 +01:00
committed by GitHub
parent 368dd6de19
commit b153cff200
518 changed files with 32 additions and 32 deletions

View File

@@ -0,0 +1,11 @@
### Relevant Articles:
- [The Observer Pattern in Java](https://www.baeldung.com/java-observer-pattern)
- [Visitor Design Pattern in Java](https://www.baeldung.com/java-visitor-pattern)
- [Interpreter Design Pattern in Java](https://www.baeldung.com/java-interpreter-pattern)
- [State Design Pattern in Java](https://www.baeldung.com/java-state-design-pattern)
- [Implementing the Template Method Pattern in Java](https://www.baeldung.com/java-template-method-pattern)
- [Chain of Responsibility Design Pattern in Java](https://www.baeldung.com/chain-of-responsibility-pattern)
- [The Command Pattern in Java](https://www.baeldung.com/java-command-pattern)
- [The Mediator Pattern in Java](https://www.baeldung.com/java-mediator-pattern)
- [Introduction to the Null Object Pattern](https://www.baeldung.com/java-null-object-pattern)
- [Avoid Check for Null Statement in Java](https://www.baeldung.com/java-avoid-null-check)

View File

@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>design-patterns-behavioral</artifactId>
<version>1.0</version>
<name>design-patterns-behavioral</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>patterns-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>${intellij.annotations.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>annotations</artifactId>
<version>${findbugs.annotations.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
<properties>
<intellij.annotations.version>16.0.2</intellij.annotations.version>
<findbugs.annotations.version>3.0.1</findbugs.annotations.version>
</properties>
</project>

View File

@@ -0,0 +1,13 @@
package com.baeldung.chainofresponsibility;
public abstract class AuthenticationProcessor {
// next element in chain or responsibility
public AuthenticationProcessor nextProcessor;
public AuthenticationProcessor(AuthenticationProcessor nextProcessor) {
this.nextProcessor = nextProcessor;
}
public abstract boolean isAuthorized(AuthenticationProvider authProvider);
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.chainofresponsibility;
public interface AuthenticationProvider {
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.chainofresponsibility;
public class OAuthAuthenticationProcessor extends AuthenticationProcessor {
public OAuthAuthenticationProcessor(AuthenticationProcessor nextProcessor) {
super(nextProcessor);
}
@Override
public boolean isAuthorized(AuthenticationProvider authProvider) {
if (authProvider instanceof OAuthTokenProvider) {
return Boolean.TRUE;
} else if (nextProcessor != null) {
return nextProcessor.isAuthorized(authProvider);
} else {
return Boolean.FALSE;
}
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.chainofresponsibility;
public class OAuthTokenProvider implements AuthenticationProvider {
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.chainofresponsibility;
public class SamlAuthenticationProvider implements AuthenticationProvider {
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.chainofresponsibility;
public class UsernamePasswordAuthenticationProcessor extends AuthenticationProcessor {
public UsernamePasswordAuthenticationProcessor(AuthenticationProcessor nextProcessor) {
super(nextProcessor);
}
@Override
public boolean isAuthorized(AuthenticationProvider authProvider) {
if (authProvider instanceof UsernamePasswordProvider) {
return Boolean.TRUE;
} else if (nextProcessor != null) {
return nextProcessor.isAuthorized(authProvider);
} else {
return Boolean.FALSE;
}
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.chainofresponsibility;
public class UsernamePasswordProvider implements AuthenticationProvider {
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.command.client;
import com.baeldung.command.command.OpenTextFileOperation;
import com.baeldung.command.command.SaveTextFileOperation;
import com.baeldung.command.command.TextFileOperation;
import com.baeldung.command.invoker.TextFileOperationExecutor;
import com.baeldung.command.receiver.TextFile;
public class TextFileApplication {
public static void main(String[] args) {
TextFileOperation openTextFileOperation = new OpenTextFileOperation(new TextFile("file1.txt"));
TextFileOperation saveTextFileOperation = new SaveTextFileOperation(new TextFile("file2.txt"));
TextFileOperationExecutor textFileOperationExecutor = new TextFileOperationExecutor();
System.out.println(textFileOperationExecutor.executeOperation(openTextFileOperation));
System.out.println(textFileOperationExecutor.executeOperation(saveTextFileOperation));
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.command.command;
import com.baeldung.command.receiver.TextFile;
public class OpenTextFileOperation implements TextFileOperation {
private final TextFile textFile;
public OpenTextFileOperation(TextFile textFile) {
this.textFile = textFile;
}
@Override
public String execute() {
return textFile.open();
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.command.command;
import com.baeldung.command.receiver.TextFile;
public class SaveTextFileOperation implements TextFileOperation {
private final TextFile textFile;
public SaveTextFileOperation(TextFile textFile) {
this.textFile = textFile;
}
@Override
public String execute() {
return textFile.save();
}
}

View File

@@ -0,0 +1,8 @@
package com.baeldung.command.command;
@FunctionalInterface
public interface TextFileOperation {
String execute();
}

View File

@@ -0,0 +1,15 @@
package com.baeldung.command.invoker;
import com.baeldung.command.command.TextFileOperation;
import java.util.ArrayList;
import java.util.List;
public class TextFileOperationExecutor {
private final List<TextFileOperation> textFileOperations = new ArrayList<>();
public String executeOperation(TextFileOperation textFileOperation) {
textFileOperations.add(textFileOperation);
return textFileOperation.execute();
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.command.receiver;
public class TextFile {
private final String name;
public TextFile(String name) {
this.name = name;
}
public String open() {
return "Opening file " + name;
}
public String read() {
return "Reading file " + name;
}
public String write() {
return "Writing to file " + name;
}
public String save() {
return "Saving file " + name;
}
public String copy() {
return "Copying file " + name;
}
public String paste() {
return "Pasting file " + name;
}
}

View File

@@ -0,0 +1,107 @@
package com.baeldung.interpreter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Context {
private static Map<String, List<Row>> tables = new HashMap<>();
static {
List<Row> list = new ArrayList<>();
list.add(new Row("John", "Doe"));
list.add(new Row("Jan", "Kowalski"));
list.add(new Row("Dominic", "Doom"));
tables.put("people", list);
}
private String table;
private String column;
/**
* Index of column to be shown in result.
* Calculated in {@link #setColumnMapper()}
*/
private int colIndex = -1;
/**
* Default setup, used for clearing the context for next queries.
* See {@link Context#clear()}
*/
private static final Predicate<String> matchAnyString = s -> s.length() > 0;
private static final Function<String, Stream<? extends String>> matchAllColumns = Stream::of;
/**
* Varies based on setup in subclasses of {@link Expression}
*/
private Predicate<String> whereFilter = matchAnyString;
private Function<String, Stream<? extends String>> columnMapper = matchAllColumns;
void setColumn(String column) {
this.column = column;
setColumnMapper();
}
void setTable(String table) {
this.table = table;
}
void setFilter(Predicate<String> filter) {
whereFilter = filter;
}
/**
* Clears the context to defaults.
* No filters, match all columns.
*/
void clear() {
column = "";
columnMapper = matchAllColumns;
whereFilter = matchAnyString;
}
List<String> search() {
List<String> result = tables.entrySet()
.stream()
.filter(entry -> entry.getKey().equalsIgnoreCase(table))
.flatMap(entry -> Stream.of(entry.getValue()))
.flatMap(Collection::stream)
.map(Row::toString)
.flatMap(columnMapper)
.filter(whereFilter)
.collect(Collectors.toList());
clear();
return result;
}
/**
* Sets column mapper based on {@link #column} attribute.
* Note: If column is unknown, will remain to look for all columns.
*/
private void setColumnMapper() {
switch (column) {
case "*":
colIndex = -1;
break;
case "name":
colIndex = 0;
break;
case "surname":
colIndex = 1;
break;
}
if (colIndex != -1) {
columnMapper = s -> Stream.of(s.split(" ")[colIndex]);
}
}
}

View File

@@ -0,0 +1,7 @@
package com.baeldung.interpreter;
import java.util.List;
interface Expression {
List<String> interpret(Context ctx);
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.interpreter;
import java.util.List;
class From implements Expression {
private String table;
private Where where;
From(String table) {
this.table = table;
}
From(String table, Where where) {
this.table = table;
this.where = where;
}
@Override
public List<String> interpret(Context ctx) {
ctx.setTable(table);
if (where == null) {
return ctx.search();
}
return where.interpret(ctx);
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.interpreter;
import java.util.List;
public class InterpreterDemo {
public static void main(String[] args) {
Expression query = new Select("name", new From("people"));
Context ctx = new Context();
List<String> result = query.interpret(ctx);
System.out.println(result);
Expression query2 = new Select("*", new From("people"));
List<String> result2 = query2.interpret(ctx);
System.out.println(result2);
Expression query3 = new Select("name", new From("people", new Where(name -> name.toLowerCase().startsWith("d"))));
List<String> result3 = query3.interpret(ctx);
System.out.println(result3);
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.interpreter;
class Row {
private String name;
private String surname;
Row(String name, String surname) {
this.name = name;
this.surname = surname;
}
@Override
public String toString() {
return name + " " + surname;
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.interpreter;
import java.util.List;
class Select implements Expression {
private String column;
private From from;
Select(String column, From from) {
this.column = column;
this.from = from;
}
@Override
public List<String> interpret(Context ctx) {
ctx.setColumn(column);
return from.interpret(ctx);
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.interpreter;
import java.util.List;
import java.util.function.Predicate;
class Where implements Expression {
private Predicate<String> filter;
Where(Predicate<String> filter) {
this.filter = filter;
}
@Override
public List<String> interpret(Context ctx) {
ctx.setFilter(filter);
return ctx.search();
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.mediator;
public class Button {
private Mediator mediator;
public void setMediator(Mediator mediator) {
this.mediator = mediator;
}
public void press() {
this.mediator.press();
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.mediator;
public class Fan {
private Mediator mediator;
private boolean isOn = false;
public void setMediator(Mediator mediator) {
this.mediator = mediator;
}
public boolean isOn() {
return isOn;
}
public void turnOn() {
this.mediator.start();
isOn = true;
}
public void turnOff() {
isOn = false;
this.mediator.stop();
}
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.mediator;
public class Mediator {
private Button button;
private Fan fan;
private PowerSupplier powerSupplier;
public void setButton(Button button) {
this.button = button;
this.button.setMediator(this);
}
public void setFan(Fan fan) {
this.fan = fan;
this.fan.setMediator(this);
}
public void setPowerSupplier(PowerSupplier powerSupplier) {
this.powerSupplier = powerSupplier;
}
public void press() {
if (fan.isOn()) {
fan.turnOff();
} else {
fan.turnOn();
}
}
public void start() {
powerSupplier.turnOn();
}
public void stop() {
powerSupplier.turnOff();
}
}

View File

@@ -0,0 +1,11 @@
package com.baeldung.mediator;
public class PowerSupplier {
public void turnOn() {
// implementation
}
public void turnOff() {
// implementation
}
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.nullobject;
public class JmsRouter implements Router {
@Override
public void route(Message msg) {
System.out.println("Routing to a JMS queue. Msg: " + msg);
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.nullobject;
public class Message {
private String body;
private String priority;
public Message(String body, String priority) {
this.body = body;
this.priority = priority;
}
public String getPriority() {
return priority;
}
@Override
public String toString() {
return "{body='" + body + '\'' +
", priority='" + priority + '\'' +
'}';
}
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.nullobject;
public class NullRouter implements Router {
@Override
public void route(Message msg) {
// do nothing
}
}

View File

@@ -0,0 +1,7 @@
package com.baeldung.nullobject;
public interface Router {
void route(Message msg);
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.nullobject;
public class RouterFactory {
public static Router getRouterForMessage(Message msg) {
if (msg.getPriority() == null) {
return new NullRouter();
}
switch (msg.getPriority()) {
case "high":
return new SmsRouter();
case "medium":
return new JmsRouter();
default:
return new NullRouter();
}
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.nullobject;
import java.util.Arrays;
import java.util.List;
public class RoutingHandler {
public void handle(Iterable<Message> messages){
for (Message msg : messages) {
Router router = RouterFactory.getRouterForMessage(msg);
router.route(msg);
}
}
public static void main(String[] args) {
Message highPriorityMsg = new Message("Alert!", "high");
Message mediumPriorityMsg = new Message("Warning!", "medium");
Message lowPriorityMsg = new Message("Take a look!", "low");
Message nullPriorityMsg = new Message("Take a look!", null);
List<Message> messages = Arrays.asList(highPriorityMsg,
mediumPriorityMsg,
lowPriorityMsg,
nullPriorityMsg);
RoutingHandler routingHandler = new RoutingHandler();
routingHandler.handle(messages);
}
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.nullobject;
public class SmsRouter implements Router {
@Override
public void route(Message msg) {
System.out.println("Routing to a SMS gateway. Msg: " + msg);
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.nulls;
public class APIContracts {
/**
* Prints the value of {@code param} if not null. Prints {@code null} otherwise.
*
* @param param
*/
public void print(Object param) {
System.out.println("Printing " + param);
}
/**
* @return non null result
* @throws Exception - if result is null
*/
public Object process() throws Exception {
Object result = doSomething();
if (result == null) {
throw new Exception("Processing fail. Got a null response");
} else {
return result;
}
}
private Object doSomething() {
return null;
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.nulls;
public class Assertions {
public void accept(Object param){
assert param != null;
doSomething(param);
}
private void doSomething(Object param) {
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.nulls;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class EmptyCollections {
public List<String> names() {
if (userExist()) {
return Stream.of(readName()).collect(Collectors.toList());
} else {
return Collections.emptyList();
}
}
private boolean userExist() {
return false;
}
private String readName() {
return "test";
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.nulls;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
public class FindBugsAnnotations {
public void accept(@NonNull Object param) {
System.out.println(param.toString());
}
public void print(@Nullable Object param) {
System.out.println("Printing " + param);
}
@NonNull
public Object process() throws Exception {
Object result = doSomething();
if (result == null) {
throw new Exception("Processing fail. Got a null response");
} else {
return result;
}
}
private Object doSomething() {
return null;
}
}

View File

@@ -0,0 +1,39 @@
package com.baeldung.nulls;
public class Preconditions {
public void goodAccept(String one, String two, String three) {
if (one == null || two == null || three == null) {
throw new IllegalArgumentException();
}
process(one);
process(two);
process(three);
}
public void badAccept(String one, String two, String three) {
if (one == null) {
throw new IllegalArgumentException();
} else {
process(one);
}
if (two == null) {
throw new IllegalArgumentException();
} else {
process(two);
}
if (three == null) {
throw new IllegalArgumentException();
} else {
process(three);
}
}
private void process(String one) {
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.nulls;
public class PrimitivesAndWrapper {
public static int primitiveSum(int a, int b) {
return a + b;
}
public static Integer wrapperSum(Integer a, Integer b) {
return a + b;
}
public static Integer goodSum(Integer a, Integer b) {
if (a != null && b != null) {
return a + b;
} else {
throw new IllegalArgumentException();
}
}
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.nulls;
import lombok.NonNull;
public class UsingLombok {
public void accept(@NonNull Object param){
System.out.println(param);
}
}

View File

@@ -0,0 +1,11 @@
package com.baeldung.nulls;
import java.util.Objects;
public class UsingObjects {
public void accept(Object param) {
Objects.requireNonNull(param);
// doSomething()
}
}

View File

@@ -0,0 +1,52 @@
package com.baeldung.nulls;
import java.util.List;
import java.util.Optional;
import static java.util.Collections.emptyList;
public class UsingOptional {
public static final String DEFAULT_VALUE = "Default Value";
public Optional<Object> process(boolean processed) {
String response = doSomething(processed);
return Optional.ofNullable(response);
}
public String findFirst() {
return getList()
.stream()
.findFirst()
.orElse(DEFAULT_VALUE);
}
public Optional<String> findOptionalFirst() {
return getList()
.stream()
.findFirst();
}
private List<String> getList() {
return emptyList();
}
public Optional<String> optionalListFirst() {
return getOptionalList()
.flatMap(list -> list.stream().findFirst());
}
private Optional<List<String>> getOptionalList() {
return Optional.of(getList());
}
private String doSomething(boolean processed) {
if (processed) {
return "passed";
} else {
return null;
}
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.nulls;
import org.apache.commons.lang3.StringUtils;
public class UsingStringUtils {
public void accept(String param) {
if (StringUtils.isNotEmpty(param)) {
System.out.println(param);
} else {
throw new IllegalArgumentException();
}
}
public void acceptOnlyNonBlank(String param) {
if (StringUtils.isNotBlank(param)) {
System.out.println(param);
} else {
throw new IllegalArgumentException();
}
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.observer;
public interface Channel {
public void update(Object o);
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.observer;
import java.util.ArrayList;
import java.util.List;
public class NewsAgency {
private String news;
private List<Channel> channels = new ArrayList<>();
public void addObserver(Channel channel) {
this.channels.add(channel);
}
public void removeObserver(Channel channel) {
this.channels.remove(channel);
}
public void setNews(String news) {
this.news = news;
for (Channel channel : this.channels) {
channel.update(this.news);
}
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.observer;
public class NewsChannel implements Channel {
private String news;
@Override
public void update(Object news) {
this.setNews((String) news);
}
public String getNews() {
return news;
}
public void setNews(String news) {
this.news = news;
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.observer;
import java.util.Observable;
public class ONewsAgency extends Observable {
private String news;
public void setNews(String news) {
this.news = news;
setChanged();
notifyObservers(news);
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.observer;
import java.util.Observable;
import java.util.Observer;
public class ONewsChannel implements Observer {
private String news;
@Override
public void update(Observable o, Object news) {
this.setNews((String) news);
}
public String getNews() {
return news;
}
public void setNews(String news) {
this.news = news;
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.observer;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
public class PCLNewsAgency {
private String news;
private PropertyChangeSupport support;
public PCLNewsAgency() {
support = new PropertyChangeSupport(this);
}
public void addPropertyChangeListener(PropertyChangeListener pcl) {
support.addPropertyChangeListener(pcl);
}
public void removePropertyChangeListener(PropertyChangeListener pcl) {
support.removePropertyChangeListener(pcl);
}
public void setNews(String value) {
support.firePropertyChange("news", this.news, value);
this.news = value;
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.observer;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public class PCLNewsChannel implements PropertyChangeListener {
private String news;
public void propertyChange(PropertyChangeEvent evt) {
this.setNews((String) evt.getNewValue());
}
public String getNews() {
return news;
}
public void setNews(String news) {
this.news = news;
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.state;
public class DeliveredState implements PackageState {
@Override
public void next(Package pkg) {
pkg.setState(new ReceivedState());
}
@Override
public void prev(Package pkg) {
pkg.setState(new OrderedState());
}
@Override
public void printStatus() {
System.out.println("Package delivered to post office, not received yet.");
}
@Override
public String toString() {
return "DeliveredState{}";
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.state;
public class OrderedState implements PackageState {
@Override
public void next(Package pkg) {
pkg.setState(new DeliveredState());
}
@Override
public void prev(Package pkg) {
System.out.println("The package is in it's root state.");
}
@Override
public void printStatus() {
System.out.println("Package ordered, not delivered to the office yet.");
}
@Override
public String toString() {
return "OrderedState{}";
}
}

View File

@@ -0,0 +1,26 @@
package com.baeldung.state;
public class Package {
private PackageState state = new OrderedState();
public PackageState getState() {
return state;
}
public void setState(PackageState state) {
this.state = state;
}
public void previousState() {
state.prev(this);
}
public void nextState() {
state.next(this);
}
public void printStatus() {
state.printStatus();
}
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.state;
public interface PackageState {
void next(Package pkg);
void prev(Package pkg);
void printStatus();
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.state;
public class ReceivedState implements PackageState {
@Override
public void next(Package pkg) {
System.out.println("This package is already received by a client.");
}
@Override
public void prev(Package pkg) {
pkg.setState(new DeliveredState());
}
@Override
public void printStatus() {
System.out.println("Package was received by client.");
}
@Override
public String toString() {
return "ReceivedState{}";
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.state;
public class StateDemo {
public static void main(String[] args) {
Package pkg = new Package();
pkg.printStatus();
pkg.nextState();
pkg.printStatus();
pkg.nextState();
pkg.printStatus();
pkg.nextState();
pkg.printStatus();
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.templatemethod.application;
import com.baeldung.templatemethod.model.Computer;
import com.baeldung.templatemethod.model.ComputerBuilder;
import com.baeldung.templatemethod.model.HighEndComputerBuilder;
import com.baeldung.templatemethod.model.StandardComputerBuilder;
public class Application {
public static void main(String[] args) {
ComputerBuilder standardComputerBuilder = new StandardComputerBuilder();
Computer standardComputer = standardComputerBuilder.buildComputer();
standardComputer.getComputerParts().forEach((k, v) -> System.out.println("Part : " + k + " Value : " + v));
ComputerBuilder highEndComputerBuilder = new HighEndComputerBuilder();
Computer highEndComputer = highEndComputerBuilder.buildComputer();
highEndComputer.getComputerParts().forEach((k, v) -> System.out.println("Part : " + k + " Value : " + v));
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.templatemethod.model;
import java.util.HashMap;
import java.util.Map;
public class Computer {
private Map<String, String> computerParts = new HashMap<>();
public Computer(Map<String, String> computerParts) {
this.computerParts = computerParts;
}
public Map<String, String> getComputerParts() {
return computerParts;
}
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.templatemethod.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class ComputerBuilder {
protected Map<String, String> computerParts = new HashMap<>();
protected List<String> motherboardSetupStatus = new ArrayList<>();
public final Computer buildComputer() {
addMotherboard();
setupMotherboard();
addProcessor();
return getComputer();
}
public abstract void addMotherboard();
public abstract void setupMotherboard();
public abstract void addProcessor();
public List<String> getMotherboardSetupStatus() {
return motherboardSetupStatus;
}
public Map<String, String> getComputerParts() {
return computerParts;
}
private Computer getComputer() {
return new Computer(computerParts);
}
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.templatemethod.model;
import java.util.Map;
public class HighEndComputer extends Computer {
public HighEndComputer(Map<String, String> computerParts) {
super(computerParts);
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.templatemethod.model;
public class HighEndComputerBuilder extends ComputerBuilder {
@Override
public void addMotherboard() {
computerParts.put("Motherboard", "High-end Motherboard");
}
@Override
public void setupMotherboard() {
motherboardSetupStatus.add("Screwing the high-end motherboard to the case.");
motherboardSetupStatus.add("Pluging in the power supply connectors.");
motherboardSetupStatus.forEach(step -> System.out.println(step));
}
@Override
public void addProcessor() {
computerParts.put("Processor", "High-end Processor");
}
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.templatemethod.model;
import java.util.Map;
public class StandardComputer extends Computer {
public StandardComputer(Map<String, String> computerParts) {
super(computerParts);
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.templatemethod.model;
public class StandardComputerBuilder extends ComputerBuilder {
@Override
public void addMotherboard() {
computerParts.put("Motherboard", "Standard Motherboard");
}
@Override
public void setupMotherboard() {
motherboardSetupStatus.add("Screwing the standard motherboard to the case.");
motherboardSetupStatus.add("Pluging in the power supply connectors.");
motherboardSetupStatus.forEach(step -> System.out.println(step));
}
@Override
public void addProcessor() {
computerParts.put("Processor", "Standard Processor");
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.visitor;
import java.util.ArrayList;
import java.util.List;
public class Document extends Element {
List<Element> elements = new ArrayList<>();
public Document(String uuid) {
super(uuid);
}
@Override
public void accept(Visitor v) {
for (Element e : this.elements) {
e.accept(v);
}
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.visitor;
public abstract class Element {
public String uuid;
public Element(String uuid) {
this.uuid = uuid;
}
public abstract void accept(Visitor v);
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.visitor;
public class ElementVisitor implements Visitor {
@Override
public void visit(XmlElement xe) {
System.out.println("processing xml element with uuid: " + xe.uuid);
}
@Override
public void visit(JsonElement je) {
System.out.println("processing json element with uuid: " + je.uuid);
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.visitor;
public class JsonElement extends Element {
public JsonElement(String uuid) {
super(uuid);
}
public void accept(Visitor v) {
v.visit(this);
}
}

View File

@@ -0,0 +1,8 @@
package com.baeldung.visitor;
public interface Visitor {
void visit(XmlElement xe);
void visit(JsonElement je);
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.visitor;
import java.util.UUID;
public class VisitorDemo {
public static void main(String[] args) {
Visitor v = new ElementVisitor();
Document d = new Document(generateUuid());
d.elements.add(new JsonElement(generateUuid()));
d.elements.add(new JsonElement(generateUuid()));
d.elements.add(new XmlElement(generateUuid()));
d.accept(v);
}
private static String generateUuid() {
return UUID.randomUUID()
.toString();
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.visitor;
public class XmlElement extends Element {
public XmlElement(String uuid) {
super(uuid);
}
public void accept(Visitor v) {
v.visit(this);
}
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.chainofresponsibility;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ChainOfResponsibilityIntegrationTest {
private static AuthenticationProcessor getChainOfAuthProcessor() {
AuthenticationProcessor oAuthProcessor = new OAuthAuthenticationProcessor(null);
AuthenticationProcessor unamePasswordProcessor = new UsernamePasswordAuthenticationProcessor(oAuthProcessor);
return unamePasswordProcessor;
}
@Test
public void givenOAuthProvider_whenCheckingAuthorized_thenSuccess() {
AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor();
boolean isAuthorized = authProcessorChain.isAuthorized(new OAuthTokenProvider());
assertTrue(isAuthorized);
}
@Test
public void givenUsernamePasswordProvider_whenCheckingAuthorized_thenSuccess() {
AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor();
boolean isAuthorized = authProcessorChain.isAuthorized(new UsernamePasswordProvider());
assertTrue(isAuthorized);
}
@Test
public void givenSamlAuthProvider_whenCheckingAuthorized_thenFailure() {
AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor();
boolean isAuthorized = authProcessorChain.isAuthorized(new SamlAuthenticationProvider());
assertTrue(!isAuthorized);
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.command.test;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import com.baeldung.command.command.OpenTextFileOperation;
import com.baeldung.command.command.TextFileOperation;
import com.baeldung.command.receiver.TextFile;
public class OpenTextFileOperationUnitTest {
@Test
public void givenOpenTextFileOperationIntance_whenCalledExecuteMethod_thenOneAssertion() {
TextFileOperation openTextFileOperation = new OpenTextFileOperation(new TextFile("file1.txt"));
assertThat(openTextFileOperation.execute()).isEqualTo("Opening file file1.txt");
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.command.test;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import com.baeldung.command.command.SaveTextFileOperation;
import com.baeldung.command.command.TextFileOperation;
import com.baeldung.command.receiver.TextFile;
public class SaveTextFileOperationUnitTest {
@Test
public void givenSaveTextFileOperationIntance_whenCalledExecuteMethod_thenOneAssertion() {
TextFileOperation openTextFileOperation = new SaveTextFileOperation(new TextFile("file1.txt"));
assertThat(openTextFileOperation.execute()).isEqualTo("Saving file file1.txt");
}
}

View File

@@ -0,0 +1,78 @@
package com.baeldung.command.test;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.function.Function;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.command.command.OpenTextFileOperation;
import com.baeldung.command.command.SaveTextFileOperation;
import com.baeldung.command.command.TextFileOperation;
import com.baeldung.command.invoker.TextFileOperationExecutor;
import com.baeldung.command.receiver.TextFile;
public class TextFileOperationExecutorUnitTest {
private static TextFileOperationExecutor textFileOperationExecutor;
@BeforeClass
public static void setUpTextFileOperationExecutor() {
textFileOperationExecutor = new TextFileOperationExecutor();
}
@Test
public void givenTextFileOPerationExecutorInstance_whenCalledexecuteOperationWithOpenTextOperation_thenOneAssertion() {
TextFileOperation textFileOperation = new OpenTextFileOperation(new TextFile("file1.txt"));
assertThat(textFileOperationExecutor.executeOperation(textFileOperation)).isEqualTo("Opening file file1.txt");
}
@Test
public void givenTextFileOPerationExecutorInstance_whenCalledexecuteOperationWithSaveTextOperation_thenOneAssertion() {
TextFileOperation textFileOperation = new SaveTextFileOperation(new TextFile("file1.txt"));
assertThat(textFileOperationExecutor.executeOperation(textFileOperation)).isEqualTo("Saving file file1.txt");
}
@Test
public void givenTextFileOperationExecutorInstance_whenCalledexecuteOperationWithTextFileOpenLambda_thenOneAssertion() {
assertThat(textFileOperationExecutor.executeOperation(() -> {return "Opening file file1.txt";})).isEqualTo("Opening file file1.txt");
}
@Test
public void givenTextFileOperationExecutorInstance_whenCalledexecuteOperationWithTextFileSaveLambda_thenOneAssertion() {
assertThat(textFileOperationExecutor.executeOperation(() -> {return "Saving file file1.txt";})).isEqualTo("Saving file file1.txt");
}
@Test
public void givenTextFileOperationExecutorInstance_whenCalledexecuteOperationWithTextFileOpenMethodReferenceOfExistingObject_thenOneAssertion() {
TextFile textFile = new TextFile("file1.txt");
assertThat(textFileOperationExecutor.executeOperation(textFile::open)).isEqualTo("Opening file file1.txt");
}
@Test
public void givenTextFileOperationExecutorInstance_whenCalledexecuteOperationWithTextFileSaveMethodReferenceOfExistingObject_thenOneAssertion() {
TextFile textFile = new TextFile("file1.txt");
assertThat(textFileOperationExecutor.executeOperation(textFile::save)).isEqualTo("Saving file file1.txt");
}
@Test
public void givenOpenTextFileOperationExecuteMethodReference_whenCalledApplyMethod_thenOneAssertion() {
Function<OpenTextFileOperation, String> executeMethodReference = OpenTextFileOperation::execute;
assertThat(executeMethodReference.apply(new OpenTextFileOperation(new TextFile("file1.txt")))).isEqualTo("Opening file file1.txt");
}
@Test
public void givenSaveTextFileOperationExecuteMethodReference_whenCalledApplyMethod_thenOneAssertion() {
Function<SaveTextFileOperation, String> executeMethodReference = SaveTextFileOperation::execute;
assertThat(executeMethodReference.apply(new SaveTextFileOperation(new TextFile("file1.txt")))).isEqualTo("Saving file file1.txt");
}
@Test
public void givenOpenAndSaveTextFileOperationExecutorInstance_whenCalledExecuteOperationWithLambdaExpression_thenBothAssertion() {
TextFileOperationExecutor textFileOperationExecutor = new TextFileOperationExecutor();
assertThat(textFileOperationExecutor.executeOperation(() -> "Opening file file1.txt")).isEqualTo("Opening file file1.txt");
assertThat(textFileOperationExecutor.executeOperation(() -> "Saving file file1.txt")).isEqualTo("Saving file file1.txt");
}
}

View File

@@ -0,0 +1,44 @@
package com.baeldung.command.test;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.command.receiver.TextFile;
public class TextFileUnitTest {
private static TextFile textFile;
@BeforeClass
public static void setUpTextFileInstance() {
textFile = new TextFile("file1.txt");
}
@Test
public void givenTextFileInstance_whenCalledopenMethod_thenOneAssertion() {
assertThat(textFile.open()).isEqualTo("Opening file file1.txt");
}
@Test
public void givenTextFileInstance_whenCalledwriteMethod_thenOneAssertion() {
assertThat(textFile.write()).isEqualTo("Writing to file file1.txt");
}
@Test
public void givenTextFileInstance_whenCalledsaveMethod_thenOneAssertion() {
assertThat(textFile.save()).isEqualTo("Saving file file1.txt");
}
@Test
public void givenTextFileInstance_whenCalledcopyMethod_thenOneAssertion() {
assertThat(textFile.copy()).isEqualTo("Copying file file1.txt");
}
@Test
public void givenTextFileInstance_whenCalledpasteMethod_thenOneAssertion() {
assertThat(textFile.paste()).isEqualTo("Pasting file file1.txt");
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.mediator;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class MediatorIntegrationTest {
private Button button;
private Fan fan;
@Before
public void setUp() {
this.button = new Button();
this.fan = new Fan();
PowerSupplier powerSupplier = new PowerSupplier();
Mediator mediator = new Mediator();
mediator.setButton(this.button);
mediator.setFan(fan);
mediator.setPowerSupplier(powerSupplier);
}
@Test
public void givenTurnedOffFan_whenPressingButtonTwice_fanShouldTurnOnAndOff() {
assertFalse(fan.isOn());
button.press();
assertTrue(fan.isOn());
button.press();
assertFalse(fan.isOn());
}
}

View File

@@ -0,0 +1,35 @@
package com.baeldung.nulls;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class PrimitivesAndWrapperUnitTest {
@Test
public void givenBothArgsNonNull_whenCallingWrapperSum_thenReturnSum() {
Integer sum = PrimitivesAndWrapper.wrapperSum(0, 0);
assertEquals(0, sum.intValue());
}
@Test()
public void givenOneArgIsNull_whenCallingWrapperSum_thenThrowNullPointerException() {
assertThrows(NullPointerException.class, () -> PrimitivesAndWrapper.wrapperSum(null, 2));
}
@Test()
public void givenBothArgsNull_whenCallingWrapperSum_thenThrowNullPointerException() {
assertThrows(NullPointerException.class, () -> PrimitivesAndWrapper.wrapperSum(null, null));
}
@Test()
public void givenOneArgNull_whenCallingGoodSum_thenThrowIllegalArgumentException() {
assertThrows(IllegalArgumentException.class, () -> PrimitivesAndWrapper.goodSum(null, 2));
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.nulls;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
class UsingLombokUnitTest {
private UsingLombok classUnderTest;
@BeforeEach
public void setup() {
classUnderTest = new UsingLombok();
}
@Test
public void whenNullArg_thenThrowNullPointerException() {
assertThrows(NullPointerException.class, () -> classUnderTest.accept(null));
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.nulls;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
class UsingObjectsUnitTest {
private UsingObjects classUnderTest;
@BeforeEach
public void setup() {
classUnderTest = new UsingObjects();
}
@Test
public void whenArgIsNull_thenThrowException() {
assertThrows(NullPointerException.class, () -> classUnderTest.accept(null));
}
@Test
public void whenArgIsNonNull_thenDoesNotThrowException() {
assertDoesNotThrow(() -> classUnderTest.accept("test "));
}
}

View File

@@ -0,0 +1,54 @@
package com.baeldung.nulls;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class UsingOptionalUnitTest {
private UsingOptional dataObject;
@BeforeEach
public void setup() {
dataObject = new UsingOptional();
}
@Test
void whenArgIsFalse_thenReturnEmptyResponse() {
Optional<Object> result = dataObject.process(false);
assertFalse(result.isPresent());
}
@Test
void whenArgIsTrue_thenReturnValidResponse() {
Optional<Object> result = dataObject.process(true);
assertTrue(result.isPresent());
}
@Test
void whenArgIsFalse_thenChainResponseAndThrowException() {
assertThrows(Exception.class, () -> dataObject.process(false).orElseThrow(Exception::new));
}
@Test()
void givenEmptyList_whenFindFirst_getDefaultValue() {
assertTrue(dataObject.findFirst().equalsIgnoreCase(UsingOptional.DEFAULT_VALUE));
}
@Test()
void givenEmptyList_whenFindOptionalFirst_returnsEmptyOptional() {
assertFalse(dataObject.findOptionalFirst().isPresent());
}
@Test()
void whenOptionalListFirst_returnsEmptyOptional() {
assertFalse(dataObject.optionalListFirst().isPresent());
}
}

View File

@@ -0,0 +1,42 @@
package com.baeldung.nulls;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
class UsingStringUtilsUnitTest {
private UsingStringUtils classUnderTest;
@BeforeEach
public void setup() {
classUnderTest = new UsingStringUtils();
}
@Test
public void givenArgIsNull_whenCallingAccept_throwIllegalArgumentException() {
assertThrows(IllegalArgumentException.class, () -> classUnderTest.accept(null));
}
@Test
public void givenArgIsEmpty_whenCallingAccept_throwIllegalArgumentException() {
assertThrows(IllegalArgumentException.class, () -> classUnderTest.accept(""));
}
@Test
public void givenArgIsNull_whenCallingAcceptOnlyNonBlank_throwIllegalArgumentException() {
assertThrows(IllegalArgumentException.class, () -> classUnderTest.acceptOnlyNonBlank(null));
}
@Test
public void givenArgIsEmpty_whenCallingAcceptOnlyNonBlank_throwIllegalArgumentException() {
assertThrows(IllegalArgumentException.class, () -> classUnderTest.acceptOnlyNonBlank(""));
}
@Test
public void givenArgIsBlank_whenCallingAcceptOnlyNonBlank_throwIllegalArgumentException() {
assertThrows(IllegalArgumentException.class, () -> classUnderTest.acceptOnlyNonBlank(" "));
}
}

View File

@@ -0,0 +1,47 @@
package com.baeldung.observer;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.baeldung.observer.NewsAgency;
import com.baeldung.observer.NewsChannel;
public class ObserverIntegrationTest {
@Test
public void whenChangingNewsAgencyState_thenNewsChannelNotified() {
NewsAgency observable = new NewsAgency();
NewsChannel observer = new NewsChannel();
observable.addObserver(observer);
observable.setNews("news");
assertEquals(observer.getNews(), "news");
}
@Test
public void whenChangingONewsAgencyState_thenONewsChannelNotified() {
ONewsAgency observable = new ONewsAgency();
ONewsChannel observer = new ONewsChannel();
observable.addObserver(observer);
observable.setNews("news");
assertEquals(observer.getNews(), "news");
}
@Test
public void whenChangingPCLNewsAgencyState_thenONewsChannelNotified() {
PCLNewsAgency observable = new PCLNewsAgency();
PCLNewsChannel observer = new PCLNewsChannel();
observable.addPropertyChangeListener(observer);
observable.setNews("news");
assertEquals(observer.getNews(), "news");
}
}

View File

@@ -0,0 +1,33 @@
package com.baeldung.state;
import com.baeldung.state.Package;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.instanceOf;
import org.junit.Test;
public class StatePatternUnitTest {
@Test
public void givenNewPackage_whenPackageReceived_thenStateReceived() {
Package pkg = new Package();
assertThat(pkg.getState(), instanceOf(OrderedState.class));
pkg.nextState();
assertThat(pkg.getState(), instanceOf(DeliveredState.class));
pkg.nextState();
assertThat(pkg.getState(), instanceOf(ReceivedState.class));
}
@Test
public void givenDeliveredPackage_whenPrevState_thenStateOrdered() {
Package pkg = new Package();
pkg.setState(new DeliveredState());
pkg.previousState();
assertThat(pkg.getState(), instanceOf(OrderedState.class));
}
}

View File

@@ -0,0 +1,89 @@
package com.baeldung.templatemethod.test;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.templatemethod.model.Computer;
import com.baeldung.templatemethod.model.HighEndComputerBuilder;
import com.baeldung.templatemethod.model.StandardComputerBuilder;
public class TemplateMethodPatternIntegrationTest {
private static StandardComputerBuilder standardComputerBuilder;
private static HighEndComputerBuilder highEndComputerBuilder;
@BeforeClass
public static void setUpStandardComputerBuilderInstance() {
standardComputerBuilder = new StandardComputerBuilder();
}
@BeforeClass
public static void setUpHighEndComputerBuilderInstance() {
highEndComputerBuilder = new HighEndComputerBuilder();
}
@Test
public void givenStandardMotherBoard_whenAddingMotherBoard_thenEqualAssertion() {
standardComputerBuilder.addMotherboard();
assertEquals("Standard Motherboard", standardComputerBuilder.getComputerParts().get("Motherboard"));
}
@Test
public void givenStandardMotherboard_whenSetup_thenTwoEqualAssertions() {
standardComputerBuilder.setupMotherboard();
assertEquals("Screwing the standard motherboard to the case.", standardComputerBuilder.getMotherboardSetupStatus().get(0));
assertEquals("Pluging in the power supply connectors.", standardComputerBuilder.getMotherboardSetupStatus().get(1));
}
@Test
public void givenStandardProcessor_whenAddingProcessor_thenEqualAssertion() {
standardComputerBuilder.addProcessor();
assertEquals("Standard Processor", standardComputerBuilder.getComputerParts().get("Processor"));
}
@Test
public void givenAllStandardParts_whenBuildingComputer_thenTwoParts() {
standardComputerBuilder.buildComputer();
assertEquals(2, standardComputerBuilder.getComputerParts().size());
}
@Test
public void givenAllStandardParts_whenComputerisBuilt_thenComputerInstance() {
assertThat(standardComputerBuilder.buildComputer(), instanceOf(Computer.class));
}
@Test
public void givenHighEnddMotherBoard_whenAddingMotherBoard_thenEqualAssertion() {
highEndComputerBuilder.addMotherboard();
Assert.assertEquals("High-end Motherboard", highEndComputerBuilder.getComputerParts().get("Motherboard"));
}
@Test
public void givenHighEnddMotheroboard_whenSetup_thenTwoEqualAssertions() {
highEndComputerBuilder.setupMotherboard();
assertEquals("Screwing the high-end motherboard to the case.", highEndComputerBuilder.getMotherboardSetupStatus().get(0));
assertEquals("Pluging in the power supply connectors.", highEndComputerBuilder.getMotherboardSetupStatus().get(1));
}
@Test
public void givenHightEndProcessor_whenAddingProcessor_thenEqualAssertion() {
highEndComputerBuilder.addProcessor();
assertEquals("High-end Processor", highEndComputerBuilder.getComputerParts().get("Processor"));
}
@Test
public void givenAllHighEnddParts_whenBuildingComputer_thenTwoParts() {
highEndComputerBuilder.buildComputer();
assertEquals(2, highEndComputerBuilder.getComputerParts().size());
}
@Test
public void givenAllHighEndParts_whenComputerisBuilt_thenComputerInstance() {
assertThat(standardComputerBuilder.buildComputer(), instanceOf(Computer.class));
}
}