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

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

* [JAVA-14174] naming fixes

Co-authored-by: panagiotiskakos <panagiotis.kakos@libra-is.com>
This commit is contained in:
panos-kakos
2022-09-19 07:44:14 +01:00
committed by GitHub
parent 74dcaa0935
commit 63a9bfbad9
518 changed files with 32 additions and 32 deletions
@@ -0,0 +1,12 @@
package com.baeldung.constructorsstaticfactorymethods.application;
import com.baeldung.constructorsstaticfactorymethods.entities.User;
public class Application {
public static void main(String[] args) {
User user1 = User.createWithDefaultCountry("John", "john@domain.com");
User user2 = User.createWithLoggedInstantiationTime("John", "john@domain.com", "Argentina");
User user3 = User.getSingletonInstance("John", "john@domain.com", "Argentina");
}
}
@@ -0,0 +1,56 @@
package com.baeldung.constructorsstaticfactorymethods.entities;
import java.time.LocalTime;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class User {
private static volatile User instance = null;
private static final Logger LOGGER = Logger.getLogger(User.class.getName());
private final String name;
private final String email;
private final String country;
public static User createWithDefaultCountry(String name, String email) {
return new User(name, email, "Argentina");
}
public static User createWithLoggedInstantiationTime(String name, String email, String country) {
LOGGER.log(Level.INFO, "Creating User instance at : {0}", LocalTime.now());
return new User(name, email, country);
}
public static User getSingletonInstance(String name, String email, String country) {
if (instance == null) {
synchronized (User.class) {
if (instance == null) {
instance = new User(name, email, country);
}
}
}
return instance;
}
private User(String name, String email, String country) {
this.name = name;
this.email = email;
this.country = country;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getCountry() {
return country;
}
}
@@ -0,0 +1,5 @@
package com.baeldung.creational.abstractfactory;
public interface AbstractFactory<T> {
T create(String type) ;
}
@@ -0,0 +1,18 @@
package com.baeldung.creational.abstractfactory;
public class AbstractPatternDriver {
public static void main(String[] args) {
AbstractFactory abstractFactory;
//creating a brown toy dog
abstractFactory = FactoryProvider.getFactory("Toy");
Animal toy =(Animal) abstractFactory.create("Dog");
abstractFactory = FactoryProvider.getFactory("Color");
Color color =(Color) abstractFactory.create("Brown");
String result = "A " + toy.getType() + " with " + color.getColor() + " color " + toy.makeSound();
System.out.println(result);
}
}
@@ -0,0 +1,6 @@
package com.baeldung.creational.abstractfactory;
public interface Animal {
String getType();
String makeSound();
}
@@ -0,0 +1,16 @@
package com.baeldung.creational.abstractfactory;
public class AnimalFactory implements AbstractFactory<Animal> {
@Override
public Animal create(String animalType) {
if ("Dog".equalsIgnoreCase(animalType)) {
return new Dog();
} else if ("Duck".equalsIgnoreCase(animalType)) {
return new Duck();
}
return null;
}
}
@@ -0,0 +1,10 @@
package com.baeldung.creational.abstractfactory;
public class Brown implements Color {
@Override
public String getColor() {
return "brown";
}
}
@@ -0,0 +1,5 @@
package com.baeldung.creational.abstractfactory;
public interface Color {
String getColor();
}
@@ -0,0 +1,16 @@
package com.baeldung.creational.abstractfactory;
public class ColorFactory implements AbstractFactory<Color> {
@Override
public Color create(String colorType) {
if ("Brown".equalsIgnoreCase(colorType)) {
return new Brown();
} else if ("White".equalsIgnoreCase(colorType)) {
return new White();
}
return null;
}
}
@@ -0,0 +1,15 @@
package com.baeldung.creational.abstractfactory;
public class Dog implements Animal {
@Override
public String getType() {
return "Dog";
}
@Override
public String makeSound() {
return "Barks";
}
}
@@ -0,0 +1,15 @@
package com.baeldung.creational.abstractfactory;
public class Duck implements Animal {
@Override
public String getType() {
return "Duck";
}
@Override
public String makeSound() {
return "Squeks";
}
}
@@ -0,0 +1,15 @@
package com.baeldung.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;
}
}
@@ -0,0 +1,10 @@
package com.baeldung.creational.abstractfactory;
public class White implements Color {
@Override
public String getColor() {
return "White";
}
}
@@ -0,0 +1,64 @@
package com.baeldung.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;
}
}
@@ -0,0 +1,16 @@
package com.baeldung.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());
}
}
@@ -0,0 +1,16 @@
package com.baeldung.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());
}
}
@@ -0,0 +1,10 @@
package com.baeldung.creational.factory;
public class Heptagon implements Polygon {
@Override
public String getType() {
return "Heptagon";
}
}
@@ -0,0 +1,10 @@
package com.baeldung.creational.factory;
public class Octagon implements Polygon {
@Override
public String getType() {
return "Octagon";
}
}
@@ -0,0 +1,10 @@
package com.baeldung.creational.factory;
public class Pentagon implements Polygon {
@Override
public String getType() {
return "Pentagon";
}
}
@@ -0,0 +1,5 @@
package com.baeldung.creational.factory;
public interface Polygon {
String getType();
}
@@ -0,0 +1,22 @@
package com.baeldung.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;
}
}
@@ -0,0 +1,10 @@
package com.baeldung.creational.factory;
public class Square implements Polygon {
@Override
public String getType() {
return "Square";
}
}
@@ -0,0 +1,10 @@
package com.baeldung.creational.factory;
public class Triangle implements Polygon {
@Override
public String getType() {
return "Triangle";
}
}
@@ -0,0 +1,13 @@
package com.baeldung.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;
}
}
@@ -0,0 +1,8 @@
package com.baeldung.creational.singleton;
public class SingletonDriver {
public static void main(String[] args) {
Singleton instance = Singleton.getInstance();
System.out.println(instance.toString());
}
}
@@ -0,0 +1,82 @@
package com.baeldung.flyweight;
import java.awt.Color;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Represents a car. This class is immutable.
*
* @author Donato Rimenti
*/
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.flyweight.Vehicle#start()
*/
@Override
public void start() {
LOG.info("Car is starting!");
engine.start();
}
/*
* (non-Javadoc)
*
* @see com.baeldung.flyweight.Vehicle#stop()
*/
@Override
public void stop() {
LOG.info("Car is stopping!");
engine.stop();
}
/*
* (non-Javadoc)
*
* @see com.baeldung.flyweight.Vehicle#getColor()
*/
@Override
public Color getColor() {
return this.color;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.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!");
}
}
@@ -0,0 +1,29 @@
package com.baeldung.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();
}
@@ -0,0 +1,45 @@
package com.baeldung.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;
}
}
@@ -0,0 +1,25 @@
package com.baeldung.freebuilder;
import org.inferred.freebuilder.FreeBuilder;
import java.util.Optional;
@FreeBuilder
public interface Address {
Optional<String> getAddressLine1();
Optional<String> getAddressLine2();
Optional<String> getAddressLine3();
String getCity();
Optional<String> getState();
Optional<Long> getPinCode();
class Builder extends Address_Builder {
}
}
@@ -0,0 +1,65 @@
package com.baeldung.freebuilder;
import org.inferred.freebuilder.FreeBuilder;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@FreeBuilder
public interface Employee {
String getName();
int getAge();
String getDepartment();
String getRole();
String getSupervisorName();
String getDesignation();
String getEmail();
long getPhoneNumber();
Optional<Boolean> getPermanent();
Optional<String> getDateOfJoining();
@Nullable
String getCurrentProject();
Address getAddress();
List<Long> getAccessTokens();
Map<String, Long> getAssetsSerialIdMapping();
Optional<Double> getSalaryInUSD();
class Builder extends Employee_Builder {
public Builder() {
// setting default value for department
setDepartment("Builder Pattern");
}
@Override
public Builder setEmail(String email) {
if (checkValidEmail(email))
return super.setEmail(email);
else
throw new IllegalArgumentException("Invalid email");
}
private boolean checkValidEmail(String email) {
return email.contains("@");
}
}
}
@@ -0,0 +1,53 @@
package com.baeldung.freebuilder.builder;
public class Employee {
private final String name;
private final int age;
private final String department;
private Employee(String name, int age, String department) {
this.name = name;
this.age = age;
this.department = department;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getDepartment() {
return department;
}
public static class Builder {
private String name;
private int age;
private String department;
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setAge(int age) {
this.age = age;
return this;
}
public Builder setDepartment(String department) {
this.department = department;
return this;
}
public Employee build() {
return new Employee(name, age, department);
}
}
}
@@ -0,0 +1,23 @@
package com.baeldung.prototype;
public class PineTree extends Tree {
private String type;
public PineTree(double mass, double height) {
super(mass, height);
this.type = "Pine";
}
public String getType() {
return type;
}
@Override
public Tree copy() {
PineTree pineTreeClone = new PineTree(this.getMass(), this.getHeight());
pineTreeClone.setPosition(this.getPosition());
return pineTreeClone;
}
}
@@ -0,0 +1,23 @@
package com.baeldung.prototype;
public class PlasticTree extends Tree {
private String name;
public PlasticTree(double mass, double height) {
super(mass, height);
this.name = "PlasticTree";
}
public String getName() {
return name;
}
@Override
public Tree copy() {
PlasticTree plasticTreeClone = new PlasticTree(this.getMass(), this.getHeight());
plasticTreeClone.setPosition(this.getPosition());
return plasticTreeClone;
}
}
@@ -0,0 +1,51 @@
package com.baeldung.prototype;
public final class Position {
private final int x;
private final int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Position other = (Position) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
@Override
public String toString() {
return "Position [x=" + x + ", y=" + y + "]";
}
}
@@ -0,0 +1,44 @@
package com.baeldung.prototype;
public abstract class Tree {
private double mass;
private double height;
private Position position;
public Tree(double mass, double height) {
this.mass = mass;
this.height = height;
}
public void setMass(double mass) {
this.mass = mass;
}
public void setHeight(double height) {
this.height = height;
}
public void setPosition(Position position) {
this.position = position;
}
public double getMass() {
return mass;
}
public double getHeight() {
return height;
}
public Position getPosition() {
return position;
}
@Override
public String toString() {
return "Tree [mass=" + mass + ", height=" + height + ", position=" + position + "]";
}
public abstract Tree copy();
}
@@ -0,0 +1,17 @@
package com.baeldung.reducingIfElse;
public class AddCommand implements Command {
private int a;
private int b;
public AddCommand(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public Integer execute() {
return a + b;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.reducingIfElse;
public class AddRule implements Rule {
private int result;
@Override
public boolean evaluate(Expression expression) {
boolean evalResult = false;
if (expression.getOperator() == Operator.ADD) {
this.result = expression.getX() + expression.getY();
evalResult = true;
}
return evalResult;
}
@Override
public Result getResult() {
return new Result(result);
}
}
@@ -0,0 +1,8 @@
package com.baeldung.reducingIfElse;
public class Addition implements Operation {
@Override
public int apply(int a, int b) {
return a + b;
}
}
@@ -0,0 +1,83 @@
package com.baeldung.reducingIfElse;
public class Calculator {
public int calculate(int a, int b, String operator) {
int result = Integer.MIN_VALUE;
if ("add".equals(operator)) {
result = a + b;
} else if ("multiply".equals(operator)) {
result = a * b;
} else if ("divide".equals(operator)) {
result = a / b;
} else if ("subtract".equals(operator)) {
result = a - b;
} else if ("modulo".equals(operator)) {
result = a % b;
}
return result;
}
public int calculateUsingSwitch(int a, int b, String operator) {
int result = 0;
switch (operator) {
case "add":
result = a + b;
break;
case "multiply":
result = a * b;
break;
case "divide":
result = a / b;
break;
case "subtract":
result = a - b;
break;
case "modulo":
result = a % b;
break;
default:
result = Integer.MIN_VALUE;
}
return result;
}
public int calculateUsingSwitch(int a, int b, Operator operator) {
int result = 0;
switch (operator) {
case ADD:
result = a + b;
break;
case MULTIPLY:
result = a * b;
break;
case DIVIDE:
result = a / b;
break;
case SUBTRACT:
result = a - b;
break;
case MODULO:
result = a % b;
break;
default:
result = Integer.MIN_VALUE;
}
return result;
}
public int calculate(int a, int b, Operator operator) {
return operator.apply(a, b);
}
public int calculateUsingFactory(int a, int b, String operation) {
Operation targetOperation = OperatorFactory.getOperation(operation)
.orElseThrow(() -> new IllegalArgumentException("Invalid Operator"));
return targetOperation.apply(a, b);
}
public int calculate(Command command) {
return command.execute();
}
}
@@ -0,0 +1,5 @@
package com.baeldung.reducingIfElse;
public interface Command {
Integer execute();
}
@@ -0,0 +1,7 @@
package com.baeldung.reducingIfElse;
public class Division implements Operation {
@Override public int apply(int a, int b) {
return a / b;
}
}
@@ -0,0 +1,26 @@
package com.baeldung.reducingIfElse;
public class Expression {
private Integer x;
private Integer y;
private Operator operator;
public Expression(Integer x, Integer y, Operator operator) {
this.x = x;
this.y = y;
this.operator = operator;
}
public Integer getX() {
return x;
}
public Integer getY() {
return y;
}
public Operator getOperator() {
return operator;
}
}
@@ -0,0 +1,7 @@
package com.baeldung.reducingIfElse;
public class Modulo implements Operation {
@Override public int apply(int a, int b) {
return a % b;
}
}
@@ -0,0 +1,7 @@
package com.baeldung.reducingIfElse;
public class Multiplication implements Operation {
@Override public int apply(int a, int b) {
return 0;
}
}
@@ -0,0 +1,5 @@
package com.baeldung.reducingIfElse;
public interface Operation {
int apply(int a, int b);
}
@@ -0,0 +1,41 @@
package com.baeldung.reducingIfElse;
public enum Operator {
ADD {
@Override
public int apply(int a, int b) {
return a + b;
}
},
MULTIPLY {
@Override
public int apply(int a, int b) {
return a * b;
}
},
SUBTRACT {
@Override
public int apply(int a, int b) {
return a - b;
}
},
DIVIDE {
@Override
public int apply(int a, int b) {
return a / b;
}
},
MODULO {
@Override
public int apply(int a, int b) {
return a % b;
}
};
public abstract int apply(int a, int b);
}
@@ -0,0 +1,21 @@
package com.baeldung.reducingIfElse;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class OperatorFactory {
static Map<String, Operation> operationMap = new HashMap<>();
static {
operationMap.put("add", new Addition());
operationMap.put("divide", new Division());
operationMap.put("multiply", new Multiplication());
operationMap.put("subtract", new Subtraction());
operationMap.put("modulo", new Modulo());
}
public static Optional<Operation> getOperation(String operation) {
return Optional.ofNullable(operationMap.get(operation));
}
}
@@ -0,0 +1,13 @@
package com.baeldung.reducingIfElse;
public class Result {
int value;
public Result(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
@@ -0,0 +1,8 @@
package com.baeldung.reducingIfElse;
public interface Rule {
boolean evaluate(Expression expression);
Result getResult();
}
@@ -0,0 +1,24 @@
package com.baeldung.reducingIfElse;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class RuleEngine {
private static List<Rule> rules = new ArrayList<>();
static {
rules.add(new AddRule());
}
public Result process(Expression expression) {
Rule rule = rules.stream()
.filter(r -> r.evaluate(expression))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Expression does not matches any Rule"));
return rule.getResult();
}
}
@@ -0,0 +1,7 @@
package com.baeldung.reducingIfElse;
public class Subtraction implements Operation {
@Override public int apply(int a, int b) {
return a - b;
}
}
@@ -0,0 +1,28 @@
package com.baeldung.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;
}
}
@@ -0,0 +1,26 @@
package com.baeldung.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;
}
}
@@ -0,0 +1,32 @@
package com.baeldung.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
}
}
@@ -0,0 +1,38 @@
package com.baeldung.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;
}
}
@@ -0,0 +1,34 @@
package com.baeldung.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;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.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;
}
}
@@ -0,0 +1,16 @@
package com.baeldung.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;
}
@@ -0,0 +1,41 @@
package com.baeldung.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;
}
}