move design patterns to new module (#4206)

* move design patterns to new module

* fix logger import
This commit is contained in:
Loredana Crusoveanu
2018-05-11 10:11:13 +03:00
committed by Grzegorz Piwowarek
parent 4a08fd1352
commit 537c1d1150
137 changed files with 200 additions and 214 deletions

View File

@@ -0,0 +1,20 @@
package com.baeldung.adapter;
import static com.baeldung.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

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,19 @@
package com.baeldung.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

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

View File

@@ -0,0 +1,14 @@
package com.baeldung.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

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

View File

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

View File

@@ -0,0 +1,11 @@
package com.baeldung.bridge;
public abstract class Shape {
protected Color color;
public Shape(Color color) {
this.color = color;
}
abstract public String draw();
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.bridge;
public class Square extends Shape {
public Square(Color color) {
super(color);
}
@Override
public String draw() {
return "Square drawn. " + color.fill();
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.bridge;
public class Triangle extends Shape {
public Triangle(Color color) {
super(color);
}
@Override
public String draw() {
return "Triangle drawn. "+ color.fill();
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,19 @@
package com.baeldung.composite;
/**
* Created by Gebruiker on 5/3/2018.
*/
public class CompositeDemo {
public static void main(String args[]) {
Department salesDepartment = new SalesDepartment(1, "Sales department");
Department financialDepartment = new FinancialDepartment(2, "Financial department");
HeadDepartment headDepartment = new HeadDepartment(3, "Head department");
headDepartment.addDepartMent(salesDepartment);
headDepartment.addDepartMent(financialDepartment);
headDepartment.printDepartmentName();
}
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.composite;
/**
* Created by Gebruiker on 5/1/2018.
*/
public interface Department {
void printDepartmentName();
}

View File

@@ -0,0 +1,35 @@
package com.baeldung.composite;
/**
* Created by Gebruiker on 5/1/2018.
*/
public class FinancialDepartment implements Department {
private Integer id;
private String name;
public FinancialDepartment(Integer id, String name) {
this.id = id;
this.name = name;
}
public void printDepartmentName() {
System.out.println(getClass().getSimpleName());
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,33 @@
package com.baeldung.composite;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Gebruiker on 5/1/2018.
*/
public class HeadDepartment implements Department {
private Integer id;
private String name;
private List<Department> childDepartments;
public HeadDepartment(Integer id, String name) {
this.id = id;
this.name = name;
this.childDepartments = new ArrayList<Department>();
}
public void printDepartmentName() {
childDepartments.forEach(Department::printDepartmentName);
}
public void addDepartMent(Department department) {
childDepartments.add(department);
}
public void removeDepartment(Department department) {
childDepartments.remove(department);
}
}

View File

@@ -0,0 +1,35 @@
package com.baeldung.composite;
/**
* Created by Gebruiker on 5/1/2018.
*/
public class SalesDepartment implements Department {
private Integer id;
private String name;
public SalesDepartment(Integer id, String name) {
this.id = id;
this.name = name;
}
public void printDepartmentName() {
System.out.println(getClass().getSimpleName());
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

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

View File

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

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

View File

@@ -0,0 +1,21 @@
package com.baeldung.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

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

View File

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

View File

@@ -0,0 +1,21 @@
package com.baeldung.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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,16 @@
package com.baeldung.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

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

View File

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

View File

@@ -0,0 +1,18 @@
package com.baeldung.decorator;
import static com.baeldung.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

@@ -0,0 +1,16 @@
package com.baeldung.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

@@ -0,0 +1,15 @@
package com.baeldung.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

@@ -0,0 +1,32 @@
package com.baeldung.facade;
import com.baeldung.facade.carsystem.*;
public class CarEngineFacade {
private static final Integer DEFAULT_COOLING_TEMP = 90;
private static final Integer MAX_ALLOWED_TEMP = 50;
private FuelInjector fuelInjector = new FuelInjector();
private AirFlowController airFlowController = new AirFlowController();
private Starter starter = new Starter();
private CoolingController coolingController = new CoolingController();
private CatalyticConverter catalyticConverter = new CatalyticConverter();
public void startEngine(){
fuelInjector.on();
airFlowController.takeAir();
fuelInjector.on();
fuelInjector.inject();
starter.start();
coolingController.setTemperatureUpperLimit(DEFAULT_COOLING_TEMP);
coolingController.run();
catalyticConverter.on();
}
public void stopEngine(){
fuelInjector.off();
catalyticConverter.off();
coolingController.cool(MAX_ALLOWED_TEMP);
coolingController.stop();
airFlowController.off();
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AirFlowController {
private static final Logger LOGGER = LoggerFactory.getLogger(AirFlowController.class);
private AirFlowMeter airFlowMeter = new AirFlowMeter();
public void takeAir() {
airFlowMeter.getMeasurements();
LOGGER.info("Air provided!");
}
public void off() {
LOGGER.info("Air controller switched off.");
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AirFlowMeter {
private static final Logger LOGGER = LoggerFactory.getLogger(AirFlowMeter.class);
public void getMeasurements() {
LOGGER.info("Getting air measurements..");
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CatalyticConverter {
private static final Logger LOGGER = LoggerFactory.getLogger(CatalyticConverter.class);
public void on() {
LOGGER.info("Catalytic Converter switched on!");
}
public void off() {
LOGGER.info("Catalytic Converter switched off!");
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CoolingController {
private static final Logger LOGGER = LoggerFactory.getLogger(CoolingController.class);
private static final Integer DEFAULT_RADIATOR_SPEED = 10;
private Integer temperatureUpperLimit;
private Radiator radiator = new Radiator();
private TemperatureSensor temperatureSensor = new TemperatureSensor();
public void setTemperatureUpperLimit(Integer temperatureUpperLimit) {
LOGGER.info("Setting temperature upper limit to {}", temperatureUpperLimit);
this.temperatureUpperLimit = temperatureUpperLimit;
}
public void run() {
LOGGER.info("Cooling Controller ready!");
radiator.setSpeed(DEFAULT_RADIATOR_SPEED);
}
public void cool(Integer maxAllowedTemp) {
LOGGER.info("Scheduled cooling with maximum allowed temperature {}", maxAllowedTemp);
temperatureSensor.getTemperature();
radiator.on();
}
public void stop() {
LOGGER.info("Stopping Cooling Controller..");
radiator.off();
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FuelInjector {
private static final Logger LOGGER = LoggerFactory.getLogger(FuelInjector.class);
private FuelPump fuelPump = new FuelPump();
public void on(){
LOGGER.info("Fuel injector ready to inject fuel.");
}
public void inject() {
fuelPump.pump();
LOGGER.info("Fuel injected.");
}
public void off() {
LOGGER.info("Stopping Fuel injector..");
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FuelPump {
private static final Logger LOGGER = LoggerFactory.getLogger(FuelPump.class);
public void pump() {
LOGGER.info("Fuel Pump is pumping fuel..");
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Radiator {
private static final Logger LOGGER = LoggerFactory.getLogger(Radiator.class);
public void on(){
LOGGER.info("Radiator switched on!");
}
public void off(){
LOGGER.info("Radiator switched off!");
}
public void setSpeed(Integer speed){
LOGGER.info("Setting radiator speed to {}",speed);
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Starter {
private static final Logger LOGGER = LoggerFactory.getLogger(Starter.class);
public void start() {
LOGGER.info("Starting..");
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TemperatureSensor {
private static final Logger LOGGER = LoggerFactory.getLogger(TemperatureSensor.class);
public void getTemperature(){
LOGGER.info("Getting temperature from the sensor..");
}
}

View File

@@ -0,0 +1,85 @@
package com.baeldung.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.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;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,20 @@
package com.baeldung.proxy;
import static com.baeldung.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

@@ -0,0 +1,13 @@
package com.baeldung.proxy;
public class ExpensiveObjectProxy implements ExpensiveObject{
private static ExpensiveObject object;
@Override
public void process() {
if(object == null) {
object = new ExpensiveObjectImpl();
}
object.process();
}
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.proxy;
public class ProxyPatternDriver {
public static void main(String[] args) {
ExpensiveObject object = new ExpensiveObjectProxy();
object.process();
object.process();
}
}

View File

@@ -0,0 +1,39 @@
package com.baeldung.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

@@ -0,0 +1,15 @@
package com.baeldung.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

@@ -0,0 +1,17 @@
package com.baeldung.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

@@ -0,0 +1,22 @@
package com.baeldung.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

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

View File

@@ -0,0 +1,15 @@
package com.baeldung.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

@@ -0,0 +1,27 @@
package com.baeldung.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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

Some files were not shown because too many files have changed in this diff Show More