Merge remote-tracking branch 'upstream/master' into BAEL-1754

This commit is contained in:
mherbaghinyan
2018-05-12 11:11:39 +04:00
486 changed files with 7678 additions and 2040 deletions

View File

@@ -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.");
}
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.designpatterns.adapter;
public class AstonMartin implements Movable {
@Override
public double getSpeed() {
return 220;
}
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.designpatterns.adapter;
public class BugattiVeyron implements Movable {
@Override
public double getSpeed() {
return 268;
}
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.designpatterns.adapter;
public class McLaren implements Movable {
@Override
public double getSpeed() {
return 241;
}
}

View File

@@ -1,6 +0,0 @@
package com.baeldung.designpatterns.adapter;
public interface Movable {
// returns speed in MPH
double getSpeed();
}

View File

@@ -1,6 +0,0 @@
package com.baeldung.designpatterns.adapter;
public interface MovableAdapter {
// returns speed in KMPH
double getSpeed();
}

View File

@@ -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;
}
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.designpatterns.bridge;
public class Blue implements Color {
@Override
public String fill() {
return "Color is Blue";
}
}

View File

@@ -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());
}
}

View File

@@ -1,5 +0,0 @@
package com.baeldung.designpatterns.bridge;
public interface Color {
String fill();
}

View File

@@ -1,10 +0,0 @@
package com.baeldung.designpatterns.bridge;
public class Red implements Color {
@Override
public String fill() {
return "Color is Red";
}
}

View File

@@ -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();
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -1,6 +0,0 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public interface AbstractFactory {
Animal getAnimal(String toyType) ;
Color getColor(String colorType);
}

View File

@@ -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);
}
}

View File

@@ -1,6 +0,0 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public interface Animal {
String getType();
String makeSound();
}

View File

@@ -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();
}
}

View File

@@ -1,10 +0,0 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public class Brown implements Color {
@Override
public String getColor() {
return "brown";
}
}

View File

@@ -1,5 +0,0 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public interface Color {
String getColor();
}

View File

@@ -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();
}
}

View File

@@ -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";
}
}

View File

@@ -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";
}
}

View File

@@ -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;
}
}

View File

@@ -1,10 +0,0 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public class White implements Color {
@Override
public String getColor() {
return "White";
}
}

View File

@@ -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;
}
}

View File

@@ -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());
}
}

View File

@@ -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());
}
}

View File

@@ -1,10 +0,0 @@
package com.baeldung.designpatterns.creational.factory;
public class Heptagon implements Polygon {
@Override
public String getType() {
return "Heptagon";
}
}

View File

@@ -1,10 +0,0 @@
package com.baeldung.designpatterns.creational.factory;
public class Octagon implements Polygon {
@Override
public String getType() {
return "Octagon";
}
}

View File

@@ -1,10 +0,0 @@
package com.baeldung.designpatterns.creational.factory;
public class Pentagon implements Polygon {
@Override
public String getType() {
return "Pentagon";
}
}

View File

@@ -1,5 +0,0 @@
package com.baeldung.designpatterns.creational.factory;
public interface Polygon {
String getType();
}

View File

@@ -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;
}
}

View File

@@ -1,10 +0,0 @@
package com.baeldung.designpatterns.creational.factory;
public class Square implements Polygon {
@Override
public String getType() {
return "Square";
}
}

View File

@@ -1,10 +0,0 @@
package com.baeldung.designpatterns.creational.factory;
public class Triangle implements Polygon {
@Override
public String getType() {
return "Triangle";
}
}

View File

@@ -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;
}
}

View File

@@ -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());
}
}

View File

@@ -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";
}
}

View File

@@ -1,5 +0,0 @@
package com.baeldung.designpatterns.decorator;
public interface ChristmasTree {
String decorate();
}

View File

@@ -1,10 +0,0 @@
package com.baeldung.designpatterns.decorator;
public class ChristmasTreeImpl implements ChristmasTree {
@Override
public String decorate() {
return "Christmas tree";
}
}

View File

@@ -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());
}
}

View File

@@ -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";
}
}

View File

@@ -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();
}
}

View File

@@ -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;
}
}

View File

@@ -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!");
}
}

View File

@@ -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();
}

View File

@@ -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;
}
}

View File

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

View File

@@ -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);
}
}
}

View File

@@ -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;
}
}

View File

@@ -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);
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -1,5 +0,0 @@
package com.baeldung.designpatterns.proxy;
public interface ExpensiveObject {
void process();
}

View File

@@ -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...");
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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);
}
}
}

View File

@@ -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";
}
}

View File

@@ -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;
}
}

View File

@@ -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);
}
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.designpatterns.service.locator;
public interface MessagingService {
String getMessageBody();
String getServiceName();
}

View File

@@ -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";
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}

View File

@@ -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;
}
}

View File

@@ -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);
}
}

View File

@@ -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();
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}