Compare commits

..

1 Commits

Author SHA1 Message Date
a1cb4e708c test change 2020-05-17 21:36:06 +03:00
16 changed files with 101 additions and 363 deletions

View File

@ -1,28 +0,0 @@
# This workflow will build a Java project with Maven
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
name: Java CI with Maven
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-18.04
steps:
- uses: actions/checkout@v2
- name: Set up JDK 11
uses: actions/setup-java@v1
with:
java-version: 11
- name: Install xvfb
run: sudo apt-get install xvfb
- name: Build with Maven
run: xvfb-run mvn clean verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}

36
.travis.yml Normal file
View File

@ -0,0 +1,36 @@
language: java
dist: bionic
jdk:
- openjdk11
sudo: required
env:
global:
- secure: "DCpazS3nkLnter3sguXEAS2fC/1ZWNfM+XLyif9MfNFxlZdpni2vCD/jA0Rdpga8puQWHNVLyAec+RPFH/2qSmJ1c1UTV5MaLv8tPqwUX0VFA+1I6XoSv6oX4ldHTBWHEWqQHkRFOLoil0h0edc0tTOWQwXF8U+DLAB+HkRb4gw="
services:
- xvfb
addons:
sonarcloud:
organization: "iluwatar"
token:
secure: "FpHwMYPMkdWU6CeIB7+O3qIeIM4vJMp47UjkKK53f0w0s6tPZofZZkab+gcL2TqKSil7sFVB/AQXU1cUubflRszwcLbNsc8H2yFehD79o0o0Mqd1Dd5ip/q0KQbHkkln+InFlVLfvrLB4Xd4mlQVxbGhqpULBhXjKzFzQlRFcuU="
script:
# Because of Travis security restrictions, SonarCloud analysis cannot be run on pull requests originated from forks
# See https://docs.travis-ci.com/user/pull-requests/#pull-requests-and-security-restrictions
- 'if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then mvn clean verify; fi'
- 'if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then mvn clean verify sonar:sonar -Dsonar.projectKey=iluwatar_java-design-patterns -Dsonar.host.url=https://sonarcloud.io; fi'
after_success:
- bash update-website.sh
notifications:
email:
- iluwatar@gmail.com
webhooks:
urls:
- https://webhooks.gitter.im/e/3319623945358a093a6f
on_success: change # options: [always|never|change] default: always
on_failure: always # options: [always|never|change] default: always
on_start: never # options: [always|never|change] default: always

View File

@ -4,7 +4,8 @@
# Design patterns implemented in Java
![Java CI with Maven](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI%20with%20Maven/badge.svg)
[![Build status](https://travis-ci.org/iluwatar/java-design-patterns.svg?branch=master)](https://travis-ci.org/iluwatar/java-design-patterns)
[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md)
[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Sonarcloud Status](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=alert_status)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns)

View File

@ -45,11 +45,9 @@ public class App {
* Entry point.
*/
public static void main(String[] args) {
var host1 = new Client();
var host2 = new Client();
host1.useService(12);
host2.useService(73);
}
}

View File

@ -1,30 +0,0 @@
---
layout: pattern
title: Arrange/Act/Assert
folder: arrange-act-assert
permalink: /patterns/arrange-act-assert/
categories: Idiom
tags:
- Testing
---
## Also known as
Given/When/Then
## Intent
The Arrange/Act/Assert (AAA) is a pattern for organizing unit tests.
It breaks tests down into three clear and distinct steps:
1. Arrange: Perform the setup and initialization required for the test.
2. Act: Take action(s) required for the test.
3. Assert: Verify the outcome(s) of the test.
## Applicability
Use Arrange/Act/Assert pattern when
* you need to structure your unit tests so they're easier to read, maintain, and enhance.
## Credits
* [Arrange, Act, Assert: What is AAA Testing?](https://blog.ncrunch.net/post/arrange-act-assert-aaa-testing.aspx)
* [Bill Wake: 3A Arrange, Act, Assert](https://xp123.com/articles/3a-arrange-act-assert/)
* [Martin Fowler: GivenWhenThen](https://martinfowler.com/bliki/GivenWhenThen.html)

View File

@ -1,11 +0,0 @@
@startuml
package com.iluwatar.arrangeactassert {
class Cash {
- amount : int
~ Cash(amount : int)
~ count() : int
~ minus(subtrahend : int) : boolean
~ plus(addend : int)
}
}
@enduml

View File

@ -1,44 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
The MIT License
Copyright © 2014-2019 Ilkka Seppälä
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<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">
<parent>
<artifactId>java-design-patterns</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.23.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>arrange-act-assert</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,57 +0,0 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.arrangeactassert;
/**
* Arrange/Act/Assert (AAA) is a unit test pattern. In this simple example, we have a ({@link Cash})
* object for plus, minus and counting amount.
*/
public class Cash {
private int amount;
Cash(int amount) {
this.amount = amount;
}
//plus
void plus(int addend) {
amount += addend;
}
//minus
boolean minus(int subtrahend) {
if (amount >= subtrahend) {
amount -= subtrahend;
return true;
} else {
return false;
}
}
//count
int count() {
return amount;
}
}

View File

@ -1,99 +0,0 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.arrangeactassert;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* Arrange/Act/Assert (AAA) is a pattern for organizing unit tests. It is a way to structure your
* tests so they're easier to read, maintain and enhance.
*
* <p>It breaks tests down into three clear and distinct steps:
* <p>1. Arrange: Perform the setup and initialization required for the test.
* <p>2. Act: Take action(s) required for the test.
* <p>3. Assert: Verify the outcome(s) of the test.
*
* <p>This pattern has several significant benefits. It creates a clear separation between a test's
* setup, operations, and results. This structure makes the code easier to read and understand. If
* you place the steps in order and format your code to separate them, you can scan a test and
* quickly comprehend what it does.
*
* <p>It also enforces a certain degree of discipline when you write your tests. You have to think
* clearly about the three steps your test will perform. But it makes tests more natural to write at
* the same time since you already have an outline.
*
* <p>In ({@link CashAAATest}) we have four test methods. Each of them has only one reason to
* change and one reason to fail. In a large and complicated code base, tests that honor the single
* responsibility principle are much easier to troubleshoot.
*/
public class CashAAATest {
@Test
public void testPlus() {
//Arrange
var cash = new Cash(3);
//Act
cash.plus(4);
//Assert
assertEquals(cash.count(), 7);
}
@Test
public void testMinus() {
//Arrange
var cash = new Cash(8);
//Act
var result = cash.minus(5);
//Assert
assertTrue(result);
assertEquals(cash.count(), 3);
}
@Test
public void testInsufficientMinus() {
//Arrange
var cash = new Cash(1);
//Act
var result = cash.minus(6);
//Assert
assertFalse(result);
assertEquals(cash.count(), 1);
}
@Test
public void testUpdate() {
//Arrange
var cash = new Cash(5);
//Act
cash.plus(6);
var result = cash.minus(3);
//Assert
assertTrue(result);
assertEquals(cash.count(), 8);
}
}

View File

@ -1,59 +0,0 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.arrangeactassert;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* ({@link CashAAATest}) is an anti-example of AAA pattern. This test is functionally correct, but
* with the addition of new feature, it needs refactoring. There are an awful lot of steps in that
* test method, but it verifies the class' important behavior in just eleven lines. It violates the
* single responsibility principle. If this test method failed after a small code change, it might
* take some digging to discover why.
*/
public class CashAntiAAATest {
@Test
public void testCash() {
//initialize
var cash = new Cash(3);
//test plus
cash.plus(4);
assertEquals(cash.count(), 7);
//test minus
cash = new Cash(8);
assertTrue(cash.minus(5));
assertEquals(cash.count(), 3);
assertFalse(cash.minus(6));
assertEquals(cash.count(), 3);
//test update
cash.plus(5);
assertTrue(cash.minus(5));
assertEquals(cash.count(), 3);
}
}

View File

@ -9,7 +9,7 @@ tags:
---
## Intent
Leader Election pattern is commonly used in cloud system design. It can help to ensure that task instances select the leader instance correctly and do not conflict with each other, cause contention for shared resources, or inadvertently interfere with the work that other task instances are performing.
Leader Election pattern is commonly used in cloud system design. It can help to ensure that task instances selec the leader instance correctly and do not conflict with each other, cause contention for shared resources, or inadvertently interfere with the work that other task instances are performing.
## Class diagram
![alt text](./etc/leader-election.urm.png "Leader Election pattern class diagram")

View File

@ -37,8 +37,6 @@ import java.io.FileNotFoundException;
*/
public class App {
private static final String ERROR = "Error";
private static final String MESSAGE = "Message";
public static FileLoggerModule fileLoggerModule;
public static ConsoleLoggerModule consoleLoggerModule;
@ -73,12 +71,12 @@ public class App {
public static void execute(final String... args) {
/* Send logs on file system */
fileLoggerModule.printString(MESSAGE);
fileLoggerModule.printErrorString(ERROR);
fileLoggerModule.printString("Message");
fileLoggerModule.printErrorString("Error");
/* Send logs on console */
consoleLoggerModule.printString(MESSAGE);
consoleLoggerModule.printErrorString(ERROR);
consoleLoggerModule.printString("Message");
consoleLoggerModule.printErrorString("Error");
}
/**

View File

@ -65,7 +65,7 @@ public final class FileLoggerModuleTest {
public void testFileMessage() throws IOException {
/* Get singletong instance of File Logger Module */
final var fileLoggerModule = FileLoggerModule.getSingleton();
final FileLoggerModule fileLoggerModule = FileLoggerModule.getSingleton();
/* Prepare the essential sub modules, to perform the sequence of jobs */
fileLoggerModule.prepare();
@ -89,7 +89,7 @@ public final class FileLoggerModuleTest {
public void testNoFileMessage() throws IOException {
/* Get singletong instance of File Logger Module */
final var fileLoggerModule = FileLoggerModule.getSingleton();
final FileLoggerModule fileLoggerModule = FileLoggerModule.getSingleton();
/* Prepare the essential sub modules, to perform the sequence of jobs */
fileLoggerModule.prepare();
@ -111,7 +111,7 @@ public final class FileLoggerModuleTest {
public void testFileErrorMessage() throws FileNotFoundException {
/* Get singletong instance of File Logger Module */
final var fileLoggerModule = FileLoggerModule.getSingleton();
final FileLoggerModule fileLoggerModule = FileLoggerModule.getSingleton();
/* Prepare the essential sub modules, to perform the sequence of jobs */
fileLoggerModule.prepare();
@ -136,7 +136,7 @@ public final class FileLoggerModuleTest {
public void testNoFileErrorMessage() throws FileNotFoundException {
/* Get singletong instance of File Logger Module */
final var fileLoggerModule = FileLoggerModule.getSingleton();
final FileLoggerModule fileLoggerModule = FileLoggerModule.getSingleton();
/* Prepare the essential sub modules, to perform the sequence of jobs */
fileLoggerModule.prepare();
@ -157,7 +157,7 @@ public final class FileLoggerModuleTest {
private static final String readFirstLine(final String file) {
String firstLine = null;
try (var bufferedReader = new BufferedReader(new FileReader(file))) {
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
while (bufferedReader.ready()) {

12
pom.xml
View File

@ -54,12 +54,6 @@
<annotation-api.version>1.3.2</annotation-api.version>
<system-rules.version>1.19.0</system-rules.version>
<urm.version>1.4.8</urm.version>
<!-- SonarCloud -->
<sonar.host.url>https://sonarcloud.io</sonar.host.url>
<sonar.organization>iluwatar</sonar.organization>
<sonar.projectKey>iluwatar_java-design-patterns</sonar.projectKey>
<sonar.moduleKey>${artifactId}</sonar.moduleKey>
<sonar.projectName>Java Design Patterns</sonar.projectName>
</properties>
<modules>
<module>abstract-factory</module>
@ -190,7 +184,6 @@
<module>combinator</module>
<module>update-method</module>
<module>leader-followers</module>
<module>arrange-act-assert</module>
</modules>
<repositories>
@ -406,11 +399,6 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.7.0.1746</version>
</plugin>
</plugins>
</pluginManagement>

View File

@ -27,13 +27,15 @@ package com.iluwatar.singleton;
* <p>Thread-safe Singleton class. The instance is lazily initialized and thus needs synchronization
* mechanism.</p>
*
* <p>Note: if created by reflection then a singleton will not be created but multiple options
* in the same classloader</p>
*/
public final class ThreadSafeLazyLoadedIvoryTower {
private static volatile ThreadSafeLazyLoadedIvoryTower instance;
private static ThreadSafeLazyLoadedIvoryTower instance;
private ThreadSafeLazyLoadedIvoryTower() {
// Protect against instantiation via reflection
// protect against instantiation via reflection
if (instance == null) {
instance = this;
} else {
@ -42,16 +44,13 @@ public final class ThreadSafeLazyLoadedIvoryTower {
}
/**
* The instance doesn't get created until the method is called for the first time.
* The instance gets created only when it is called for first time. Lazy-loading
*/
public static synchronized ThreadSafeLazyLoadedIvoryTower getInstance() {
if (instance == null) {
synchronized (ThreadSafeLazyLoadedIvoryTower.class) {
if (instance == null) {
instance = new ThreadSafeLazyLoadedIvoryTower();
}
}
instance = new ThreadSafeLazyLoadedIvoryTower();
}
return instance;
}
}

46
update-website.sh Normal file
View File

@ -0,0 +1,46 @@
#!/bin/bash
#
# The MIT License
# Copyright © 2014-2019 Ilkka Seppälä
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# Clone gh-pages
git clone https://github.com/iluwatar/java-design-patterns-web.git
cd java-design-patterns-web
# Init and update submodule to latest
git submodule update --init --recursive
cd 30-seconds-of-java
git pull origin master
cd ../patterns
git pull origin master
cd ../programming-principles
git pull origin gh-pages
cd ..
# Setup Git
git config user.name "Travis-CI"
git config user.email "travis@no.reply"
git add .
git commit -m ":sparkles: :up: Automagic Update via Travis-CI"
git push --quiet "https://${GH_TOKEN}:x-oauth-basic@github.com/iluwatar/java-design-patterns-web.git" master > /dev/null 2>&1