Merge remote-tracking branch 'upstream/master' into BAEL-1754
This commit is contained in:
+20
-1
@@ -116,7 +116,7 @@
|
||||
- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings)
|
||||
- [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance)
|
||||
- [Guide to Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
|
||||
- [The Observer Pattern in Java](https://github.com/eugenp/tutorials/tree/master/core-java)
|
||||
- [The Observer Pattern in Java](http://www.baeldung.com/java-observer-pattern)
|
||||
- [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight)
|
||||
- [Object Type Casting in Java](http://www.baeldung.com/java-type-casting)
|
||||
- [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat)
|
||||
@@ -127,4 +127,23 @@
|
||||
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
|
||||
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
|
||||
- [The "final" Keyword in Java](http://www.baeldung.com/java-final)
|
||||
- [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
|
||||
- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java)
|
||||
- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
|
||||
- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums)
|
||||
- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
|
||||
- [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system)
|
||||
- [Class Loaders in Java](http://www.baeldung.com/java-classloaders)
|
||||
- [Find Sum and Average in a Java Array](http://www.baeldung.com/java-array-sum-average)
|
||||
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
|
||||
- [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern)
|
||||
- [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure)
|
||||
- [BigDecimal and BigInteger in Java](http://www.baeldung.com/java-bigdecimal-biginteger)
|
||||
- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
|
||||
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
|
||||
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
|
||||
- [Sending Emails with Java](http://www.baeldung.com/java-email)
|
||||
- [Introduction to SSL in Java](http://www.baeldung.com/java-ssl)
|
||||
- [Java KeyStore API](http://www.baeldung.com/java-keystore)
|
||||
- [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking)
|
||||
- [Guide to Java Clock Class](http://www.baeldung.com/java-clock)
|
||||
|
||||
+3
-9
@@ -9,17 +9,12 @@
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
@@ -438,7 +433,6 @@
|
||||
<log4j.version>1.2.17</log4j.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>22.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<bouncycastle.version>1.55</bouncycastle.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.designpatterns.adapter;
|
||||
|
||||
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||
|
||||
public class AdapterPatternDriver {
|
||||
|
||||
public static void main(String args[]) {
|
||||
Movable bugattiVeyron = new BugattiVeyron();
|
||||
MovableAdapter bugattiVeyronAdapter = new MovableAdapterImpl(bugattiVeyron);
|
||||
LOG.info("Bugatti Veyron Super Sport's top speed is " + bugattiVeyronAdapter.getSpeed() + " Kmph.");
|
||||
|
||||
Movable mcLaren = new McLaren();
|
||||
MovableAdapter mcLarenAdapter = new MovableAdapterImpl(mcLaren);
|
||||
LOG.info("McLaren F1 top speed is " + mcLarenAdapter.getSpeed() + " Kmph.");
|
||||
|
||||
Movable astonMartin = new AstonMartin();
|
||||
MovableAdapter astonMartinAdapter = new MovableAdapterImpl(astonMartin);
|
||||
LOG.info("McLaren F1 top speed is " + astonMartinAdapter.getSpeed() + " Kmph.");
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.designpatterns.adapter;
|
||||
|
||||
public class AstonMartin implements Movable {
|
||||
@Override
|
||||
public double getSpeed() {
|
||||
return 220;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.designpatterns.adapter;
|
||||
|
||||
public class BugattiVeyron implements Movable {
|
||||
@Override
|
||||
public double getSpeed() {
|
||||
return 268;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.designpatterns.adapter;
|
||||
|
||||
public class McLaren implements Movable {
|
||||
@Override
|
||||
public double getSpeed() {
|
||||
return 241;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.baeldung.designpatterns.adapter;
|
||||
|
||||
public interface Movable {
|
||||
// returns speed in MPH
|
||||
double getSpeed();
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.baeldung.designpatterns.adapter;
|
||||
|
||||
public interface MovableAdapter {
|
||||
// returns speed in KMPH
|
||||
double getSpeed();
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.designpatterns.adapter;
|
||||
|
||||
public class MovableAdapterImpl implements MovableAdapter {
|
||||
private Movable luxuryCars;
|
||||
|
||||
public MovableAdapterImpl(Movable luxuryCars) {
|
||||
this.luxuryCars = luxuryCars;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getSpeed() {
|
||||
double mph = luxuryCars.getSpeed();
|
||||
return convertMPHtoKMPH(mph);
|
||||
}
|
||||
|
||||
private double convertMPHtoKMPH(double mph) {
|
||||
return mph * 1.60934;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.designpatterns.bridge;
|
||||
|
||||
public class Blue implements Color {
|
||||
@Override
|
||||
public String fill() {
|
||||
return "Color is Blue";
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package com.baeldung.designpatterns.bridge;
|
||||
|
||||
public class BridgePatternDriver {
|
||||
|
||||
public static void main(String[] args) {
|
||||
//a square with red color
|
||||
Shape square = new Square(new Red());
|
||||
System.out.println(square.draw());
|
||||
|
||||
//a triangle with blue color
|
||||
Shape triangle = new Triangle(new Blue());
|
||||
System.out.println(triangle.draw());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.designpatterns.bridge;
|
||||
|
||||
public interface Color {
|
||||
String fill();
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.designpatterns.bridge;
|
||||
|
||||
public class Red implements Color {
|
||||
|
||||
@Override
|
||||
public String fill() {
|
||||
return "Color is Red";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.baeldung.designpatterns.bridge;
|
||||
|
||||
public abstract class Shape {
|
||||
protected Color color;
|
||||
|
||||
public Shape(Color color) {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
abstract public String draw();
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.designpatterns.bridge;
|
||||
|
||||
public class Square extends Shape {
|
||||
|
||||
public Square(Color color) {
|
||||
super(color);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String draw() {
|
||||
return "Square drawn. " + color.fill();
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.designpatterns.bridge;
|
||||
|
||||
public class Triangle extends Shape {
|
||||
|
||||
public Triangle(Color color) {
|
||||
super(color);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String draw() {
|
||||
return "Triangle drawn. "+ color.fill();
|
||||
}
|
||||
}
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||
|
||||
public interface AbstractFactory {
|
||||
Animal getAnimal(String toyType) ;
|
||||
Color getColor(String colorType);
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||
|
||||
public class AbstractPatternDriver {
|
||||
public static void main(String[] args) {
|
||||
AbstractFactory abstractFactory;
|
||||
|
||||
//creating a brown toy dog
|
||||
abstractFactory = FactoryProvider.getFactory("Toy");
|
||||
Animal toy = abstractFactory.getAnimal("Dog");
|
||||
|
||||
abstractFactory = FactoryProvider.getFactory("Color");
|
||||
Color color = abstractFactory.getColor("Brown");
|
||||
|
||||
String result = "A " + toy.getType() + " with " + color.getColor() + " color " + toy.makeSound();
|
||||
|
||||
System.out.println(result);
|
||||
}
|
||||
}
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||
|
||||
public interface Animal {
|
||||
String getType();
|
||||
String makeSound();
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||
|
||||
public class AnimalFactory implements AbstractFactory {
|
||||
|
||||
@Override
|
||||
public Animal getAnimal(String animalType) {
|
||||
if ("Dog".equalsIgnoreCase(animalType)) {
|
||||
return new Dog();
|
||||
} else if ("Duck".equalsIgnoreCase(animalType)) {
|
||||
return new Duck();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Color getColor(String color) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
}
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||
|
||||
public class Brown implements Color {
|
||||
|
||||
@Override
|
||||
public String getColor() {
|
||||
return "brown";
|
||||
}
|
||||
|
||||
}
|
||||
-5
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||
|
||||
public interface Color {
|
||||
String getColor();
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||
|
||||
public class ColorFactory implements AbstractFactory {
|
||||
|
||||
@Override
|
||||
public Color getColor(String colorType) {
|
||||
if ("Brown".equalsIgnoreCase(colorType)) {
|
||||
return new Brown();
|
||||
} else if ("White".equalsIgnoreCase(colorType)) {
|
||||
return new White();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Animal getAnimal(String toyType) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||
|
||||
public class Dog implements Animal {
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return "Dog";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String makeSound() {
|
||||
return "Barks";
|
||||
}
|
||||
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||
|
||||
public class Duck implements Animal {
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return "Duck";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String makeSound() {
|
||||
return "Squeks";
|
||||
}
|
||||
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||
|
||||
public class FactoryProvider {
|
||||
public static AbstractFactory getFactory(String choice){
|
||||
|
||||
if("Toy".equalsIgnoreCase(choice)){
|
||||
return new AnimalFactory();
|
||||
}
|
||||
else if("Color".equalsIgnoreCase(choice)){
|
||||
return new ColorFactory();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||
|
||||
public class White implements Color {
|
||||
|
||||
@Override
|
||||
public String getColor() {
|
||||
return "White";
|
||||
}
|
||||
|
||||
}
|
||||
-64
@@ -1,64 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.builder;
|
||||
|
||||
public class BankAccount {
|
||||
private String name;
|
||||
private String accountNumber;
|
||||
private String email;
|
||||
private boolean newsletter;
|
||||
|
||||
//The constructor that takes a builder from which it will create object
|
||||
//the access to this is only provided to builder
|
||||
private BankAccount(BankAccountBuilder builder) {
|
||||
this.name = builder.name;
|
||||
this.accountNumber = builder.accountNumber;
|
||||
this.email = builder.email;
|
||||
this.newsletter = builder.newsletter;
|
||||
}
|
||||
|
||||
public static class BankAccountBuilder {
|
||||
private String name;
|
||||
private String accountNumber;
|
||||
private String email;
|
||||
private boolean newsletter;
|
||||
|
||||
//All Mandatory parameters goes with this constructor
|
||||
public BankAccountBuilder(String name, String accountNumber) {
|
||||
this.name = name;
|
||||
this.accountNumber = accountNumber;
|
||||
}
|
||||
|
||||
//setters for optional parameters which returns this same builder
|
||||
//to support fluent design
|
||||
public BankAccountBuilder withEmail(String email) {
|
||||
this.email = email;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BankAccountBuilder wantNewsletter(boolean newsletter) {
|
||||
this.newsletter = newsletter;
|
||||
return this;
|
||||
}
|
||||
|
||||
//the actual build method that prepares and returns a BankAccount object
|
||||
public BankAccount build() {
|
||||
return new BankAccount(this);
|
||||
}
|
||||
}
|
||||
|
||||
//getters
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getAccountNumber() {
|
||||
return accountNumber;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public boolean isNewsletter() {
|
||||
return newsletter;
|
||||
}
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.builder;
|
||||
|
||||
public class BuilderPatternDriver {
|
||||
public static void main(String[] args) {
|
||||
BankAccount newAccount = new BankAccount
|
||||
.BankAccountBuilder("Jon", "22738022275")
|
||||
.withEmail("jon@example.com")
|
||||
.wantNewsletter(true)
|
||||
.build();
|
||||
|
||||
System.out.println("Name: " + newAccount.getName());
|
||||
System.out.println("AccountNumber:" + newAccount.getAccountNumber());
|
||||
System.out.println("Email: " + newAccount.getEmail());
|
||||
System.out.println("Want News letter?: " + newAccount.isNewsletter());
|
||||
}
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.factory;
|
||||
|
||||
public class FactoryDriver {
|
||||
public static void main(String[] args) {
|
||||
Polygon p;
|
||||
PolygonFactory factory = new PolygonFactory();
|
||||
|
||||
//get the shape which has 4 sides
|
||||
p = factory.getPolygon(4);
|
||||
System.out.println("The shape with 4 sides is a " + p.getType());
|
||||
|
||||
//get the shape which has 4 sides
|
||||
p = factory.getPolygon(8);
|
||||
System.out.println("The shape with 8 sides is a " + p.getType());
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.factory;
|
||||
|
||||
public class Heptagon implements Polygon {
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return "Heptagon";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.factory;
|
||||
|
||||
public class Octagon implements Polygon {
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return "Octagon";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.factory;
|
||||
|
||||
public class Pentagon implements Polygon {
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return "Pentagon";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.factory;
|
||||
|
||||
public interface Polygon {
|
||||
String getType();
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.factory;
|
||||
|
||||
public class PolygonFactory {
|
||||
public Polygon getPolygon(int numberOfSides) {
|
||||
if(numberOfSides == 3) {
|
||||
return new Triangle();
|
||||
}
|
||||
if(numberOfSides == 4) {
|
||||
return new Square();
|
||||
}
|
||||
if(numberOfSides == 5) {
|
||||
return new Pentagon();
|
||||
}
|
||||
if(numberOfSides == 7) {
|
||||
return new Heptagon();
|
||||
}
|
||||
else if(numberOfSides == 8) {
|
||||
return new Octagon();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.factory;
|
||||
|
||||
public class Square implements Polygon {
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return "Square";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.factory;
|
||||
|
||||
public class Triangle implements Polygon {
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return "Triangle";
|
||||
}
|
||||
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.singleton;
|
||||
|
||||
public class Singleton {
|
||||
private Singleton() {}
|
||||
|
||||
private static class SingletonHolder {
|
||||
public static final Singleton instance = new Singleton();
|
||||
}
|
||||
|
||||
public static Singleton getInstance() {
|
||||
return SingletonHolder.instance;
|
||||
}
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.singleton;
|
||||
|
||||
public class SingletonDriver {
|
||||
public static void main(String[] args) {
|
||||
Singleton instance = Singleton.getInstance();
|
||||
System.out.println(instance.toString());
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.designpatterns.decorator;
|
||||
|
||||
public class BubbleLights extends TreeDecorator {
|
||||
|
||||
public BubbleLights(ChristmasTree tree) {
|
||||
super(tree);
|
||||
}
|
||||
|
||||
public String decorate() {
|
||||
return super.decorate() + decorateWithBubbleLights();
|
||||
}
|
||||
|
||||
private String decorateWithBubbleLights() {
|
||||
return " with Bubble Lights";
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.designpatterns.decorator;
|
||||
|
||||
public interface ChristmasTree {
|
||||
String decorate();
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.designpatterns.decorator;
|
||||
|
||||
public class ChristmasTreeImpl implements ChristmasTree {
|
||||
|
||||
@Override
|
||||
public String decorate() {
|
||||
return "Christmas tree";
|
||||
}
|
||||
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
package com.baeldung.designpatterns.decorator;
|
||||
|
||||
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||
|
||||
public class DecoratorPatternDriver {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// christmas tree with just one Garland
|
||||
ChristmasTree tree1 = new Garland(new ChristmasTreeImpl());
|
||||
LOG.info(tree1.decorate());
|
||||
|
||||
// christmas tree with two Garlands and one Bubble lights
|
||||
ChristmasTree tree2 = new BubbleLights(new Garland(new Garland(new ChristmasTreeImpl())));
|
||||
LOG.info(tree2.decorate());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.designpatterns.decorator;
|
||||
|
||||
public class Garland extends TreeDecorator {
|
||||
|
||||
public Garland(ChristmasTree tree) {
|
||||
super(tree);
|
||||
}
|
||||
|
||||
public String decorate() {
|
||||
return super.decorate() + decorateWithGarland();
|
||||
}
|
||||
|
||||
private String decorateWithGarland() {
|
||||
return " with Garland";
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.designpatterns.decorator;
|
||||
|
||||
public abstract class TreeDecorator implements ChristmasTree {
|
||||
private ChristmasTree tree;
|
||||
|
||||
public TreeDecorator(ChristmasTree tree) {
|
||||
this.tree = tree;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String decorate() {
|
||||
return tree.decorate();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
package com.baeldung.designpatterns.flyweight;
|
||||
|
||||
import java.awt.Color;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Represents a car. This class is immutable.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*/
|
||||
@Immutable
|
||||
public class Car implements Vehicle {
|
||||
|
||||
/**
|
||||
* Logger.
|
||||
*/
|
||||
private final static Logger LOG = LoggerFactory.getLogger(Car.class);
|
||||
|
||||
/**
|
||||
* The car's engine.
|
||||
*/
|
||||
private Engine engine;
|
||||
|
||||
/**
|
||||
* The car's color.
|
||||
*/
|
||||
private Color color;
|
||||
|
||||
/**
|
||||
* Instantiates a new Car.
|
||||
*
|
||||
* @param engine
|
||||
* the {@link #engine}
|
||||
* @param color
|
||||
* the {@link #color}
|
||||
*/
|
||||
public Car(Engine engine, Color color) {
|
||||
this.engine = engine;
|
||||
this.color = color;
|
||||
|
||||
// Building a new car is a very expensive operation!
|
||||
try {
|
||||
Thread.sleep(2000);
|
||||
} catch (InterruptedException e) {
|
||||
LOG.error("Error while creating a new car", e);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see com.baeldung.designpatterns.flyweight.Vehicle#start()
|
||||
*/
|
||||
@Override
|
||||
public void start() {
|
||||
LOG.info("Car is starting!");
|
||||
engine.start();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see com.baeldung.designpatterns.flyweight.Vehicle#stop()
|
||||
*/
|
||||
@Override
|
||||
public void stop() {
|
||||
LOG.info("Car is stopping!");
|
||||
engine.stop();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see com.baeldung.designpatterns.flyweight.Vehicle#getColor()
|
||||
*/
|
||||
@Override
|
||||
public Color getColor() {
|
||||
return this.color;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.baeldung.designpatterns.flyweight;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Engine for a vehicle.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*/
|
||||
public class Engine {
|
||||
|
||||
/**
|
||||
* Logger.
|
||||
*/
|
||||
private final static Logger LOG = LoggerFactory.getLogger(Engine.class);
|
||||
|
||||
/**
|
||||
* Starts the engine.
|
||||
*/
|
||||
public void start() {
|
||||
LOG.info("Engine is starting!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the engine.
|
||||
*/
|
||||
public void stop() {
|
||||
LOG.info("Engine is stopping!");
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.designpatterns.flyweight;
|
||||
|
||||
import java.awt.Color;
|
||||
|
||||
/**
|
||||
* Interface for a vehicle.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*/
|
||||
public interface Vehicle {
|
||||
|
||||
/**
|
||||
* Starts the vehicle.
|
||||
*/
|
||||
public void start();
|
||||
|
||||
/**
|
||||
* Stops the vehicle.
|
||||
*/
|
||||
public void stop();
|
||||
|
||||
/**
|
||||
* Gets the color of the vehicle.
|
||||
*
|
||||
* @return the color of the vehicle
|
||||
*/
|
||||
public Color getColor();
|
||||
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package com.baeldung.designpatterns.flyweight;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Factory which implements the Flyweight pattern to return an existing vehicle
|
||||
* if present or a new one otherwise.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*/
|
||||
public class VehicleFactory {
|
||||
|
||||
/**
|
||||
* Stores the already created vehicles.
|
||||
*/
|
||||
private static Map<Color, Vehicle> vehiclesCache = new HashMap<Color, Vehicle>();
|
||||
|
||||
/**
|
||||
* Private constructor to prevent this class instantiation.
|
||||
*/
|
||||
private VehicleFactory() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a vehicle of the same color passed as argument. If that vehicle
|
||||
* was already created by this factory, that vehicle is returned, otherwise
|
||||
* a new one is created and returned.
|
||||
*
|
||||
* @param color
|
||||
* the color of the vehicle to return
|
||||
* @return a vehicle of the specified color
|
||||
*/
|
||||
public static Vehicle createVehicle(Color color) {
|
||||
// Looks for the requested vehicle into the cache.
|
||||
// If the vehicle doesn't exist, a new one is created.
|
||||
Vehicle newVehicle = vehiclesCache.computeIfAbsent(color, newColor -> {
|
||||
// Creates the new car.
|
||||
Engine newEngine = new Engine();
|
||||
return new Car(newEngine, newColor);
|
||||
});
|
||||
return newVehicle;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.designpatterns.observer;
|
||||
|
||||
public interface Channel {
|
||||
public void update(Object o);
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.baeldung.designpatterns.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.designpatterns.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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.designpatterns.observer;
|
||||
|
||||
import java.util.Observable;
|
||||
|
||||
public class ONewsAgency extends Observable {
|
||||
private String news;
|
||||
|
||||
public void setNews(String news) {
|
||||
this.news = news;
|
||||
setChanged();
|
||||
notifyObservers(news);
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.designpatterns.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;
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package com.baeldung.designpatterns.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;
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package com.baeldung.designpatterns.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;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.designpatterns.proxy;
|
||||
|
||||
public interface ExpensiveObject {
|
||||
void process();
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.designpatterns.proxy;
|
||||
|
||||
import static com.baeldung.designpatterns.util.LogerUtil.LOG;;
|
||||
|
||||
public class ExpensiveObjectImpl implements ExpensiveObject {
|
||||
|
||||
public ExpensiveObjectImpl() {
|
||||
heavyInitialConfiguration();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void process() {
|
||||
LOG.info("processing complete.");
|
||||
}
|
||||
|
||||
private void heavyInitialConfiguration() {
|
||||
LOG.info("Loading initial configuration...");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.designpatterns.proxy;
|
||||
|
||||
public class ExpensiveObjectProxy implements ExpensiveObject{
|
||||
private static ExpensiveObject object;
|
||||
|
||||
@Override
|
||||
public void process() {
|
||||
if(object == null) {
|
||||
object = new ExpensiveObjectImpl();
|
||||
}
|
||||
object.process();
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.designpatterns.proxy;
|
||||
|
||||
public class ProxyPatternDriver {
|
||||
public static void main(String[] args) {
|
||||
ExpensiveObject object = new ExpensiveObjectProxy();
|
||||
object.process();
|
||||
object.process();
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package com.baeldung.designpatterns.service.locator;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created by Gebruiker on 4/20/2018.
|
||||
*/
|
||||
public class Cache {
|
||||
private List<MessagingService> services;
|
||||
|
||||
public Cache(){
|
||||
services = new ArrayList<MessagingService>();
|
||||
}
|
||||
|
||||
public MessagingService getService(String serviceName){
|
||||
|
||||
for (MessagingService service : services) {
|
||||
if(service.getServiceName().equalsIgnoreCase(serviceName)){
|
||||
System.out.println("Returning cached " + serviceName + " object");
|
||||
return service;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void addService(MessagingService newService){
|
||||
boolean exists = false;
|
||||
|
||||
for (MessagingService service : services) {
|
||||
if(service.getServiceName().equalsIgnoreCase(newService.getServiceName())){
|
||||
exists = true;
|
||||
}
|
||||
}
|
||||
if(!exists){
|
||||
services.add(newService);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.designpatterns.service.locator;
|
||||
|
||||
/**
|
||||
* Created by Gebruiker on 4/20/2018.
|
||||
*/
|
||||
public class EmailService implements MessagingService {
|
||||
|
||||
public String getMessageBody() {
|
||||
return "email message";
|
||||
}
|
||||
|
||||
public String getServiceName() {
|
||||
return "EmailService";
|
||||
}
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
package com.baeldung.designpatterns.service.locator;
|
||||
|
||||
/**
|
||||
* Created by Gebruiker on 4/20/2018.
|
||||
*/
|
||||
public class InitialContext {
|
||||
|
||||
public Object lookup(String serviceName) {
|
||||
|
||||
if (serviceName.equalsIgnoreCase("EmailService")) {
|
||||
return new EmailService();
|
||||
} else if (serviceName.equalsIgnoreCase("SMSService")) {
|
||||
return new SMSService();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.designpatterns.service.locator;
|
||||
|
||||
/**
|
||||
* Created by Gebruiker on 4/20/2018.
|
||||
*/
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
MessagingService service = ServiceLocator.getService("EmailService");
|
||||
String email = service.getMessageBody();
|
||||
System.out.println(email);
|
||||
|
||||
service = ServiceLocator.getService("SMSService");
|
||||
String sms = service.getMessageBody();
|
||||
System.out.println(sms);
|
||||
|
||||
service = ServiceLocator.getService("EmailService");
|
||||
String newEmail = service.getMessageBody();
|
||||
System.out.println(newEmail);
|
||||
}
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.designpatterns.service.locator;
|
||||
|
||||
public interface MessagingService {
|
||||
|
||||
String getMessageBody();
|
||||
|
||||
String getServiceName();
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.designpatterns.service.locator;
|
||||
|
||||
/**
|
||||
* Created by Gebruiker on 4/20/2018.
|
||||
*/
|
||||
public class SMSService implements MessagingService {
|
||||
|
||||
public String getMessageBody() {
|
||||
return "sms message";
|
||||
}
|
||||
|
||||
public String getServiceName() {
|
||||
return "SMSService";
|
||||
}
|
||||
}
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
package com.baeldung.designpatterns.service.locator;
|
||||
|
||||
/**
|
||||
* Created by Gebruiker on 4/20/2018.
|
||||
*/
|
||||
public class ServiceLocator {
|
||||
|
||||
private static Cache cache;
|
||||
|
||||
static {
|
||||
cache = new Cache();
|
||||
}
|
||||
|
||||
public static MessagingService getService(String serviceName){
|
||||
|
||||
MessagingService service = cache.getService(serviceName);
|
||||
|
||||
if(service != null){
|
||||
return service;
|
||||
}
|
||||
|
||||
InitialContext context = new InitialContext();
|
||||
MessagingService service1 = (MessagingService)context.lookup(serviceName);
|
||||
cache.addService(service1);
|
||||
return service1;
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package com.baeldung.designpatterns.singleton;
|
||||
|
||||
public class ClassSingleton {
|
||||
|
||||
private static ClassSingleton INSTANCE;
|
||||
private String info = "Initial class info";
|
||||
|
||||
private ClassSingleton(){
|
||||
}
|
||||
|
||||
public static ClassSingleton getInstance(){
|
||||
if(INSTANCE == null){
|
||||
INSTANCE = new ClassSingleton();
|
||||
}
|
||||
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
// getters and setters
|
||||
|
||||
public String getInfo() {
|
||||
return info;
|
||||
}
|
||||
|
||||
public void setInfo(String info) {
|
||||
this.info = info;
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.baeldung.designpatterns.singleton;
|
||||
|
||||
public enum EnumSingleton {
|
||||
|
||||
INSTANCE("Initial enum info"); //Name of the single instance
|
||||
|
||||
private String info;
|
||||
|
||||
private EnumSingleton(String info) {
|
||||
this.info = info;
|
||||
}
|
||||
|
||||
public EnumSingleton getInstance(){
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
//getters and setters
|
||||
|
||||
public String getInfo() {
|
||||
return info;
|
||||
}
|
||||
|
||||
public void setInfo(String info) {
|
||||
this.info = info;
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package com.baeldung.designpatterns.singleton;
|
||||
|
||||
public class Sandbox {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
//Class singleton
|
||||
|
||||
ClassSingleton classSingleton1 = ClassSingleton.getInstance();
|
||||
//OurSingleton object1 = new OurSingleton(); // The constructor OurSingleton() is not visible
|
||||
|
||||
System.out.println(classSingleton1.getInfo()); //Initial class info
|
||||
|
||||
ClassSingleton classSingleton2 = ClassSingleton.getInstance();
|
||||
classSingleton2.setInfo("New class info");
|
||||
|
||||
System.out.println(classSingleton1.getInfo()); //New class info
|
||||
System.out.println(classSingleton2.getInfo()); //New class info
|
||||
|
||||
//Enum singleton
|
||||
|
||||
EnumSingleton enumSingleton1 = EnumSingleton.INSTANCE.getInstance();
|
||||
|
||||
System.out.println(enumSingleton1.getInfo()); //Initial enum info
|
||||
|
||||
EnumSingleton enumSingleton2 = EnumSingleton.INSTANCE.getInstance();
|
||||
enumSingleton2.setInfo("New enum info");
|
||||
|
||||
System.out.println(enumSingleton1.getInfo()); //New enum info
|
||||
System.out.println(enumSingleton2.getInfo()); //New enum info
|
||||
}
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package com.baeldung.designpatterns.singleton.synchronization;
|
||||
|
||||
/**
|
||||
* Double-checked locking design pattern applied to a singleton.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class DclSingleton {
|
||||
|
||||
/**
|
||||
* Current instance of the singleton.
|
||||
*/
|
||||
private static volatile DclSingleton instance;
|
||||
|
||||
/**
|
||||
* Private constructor to avoid instantiation.
|
||||
*/
|
||||
private DclSingleton() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current instance of the singleton.
|
||||
*
|
||||
* @return the current instance of the singleton
|
||||
*/
|
||||
public static DclSingleton getInstance() {
|
||||
if (instance == null) {
|
||||
synchronized (DclSingleton.class) {
|
||||
if (instance == null) {
|
||||
instance = new DclSingleton();
|
||||
}
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
}
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package com.baeldung.designpatterns.singleton.synchronization;
|
||||
|
||||
/**
|
||||
* Draconian singleton. The method to get the instance is synchronized.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class DraconianSingleton {
|
||||
|
||||
/**
|
||||
* Current instance of the singleton.
|
||||
*/
|
||||
private static DraconianSingleton instance;
|
||||
|
||||
/**
|
||||
* Private constructor to avoid instantiation.
|
||||
*/
|
||||
private DraconianSingleton() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current instance of the singleton.
|
||||
*
|
||||
* @return the current instance of the singleton
|
||||
*/
|
||||
public static synchronized DraconianSingleton getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new DraconianSingleton();
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
}
|
||||
-31
@@ -1,31 +0,0 @@
|
||||
package com.baeldung.designpatterns.singleton.synchronization;
|
||||
|
||||
/**
|
||||
* Singleton with early initialization. Inlines the singleton instance
|
||||
* initialization.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class EarlyInitSingleton {
|
||||
|
||||
/**
|
||||
* Current instance of the singleton.
|
||||
*/
|
||||
private static final EarlyInitSingleton INSTANCE = new EarlyInitSingleton();
|
||||
|
||||
/**
|
||||
* Private constructor to avoid instantiation.
|
||||
*/
|
||||
private EarlyInitSingleton() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current instance of the singleton.
|
||||
*
|
||||
* @return the current instance of the singleton
|
||||
*/
|
||||
public static EarlyInitSingleton getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.designpatterns.singleton.synchronization;
|
||||
|
||||
/**
|
||||
* Enum singleton pattern. Uses an enum to hold a reference to the singleton
|
||||
* instance.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public enum EnumSingleton {
|
||||
|
||||
/**
|
||||
* Current instance of the singleton.
|
||||
*/
|
||||
INSTANCE;
|
||||
}
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
package com.baeldung.designpatterns.singleton.synchronization;
|
||||
|
||||
/**
|
||||
* Initialization on demand singleton pattern. Uses a nested static class to
|
||||
* hold a reference to the singleton instance.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class InitOnDemandSingleton {
|
||||
|
||||
/**
|
||||
* Holder for a singleton instance.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
private static class InstanceHolder {
|
||||
|
||||
/**
|
||||
* Current instance of the singleton.
|
||||
*/
|
||||
private static final InitOnDemandSingleton INSTANCE = new InitOnDemandSingleton();
|
||||
}
|
||||
|
||||
/**
|
||||
* Private constructor to avoid instantiation.
|
||||
*/
|
||||
private InitOnDemandSingleton() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current instance of the singleton.
|
||||
*
|
||||
* @return the current instance of the singleton
|
||||
*/
|
||||
public static InitOnDemandSingleton getInstance() {
|
||||
return InstanceHolder.INSTANCE;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package com.baeldung.designpatterns.util;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.apache.log4j.PropertyConfigurator;
|
||||
|
||||
public class LogerUtil {
|
||||
|
||||
public final static Logger LOG = Logger.getLogger("GLOBAL");
|
||||
|
||||
static {
|
||||
configuration();
|
||||
}
|
||||
|
||||
private static void configuration() {
|
||||
Properties props = new Properties();
|
||||
try {
|
||||
props.load(
|
||||
new BufferedReader(
|
||||
new InputStreamReader(
|
||||
LogerUtil.class.getResourceAsStream("/log4jstructuraldp.properties")
|
||||
)
|
||||
)
|
||||
);
|
||||
} catch (IOException e) {
|
||||
System.out.println("log4jstructuraldp.properties file not configured properly");
|
||||
System.exit(0);
|
||||
}
|
||||
PropertyConfigurator.configure(props);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
package com.baeldung.numberofdigits;
|
||||
|
||||
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
public class NumberOfDigitsDriver {
|
||||
private static NumberOfDigits numberOfDigits;
|
||||
|
||||
private static Logger LOG = Logger.getLogger(NumberOfDigitsDriver.class);
|
||||
|
||||
static {
|
||||
numberOfDigits = new NumberOfDigits();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
|
||||
public class Benchmarking {
|
||||
public static void main(String[] args) throws RunnerException {
|
||||
Options opt = new OptionsBuilder()
|
||||
.include(Benchmarking.class.getSimpleName())
|
||||
.forks(1)
|
||||
.build();
|
||||
|
||||
new Runner(opt).run();
|
||||
}
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class ExecutionPlan {
|
||||
public String number = Integer.toString(Integer.MAX_VALUE);
|
||||
public boolean isNumber = false;
|
||||
public IsNumeric isNumeric= new IsNumeric();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingCoreJava(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingCoreJava(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingRegularExpressions(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingRegularExpressions(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingNumberUtils_isCreatable(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingNumberUtils_isCreatable(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingNumberUtils_isParsable(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingNumberUtils_isParsable(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingStringUtils_isNumeric(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingStringUtils_isNumeric(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingStringUtils_isNumericSpace(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingStringUtils_isNumericSpace(plan.number);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
|
||||
public class IsNumeric {
|
||||
public boolean usingCoreJava(String strNum) {
|
||||
try {
|
||||
double d = Double.parseDouble(strNum);
|
||||
} catch (NumberFormatException | NullPointerException nfe) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean usingRegularExpressions(String strNum) {
|
||||
return strNum.matches("-?\\d+(\\.\\d+)?");
|
||||
}
|
||||
|
||||
public boolean usingNumberUtils_isCreatable(String strNum) {
|
||||
return NumberUtils.isCreatable(strNum);
|
||||
}
|
||||
|
||||
public boolean usingNumberUtils_isParsable(String strNum) {
|
||||
return NumberUtils.isParsable(strNum);
|
||||
}
|
||||
|
||||
public boolean usingStringUtils_isNumeric(String strNum) {
|
||||
return StringUtils.isNumeric(strNum);
|
||||
}
|
||||
|
||||
public boolean usingStringUtils_isNumericSpace(String strNum) {
|
||||
return StringUtils.isNumericSpace(strNum);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
public class IsNumericDriver {
|
||||
private static IsNumeric isNumeric;
|
||||
private static Logger LOG = Logger.getLogger(IsNumericDriver.class);
|
||||
static {
|
||||
isNumeric =new IsNumeric();
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
LOG.info("Testing all methods...");
|
||||
|
||||
boolean res = isNumeric.usingCoreJava("1001");
|
||||
LOG.info("Using Core Java : " + res);
|
||||
|
||||
res = isNumeric.usingRegularExpressions("1001");
|
||||
LOG.info("Using Regular Expressions : " + res);
|
||||
|
||||
res =isNumeric.usingNumberUtils_isCreatable("1001");
|
||||
LOG.info("Using NumberUtils.isCreatable : " + res);
|
||||
|
||||
res =isNumeric.usingNumberUtils_isParsable("1001");
|
||||
LOG.info("Using NumberUtils.isParsable : " + res);
|
||||
|
||||
res =isNumeric.usingStringUtils_isNumeric("1001");
|
||||
LOG.info("Using StringUtils.isNumeric : " + res);
|
||||
|
||||
res =isNumeric.usingStringUtils_isNumericSpace("1001");
|
||||
LOG.info("Using StringUtils.isNumericSpace : " + res);
|
||||
}
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
package com.baeldung.designpatterns;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.designpatterns.adapter.AstonMartin;
|
||||
import com.baeldung.designpatterns.adapter.BugattiVeyron;
|
||||
import com.baeldung.designpatterns.adapter.McLaren;
|
||||
import com.baeldung.designpatterns.adapter.Movable;
|
||||
import com.baeldung.designpatterns.adapter.MovableAdapter;
|
||||
import com.baeldung.designpatterns.adapter.MovableAdapterImpl;
|
||||
|
||||
public class AdapterPatternIntegrationTest {
|
||||
@Test
|
||||
public void givenMovableAdapter_WhenConvertingMPHToKMPH_thenSuccessfullyConverted() {
|
||||
Movable bugattiVeyron = new BugattiVeyron();
|
||||
MovableAdapter bugattiVeyronAdapter = new MovableAdapterImpl(bugattiVeyron);
|
||||
assertEquals(bugattiVeyronAdapter.getSpeed(), 431.30312, 0.00001);
|
||||
|
||||
Movable mcLaren = new McLaren();
|
||||
MovableAdapter mcLarenAdapter = new MovableAdapterImpl(mcLaren);
|
||||
assertEquals(mcLarenAdapter.getSpeed(), 387.85094, 0.00001);
|
||||
|
||||
Movable astonMartin = new AstonMartin();
|
||||
MovableAdapter astonMartinAdapter = new MovableAdapterImpl(astonMartin);
|
||||
assertEquals(astonMartinAdapter.getSpeed(), 354.0548, 0.00001);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.baeldung.designpatterns;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.designpatterns.bridge.Blue;
|
||||
import com.baeldung.designpatterns.bridge.Red;
|
||||
import com.baeldung.designpatterns.bridge.Shape;
|
||||
import com.baeldung.designpatterns.bridge.Square;
|
||||
import com.baeldung.designpatterns.bridge.Triangle;
|
||||
|
||||
public class BridgePatternIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void whenBridgePatternInvoked_thenConfigSuccess() {
|
||||
//a square with red color
|
||||
Shape square = new Square(new Red());
|
||||
assertEquals(square.draw(), "Square drawn. Color is Red");
|
||||
|
||||
//a triangle with blue color
|
||||
Shape triangle = new Triangle(new Blue());
|
||||
assertEquals(triangle.draw(), "Triangle drawn. Color is Blue");
|
||||
}
|
||||
}
|
||||
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
package com.baeldung.designpatterns;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.designpatterns.decorator.BubbleLights;
|
||||
import com.baeldung.designpatterns.decorator.ChristmasTree;
|
||||
import com.baeldung.designpatterns.decorator.ChristmasTreeImpl;
|
||||
import com.baeldung.designpatterns.decorator.Garland;
|
||||
|
||||
public class DecoratorPatternIntegrationTest {
|
||||
@Test
|
||||
public void givenDecoratorPattern_WhenDecoratorsInjectedAtRuntime_thenConfigSuccess() {
|
||||
ChristmasTree tree1 = new Garland(new ChristmasTreeImpl());
|
||||
assertEquals(tree1.decorate(),
|
||||
"Christmas tree with Garland");
|
||||
|
||||
ChristmasTree tree2 = new BubbleLights(
|
||||
new Garland(new Garland(new ChristmasTreeImpl())));
|
||||
assertEquals(tree2.decorate(),
|
||||
"Christmas tree with Garland with Garland with Bubble Lights");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.baeldung.designpatterns;
|
||||
|
||||
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.log4j.spi.LoggingEvent;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.designpatterns.proxy.ExpensiveObject;
|
||||
import com.baeldung.designpatterns.proxy.ExpensiveObjectProxy;
|
||||
|
||||
public class ProxyPatternIntegrationTest {
|
||||
public static TestAppenderDP appender;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
appender = new TestAppenderDP();
|
||||
LOG.addAppender(appender);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExpensiveObjectProxy_WhenObjectInitialized_thenInitializedOnlyOnce() {
|
||||
ExpensiveObject object = new ExpensiveObjectProxy();
|
||||
object.process();
|
||||
object.process();
|
||||
|
||||
final List<LoggingEvent> log = appender.getLog();
|
||||
|
||||
assertThat((String) log.get(0).getMessage(), is("Loading initial configuration..."));
|
||||
assertThat((String) log.get(1).getMessage(), is("processing complete."));
|
||||
assertThat((String) log.get(2).getMessage(), is("processing complete."));
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
LOG.removeAppender(appender);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.designpatterns;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.log4j.AppenderSkeleton;
|
||||
import org.apache.log4j.spi.LoggingEvent;
|
||||
|
||||
public class TestAppenderDP extends AppenderSkeleton {
|
||||
private final List<LoggingEvent> log = new ArrayList<LoggingEvent>();
|
||||
|
||||
@Override
|
||||
public boolean requiresLayout() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void append(final LoggingEvent loggingEvent) {
|
||||
log.add(loggingEvent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
|
||||
public List<LoggingEvent> getLog() {
|
||||
return new ArrayList<LoggingEvent>(log);
|
||||
}
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class AbstractPatternIntegrationTest {
|
||||
@Test
|
||||
public void givenAbstractFactory_whenGettingObjects_thenSuccessful() {
|
||||
AbstractFactory abstractFactory;
|
||||
|
||||
//creating a brown toy dog
|
||||
abstractFactory = FactoryProvider.getFactory("Toy");
|
||||
Animal toy = abstractFactory.getAnimal("Dog");
|
||||
|
||||
abstractFactory = FactoryProvider.getFactory("Color");
|
||||
Color color = abstractFactory.getColor("Brown");
|
||||
|
||||
String result = "A " + toy.getType() + " with " + color.getColor() + " color " + toy.makeSound();
|
||||
assertEquals("A Dog with brown color Barks", result);
|
||||
}
|
||||
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.builder;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class BuilderPatternIntegrationTest {
|
||||
@Test
|
||||
public void whenCreatingObjectThroughBuilder_thenObjectValid() {
|
||||
BankAccount newAccount = new BankAccount
|
||||
.BankAccountBuilder("Jon", "22738022275")
|
||||
.withEmail("jon@example.com")
|
||||
.wantNewsletter(true)
|
||||
.build();
|
||||
|
||||
assertEquals(newAccount.getName(), "Jon");
|
||||
assertEquals(newAccount.getAccountNumber(), "22738022275");
|
||||
assertEquals(newAccount.getEmail(), "jon@example.com");
|
||||
assertEquals(newAccount.isNewsletter(), true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSkippingOptionalParameters_thenObjectValid() {
|
||||
BankAccount newAccount = new BankAccount
|
||||
.BankAccountBuilder("Jon", "22738022275")
|
||||
.build();
|
||||
|
||||
assertEquals(newAccount.getName(), "Jon");
|
||||
assertEquals(newAccount.getAccountNumber(), "22738022275");
|
||||
assertEquals(newAccount.getEmail(), null);
|
||||
assertEquals(newAccount.isNewsletter(), false);
|
||||
}
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.factory;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FactoryIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingFactoryForSquare_thenCorrectObjectReturned() {
|
||||
Polygon p;
|
||||
PolygonFactory factory = new PolygonFactory();
|
||||
|
||||
//get the shape which has 4 sides
|
||||
p = factory.getPolygon(4);
|
||||
String result = "The shape with 4 sides is a " + p.getType();
|
||||
|
||||
assertEquals("The shape with 4 sides is a Square", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFactoryForOctagon_thenCorrectObjectReturned() {
|
||||
Polygon p;
|
||||
PolygonFactory factory = new PolygonFactory();
|
||||
|
||||
//get the shape which has 4 sides
|
||||
p = factory.getPolygon(8);
|
||||
String result = "The shape with 8 sides is a " + p.getType();
|
||||
|
||||
assertEquals("The shape with 8 sides is a Octagon", result);
|
||||
}
|
||||
}
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
package com.baeldung.designpatterns.creational.singleton;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class SingletonIntegrationTest {
|
||||
|
||||
@Test
|
||||
/**
|
||||
* Although there is absolutely no way to determine whether
|
||||
* a class is Singleton, in this test case, we will just
|
||||
* check for two objects if they point to same instance or
|
||||
* not. We will also check for their hashcode.
|
||||
*/
|
||||
public void whenGettingMultipleObjects_thenAllPointToSame() {
|
||||
//first object
|
||||
Singleton obj1 = Singleton.getInstance();
|
||||
|
||||
//Second object
|
||||
Singleton obj2 = Singleton.getInstance();
|
||||
|
||||
assertTrue(obj1 == obj2);
|
||||
assertEquals(obj1.hashCode(), obj2.hashCode());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package com.baeldung.designpatterns.flyweight;
|
||||
|
||||
import java.awt.Color;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Unit test for {@link VehicleFactory}.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*/
|
||||
public class FlyweightUnitTest {
|
||||
|
||||
/**
|
||||
* Checks that when the {@link VehicleFactory} is asked to provide two
|
||||
* vehicles of different colors, the objects returned are different.
|
||||
*/
|
||||
@Test
|
||||
public void givenDifferentFlyweightObjects_whenEquals_thenFalse() {
|
||||
Vehicle blackVehicle = VehicleFactory.createVehicle(Color.BLACK);
|
||||
Vehicle blueVehicle = VehicleFactory.createVehicle(Color.BLUE);
|
||||
|
||||
Assert.assertNotNull("Object returned by the factory is null!", blackVehicle);
|
||||
Assert.assertNotNull("Object returned by the factory is null!", blueVehicle);
|
||||
Assert.assertNotEquals("Objects returned by the factory are equals!", blackVehicle, blueVehicle);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that when the {@link VehicleFactory} is asked to provide two
|
||||
* vehicles of the same colors, the same object is returned twice.
|
||||
*/
|
||||
@Test
|
||||
public void givenSameFlyweightObjects_whenEquals_thenTrue() {
|
||||
Vehicle blackVehicle = VehicleFactory.createVehicle(Color.BLACK);
|
||||
Vehicle anotherBlackVehicle = VehicleFactory.createVehicle(Color.BLACK);
|
||||
|
||||
Assert.assertNotNull("Object returned by the factory is null!", blackVehicle);
|
||||
Assert.assertNotNull("Object returned by the factory is null!", anotherBlackVehicle);
|
||||
Assert.assertEquals("Objects returned by the factory are not equals!", blackVehicle, anotherBlackVehicle);
|
||||
}
|
||||
}
|
||||
-47
@@ -1,47 +0,0 @@
|
||||
package com.baeldung.designpatterns.observer;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.designpatterns.observer.NewsAgency;
|
||||
import com.baeldung.designpatterns.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");
|
||||
}
|
||||
}
|
||||
-119
@@ -1,119 +0,0 @@
|
||||
package com.baeldung.designpatterns.singleton.synchronization;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Unit tests for the singleton synchronization package with the same name.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class SingletonSynchronizationUnitTest {
|
||||
|
||||
/**
|
||||
* Size of the thread pools used.
|
||||
*/
|
||||
private static final int POOL_SIZE = 1_000;
|
||||
|
||||
/**
|
||||
* Number of tasks to submit.
|
||||
*/
|
||||
private static final int TASKS_TO_SUBMIT = 1_000_000;
|
||||
|
||||
/**
|
||||
* Tests the thread-safety of {@link DraconianSingleton}.
|
||||
*/
|
||||
@Test
|
||||
public void givenDraconianSingleton_whenMultithreadInstancesEquals_thenTrue() {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
|
||||
Set<DraconianSingleton> resultSet = Collections.synchronizedSet(new HashSet<DraconianSingleton>());
|
||||
|
||||
// Submits the instantiation tasks.
|
||||
for (int i = 0; i < TASKS_TO_SUBMIT; i++) {
|
||||
executor.submit(() -> resultSet.add(DraconianSingleton.getInstance()));
|
||||
}
|
||||
|
||||
// Since the instance of the object we inserted into the set is always
|
||||
// the same, the size should be one.
|
||||
Assert.assertEquals(1, resultSet.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the thread-safety of {@link DclSingleton}.
|
||||
*/
|
||||
@Test
|
||||
public void givenDclSingleton_whenMultithreadInstancesEquals_thenTrue() {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
|
||||
Set<DclSingleton> resultSet = Collections.synchronizedSet(new HashSet<DclSingleton>());
|
||||
|
||||
// Submits the instantiation tasks.
|
||||
for (int i = 0; i < TASKS_TO_SUBMIT; i++) {
|
||||
executor.submit(() -> resultSet.add(DclSingleton.getInstance()));
|
||||
}
|
||||
|
||||
// Since the instance of the object we inserted into the set is always
|
||||
// the same, the size should be one.
|
||||
Assert.assertEquals(1, resultSet.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the thread-safety of {@link EarlyInitSingleton}.
|
||||
*/
|
||||
@Test
|
||||
public void givenEarlyInitSingleton_whenMultithreadInstancesEquals_thenTrue() {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
|
||||
Set<EarlyInitSingleton> resultSet = Collections.synchronizedSet(new HashSet<EarlyInitSingleton>());
|
||||
|
||||
// Submits the instantiation tasks.
|
||||
for (int i = 0; i < TASKS_TO_SUBMIT; i++) {
|
||||
executor.submit(() -> resultSet.add(EarlyInitSingleton.getInstance()));
|
||||
}
|
||||
|
||||
// Since the instance of the object we inserted into the set is always
|
||||
// the same, the size should be one.
|
||||
Assert.assertEquals(1, resultSet.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the thread-safety of {@link InitOnDemandSingleton}.
|
||||
*/
|
||||
@Test
|
||||
public void givenInitOnDemandSingleton_whenMultithreadInstancesEquals_thenTrue() {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
|
||||
Set<InitOnDemandSingleton> resultSet = Collections.synchronizedSet(new HashSet<InitOnDemandSingleton>());
|
||||
|
||||
// Submits the instantiation tasks.
|
||||
for (int i = 0; i < TASKS_TO_SUBMIT; i++) {
|
||||
executor.submit(() -> resultSet.add(InitOnDemandSingleton.getInstance()));
|
||||
}
|
||||
|
||||
// Since the instance of the object we inserted into the set is always
|
||||
// the same, the size should be one.
|
||||
Assert.assertEquals(1, resultSet.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the thread-safety of {@link EnumSingleton}.
|
||||
*/
|
||||
@Test
|
||||
public void givenEnumSingleton_whenMultithreadInstancesEquals_thenTrue() {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
|
||||
Set<EnumSingleton> resultSet = Collections.synchronizedSet(new HashSet<EnumSingleton>());
|
||||
|
||||
// Submits the instantiation tasks.
|
||||
for (int i = 0; i < TASKS_TO_SUBMIT; i++) {
|
||||
executor.submit(() -> resultSet.add(EnumSingleton.INSTANCE));
|
||||
}
|
||||
|
||||
// Since the instance of the object we inserted into the set is always
|
||||
// the same, the size should be one.
|
||||
Assert.assertEquals(1, resultSet.size());
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CoreJavaIsNumericUnitTest {
|
||||
public static boolean isNumeric(String strNum) {
|
||||
try {
|
||||
double d = Double.parseDouble(strNum);
|
||||
} catch (NumberFormatException | NullPointerException nfe) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCoreJava_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(isNumeric("22")).isTrue();
|
||||
assertThat(isNumeric("5.05")).isTrue();
|
||||
assertThat(isNumeric("-200")).isTrue();
|
||||
assertThat(isNumeric("10.0d")).isTrue();
|
||||
assertThat(isNumeric(" 22 ")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(isNumeric(null)).isFalse();
|
||||
assertThat(isNumeric("")).isFalse();
|
||||
assertThat(isNumeric("abc")).isFalse();
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NumberUtilsIsCreatableUnitTest {
|
||||
@Test
|
||||
public void givenApacheCommons_whenUsingIsParsable_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(NumberUtils.isCreatable("22")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("5.05")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("-200")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("10.0d")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("1000L")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("0xFF")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("07")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("2.99e+8")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(NumberUtils.isCreatable(null)).isFalse();
|
||||
assertThat(NumberUtils.isCreatable("")).isFalse();
|
||||
assertThat(NumberUtils.isCreatable("abc")).isFalse();
|
||||
assertThat(NumberUtils.isCreatable(" 22 ")).isFalse();
|
||||
assertThat(NumberUtils.isCreatable("09")).isFalse();
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NumberUtilsIsParsableUnitTest {
|
||||
@Test
|
||||
public void givenApacheCommons_whenUsingIsParsable_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(NumberUtils.isParsable("22")).isTrue();
|
||||
assertThat(NumberUtils.isParsable("-23")).isTrue();
|
||||
assertThat(NumberUtils.isParsable("2.2")).isTrue();
|
||||
assertThat(NumberUtils.isParsable("09")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(NumberUtils.isParsable(null)).isFalse();
|
||||
assertThat(NumberUtils.isParsable("")).isFalse();
|
||||
assertThat(NumberUtils.isParsable("6.2f")).isFalse();
|
||||
assertThat(NumberUtils.isParsable("9.8d")).isFalse();
|
||||
assertThat(NumberUtils.isParsable("22L")).isFalse();
|
||||
assertThat(NumberUtils.isParsable("0xFF")).isFalse();
|
||||
assertThat(NumberUtils.isParsable("2.99e+8")).isFalse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RegularExpressionsUnitTest {
|
||||
public static boolean isNumeric(String strNum) {
|
||||
return strNum.matches("-?\\d+(\\.\\d+)?");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingRegularExpressions_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(isNumeric("22")).isTrue();
|
||||
assertThat(isNumeric("5.05")).isTrue();
|
||||
assertThat(isNumeric("-200")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(isNumeric("abc")).isFalse();
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StringUtilsIsNumericSpaceUnitTest {
|
||||
@Test
|
||||
public void givenApacheCommons_whenUsingIsNumericSpace_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(StringUtils.isNumericSpace("123")).isTrue();
|
||||
assertThat(StringUtils.isNumericSpace("١٢٣")).isTrue();
|
||||
assertThat(StringUtils.isNumericSpace("")).isTrue();
|
||||
assertThat(StringUtils.isNumericSpace(" ")).isTrue();
|
||||
assertThat(StringUtils.isNumericSpace("12 3")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(StringUtils.isNumericSpace(null)).isFalse();
|
||||
assertThat(StringUtils.isNumericSpace("ab2c")).isFalse();
|
||||
assertThat(StringUtils.isNumericSpace("12.3")).isFalse();
|
||||
assertThat(StringUtils.isNumericSpace("-123")).isFalse();
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StringUtilsIsNumericUnitTest {
|
||||
@Test
|
||||
public void givenApacheCommons_whenUsingIsNumeric_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(StringUtils.isNumeric("123")).isTrue();
|
||||
assertThat(StringUtils.isNumeric("١٢٣")).isTrue();
|
||||
assertThat(StringUtils.isNumeric("१२३")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(StringUtils.isNumeric(null)).isFalse();
|
||||
assertThat(StringUtils.isNumeric("")).isFalse();
|
||||
assertThat(StringUtils.isNumeric(" ")).isFalse();
|
||||
assertThat(StringUtils.isNumeric("12 3")).isFalse();
|
||||
assertThat(StringUtils.isNumeric("ab2c")).isFalse();
|
||||
assertThat(StringUtils.isNumeric("12.3")).isFalse();
|
||||
assertThat(StringUtils.isNumeric("-123")).isFalse();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user