Java Design patterns

This commit is contained in:
Javadevjournal
2022-03-20 09:31:02 -07:00
parent aa5cb0a341
commit 3f49ebb6c0
52 changed files with 1080 additions and 0 deletions

View File

@@ -0,0 +1,8 @@
package javadevjournal.design.creational.abstractfactory;
/**
* @author Kunwar
*/
public abstract class AbstractFactory {
abstract Shape getShape(String shapeType) ;
}

View File

@@ -0,0 +1,29 @@
package javadevjournal.design.creational.abstractfactory;
/**
* @author Kunwar
*/
public class AbstractFactoryDemo {
public static void main(String[] args) {
/* get shape factory */
AbstractFactory shapeFactory = FactoryOfFactory.getFactory(false);
/* get an object of Shape Rectangle */
Shape shape1 = shapeFactory.getShape("RECTANGLE");
/* call draw method of Shape Rectangle */
shape1.drawShape();
/* get an object of Shape Square */
Shape shape2 = shapeFactory.getShape("SQUARE");
/* call draw method of Shape Square */
shape2.drawShape();
/* get rounded shape factory */
AbstractFactory roundShapeFactory = FactoryOfFactory.getFactory(true);
/* get an object of Shape Rectangle */
Shape shape3 = roundShapeFactory.getShape("RECTANGLE");
/* call draw method of Shape Rectangle */
shape3.drawShape();
/* get an object of Shape Square */
Shape shape4 = roundShapeFactory.getShape("SQUARE");
/* call draw method of Shape Square */
shape4.drawShape();
}
}

View File

@@ -0,0 +1,14 @@
package javadevjournal.design.creational.abstractfactory;
/**
* @author Kunwar
*/
public class FactoryOfFactory {
public static AbstractFactory getFactory(boolean rounded){
if(rounded){
return new RoundedShapeFactory();
}else{
return new ShapeFactory();
}
}
}

View File

@@ -0,0 +1,11 @@
package javadevjournal.design.creational.abstractfactory;
/**
* @author Kunwar
*/
public class Rectangle implements Shape {
@Override
public void drawShape() {
System.out.println("Inside Rectangle::draw() method.");
}
}

View File

@@ -0,0 +1,11 @@
package javadevjournal.design.creational.abstractfactory;
/**
* @author Kunwar
*/
public class RoundedRectangle implements Shape {
@Override
public void drawShape() {
System.out.println("Inside RoundedRectangle::draw() method.");
}
}

View File

@@ -0,0 +1,16 @@
package javadevjournal.design.creational.abstractfactory;
/**
* @author Kunwar
*/
public class RoundedShapeFactory extends AbstractFactory {
@Override
public Shape getShape(String shapeType){
if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new RoundedRectangle();
}else if(shapeType.equalsIgnoreCase("SQUARE")){
return new RoundedSquare();
}
return null;
}
}

View File

@@ -0,0 +1,11 @@
package javadevjournal.design.creational.abstractfactory;
/**
* @author Kunwar
*/
public class RoundedSquare implements Shape {
@Override
public void drawShape() {
System.out.println("Inside RoundedSquare::draw() method.");
}
}

View File

@@ -0,0 +1,8 @@
package javadevjournal.design.creational.abstractfactory;
/**
* @author Kunwar
*/
public interface Shape {
void drawShape();
}

View File

@@ -0,0 +1,16 @@
package javadevjournal.design.creational.abstractfactory;
/**
* @author Kunwar
*/
public class ShapeFactory extends AbstractFactory {
@Override
public Shape getShape(String shapeType){
if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}

View File

@@ -0,0 +1,11 @@
package javadevjournal.design.creational.abstractfactory;
/**
* @author Kunwar
*/
public class Square implements Shape {
@Override
public void drawShape() {
System.out.println("Inside Square::draw() method.");
}
}

View File

@@ -0,0 +1,8 @@
package javadevjournal.design.creational.abstractfactory.example2;
/**
* Abstract Factory - Factory of Factories
*/
public abstract class AbstractFactory{
abstract IMobile getMobile(String mobileModel) ;
}

View File

@@ -0,0 +1,19 @@
package javadevjournal.design.creational.abstractfactory.example2;
/**
* Client Class
*/
public class AbstractFactoryPatternDemo{
public static void main(String[] args){
AbstractFactory abstractFactory1 = MpbileFactoryProducer.getFactory(false);
IMobile onePlus = abstractFactory1.getMobile("Oneplus");
onePlus.brandName();
IMobile sony = abstractFactory1.getMobile("Sony");
sony.brandName();
IMobile lava = abstractFactory1.getMobile("Lava");
lava.brandName();
AbstractFactory abstractFactory2 = MpbileFactoryProducer.getFactory(true);
IMobile iphone = abstractFactory2.getMobile("iphone");
iphone.brandName();
}
}

View File

@@ -0,0 +1,18 @@
package javadevjournal.design.creational.abstractfactory.example2;
/**
* Android Mobile Factory
*/
public class AndroidMobileFactory extends AbstractFactory {
@Override
public IMobile getMobile(String mobileModel){
if(mobileModel.equalsIgnoreCase("Oneplus")){
return new OnePlus();
}else if(mobileModel.equalsIgnoreCase("Sony")){
return new Sony();
}else if(mobileModel.equalsIgnoreCase("Lava")){
return new Lava();
}
return null;
}
}

View File

@@ -0,0 +1,14 @@
package javadevjournal.design.creational.abstractfactory.example2;
/**
* Apple Mobile Factory
*/
public class AppleMobileFactory extends AbstractFactory{
@Override
public IMobile getMobile(String mobileModel){
if(mobileModel.equalsIgnoreCase("iphone")){
return new Iphone();
}
return null;
}
}

View File

@@ -0,0 +1,8 @@
package javadevjournal.design.creational.abstractfactory.example2;
/**
* Mobile
*/
public interface IMobile {
void brandName();
}

View File

@@ -0,0 +1,11 @@
package javadevjournal.design.creational.abstractfactory.example2;
/**
* Iphone Mobile
*/
public class Iphone implements IMobile {
@Override
public void brandName() {
System.out.println("The brand name is Iphone");
}
}

View File

@@ -0,0 +1,11 @@
package javadevjournal.design.creational.abstractfactory.example2;
/**
* Nokia Mobile Concrete Class
*/
public class Lava implements IMobile {
@Override
public void brandName() {
System.out.println("The brand name is Lava");
}
}

View File

@@ -0,0 +1,15 @@
package javadevjournal.design.creational.abstractfactory.example2;
/**
* Factory Producer
*/
public class MpbileFactoryProducer {
public static AbstractFactory getFactory(boolean isApple){
if(isApple){
return new AppleMobileFactory();
}else{
return new AndroidMobileFactory();
}
}
}

View File

@@ -0,0 +1,11 @@
package javadevjournal.design.creational.abstractfactory.example2;
/**
* OnePlus Mobile
*/
public class OnePlus implements IMobile {
@Override
public void brandName() {
System.out.println("The brand name is OnePlus");
}
}

View File

@@ -0,0 +1,11 @@
package javadevjournal.design.creational.abstractfactory.example2;
/**
* Sony Mobile
*/
public class Sony implements IMobile {
@Override
public void brandName() {
System.out.println("The brand name is Sony");
}
}

View File

@@ -0,0 +1,26 @@
package javadevjournal.design.creational.builder;
/**
* @author Kunwar
* Builder Pattern Client Class
* Create Computer object with mandatory and optional properties
*/
public class BuilderPatternDemo {
public static void main(String[] args) {
Computer model1 = new Computer.ComputerBuilder(
"1 TB", "16 GB","15.6").setBluetoothEnabled(true)
.setGraphicsCardEnabled(true).setTouchScreenEnabled(true).setWebCamEnabled(true).build();
System.out.println("model1: " + model1.toString());
Computer model2 = new Computer.ComputerBuilder(
"256 GB", "8 GB","14.6").setBluetoothEnabled(true)
.setGraphicsCardEnabled(true).build();
System.out.println("model2: "+model2.toString());
Computer model3 = new Computer.ComputerBuilder(
"128 GB", "4 GB","13.6").build();
System.out.println("model3: "+model3.toString());
}
}

View File

@@ -0,0 +1,116 @@
package javadevjournal.design.creational.builder;
/**
* @author Kunwar
* Product Class
* Builder Pattern Class
*/
public class Computer {
//required parameters
private String HDD;
private String RAM;
private String screenSize;
//optional parameters
private boolean isGraphicsCardEnabled;
private boolean isBluetoothEnabled;
private boolean isWebCamEnabled;
private boolean isTouchScreenEnabled;
public String getHDD() {
return HDD;
}
public String getRAM() {
return RAM;
}
public String getScreenSize() {
return screenSize;
}
public boolean isGraphicsCardEnabled() {
return isGraphicsCardEnabled;
}
public boolean isBluetoothEnabled() {
return isBluetoothEnabled;
}
public boolean isWebCamEnabled() {
return isWebCamEnabled;
}
public boolean isTouchScreenEnabled() {
return isTouchScreenEnabled;
}
private Computer(ComputerBuilder builder) {
this.HDD=builder.HDD;
this.RAM=builder.RAM;
this.screenSize=builder.screenSize;
this.isGraphicsCardEnabled=builder.isGraphicsCardEnabled;
this.isBluetoothEnabled=builder.isBluetoothEnabled;
this.isTouchScreenEnabled=builder.isTouchScreenEnabled;
this.isWebCamEnabled=builder.isWebCamEnabled;
this.isWebCamEnabled=builder.isWebCamEnabled;
}
//Builder Class
public static class ComputerBuilder{
// required parameters
private String HDD;
private String RAM;
private String screenSize;
// optional parameters
private boolean isGraphicsCardEnabled;
private boolean isBluetoothEnabled;
private boolean isWebCamEnabled;
private boolean isTouchScreenEnabled;
public ComputerBuilder(String hdd, String ram, String screenSize){
this.HDD=hdd;
this.RAM=ram;
this.screenSize=screenSize;
}
public ComputerBuilder setGraphicsCardEnabled(boolean isGraphicsCardEnabled) {
this.isGraphicsCardEnabled = isGraphicsCardEnabled;
return this;
}
public ComputerBuilder setBluetoothEnabled(boolean isBluetoothEnabled) {
this.isBluetoothEnabled = isBluetoothEnabled;
return this;
}
public ComputerBuilder setWebCamEnabled(boolean webCamEnabled) {
isWebCamEnabled = webCamEnabled;
return this;
}
public ComputerBuilder setTouchScreenEnabled(boolean touchScreenEnabled) {
isTouchScreenEnabled = touchScreenEnabled;
return this;
}
public Computer build(){
return new Computer(this);
}
}
@Override
public String toString() {
return "Computer{" +
"HDD='" + HDD + '\'' +
", RAM='" + RAM + '\'' +
", screenSize='" + screenSize + '\'' +
", isGraphicsCardEnabled=" + isGraphicsCardEnabled +
", isBluetoothEnabled=" + isBluetoothEnabled +
", isWebCamEnabled=" + isWebCamEnabled +
", isTouchScreenEnabled=" + isTouchScreenEnabled +
'}';
}
}

View File

@@ -0,0 +1,11 @@
package javadevjournal.design.creational.factory;
/**
* @author Kunwar
*/
public class Circle implements Shape {
@Override
public void drawShape() {
System.out.println("Inside Circle::drawShape() method.");
}
}

View File

@@ -0,0 +1,23 @@
package javadevjournal.design.creational.factory;
/**
* @author Kunwar
* Factory Pattern Demo
*/
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
/* get an object of Circle Class and call its drawShape method. */
Shape shape1 = shapeFactory.getShape("CIRCLE");
shape1.drawShape();
/* get an object of Rectangle Class and call its drawShape method. */
Shape shape2 = shapeFactory.getShape("RECTANGLE");
shape2.drawShape();
/* get an object of Square Class and call its drawShape method. */
Shape shape3 = shapeFactory.getShape("SQUARE");
shape3.drawShape();
}
}

View File

@@ -0,0 +1,11 @@
package javadevjournal.design.creational.factory;
/**
* @author Kunwar
*/
public class Rectangle implements Shape {
@Override
public void drawShape() {
System.out.println("Inside Rectangle::drawShape() method.");
}
}

View File

@@ -0,0 +1,8 @@
package javadevjournal.design.creational.factory;
/**
* @author Kunwar
*/
public interface Shape {
void drawShape();
}

View File

@@ -0,0 +1,28 @@
package javadevjournal.design.creational.factory;
/**
* @author Kunwar
* Factory Pattern Implementation here
*/
public class ShapeFactory {
/**
* get the shapeType from caller and decide the correct implementation class
* @param shapeType
* @return
*/
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
} else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}

View File

@@ -0,0 +1,11 @@
package javadevjournal.design.creational.factory;
/**
* @author Kunwar
*/
public class Square implements Shape {
@Override
public void drawShape() {
System.out.println("Inside Square::drawShape() method.");
}
}

View File

@@ -0,0 +1,8 @@
package javadevjournal.design.creational.factory.banking;
/**
* @author Kunwar
*/
public interface BankAccount {
public void registerAccount();
}

View File

@@ -0,0 +1,20 @@
package javadevjournal.design.creational.factory.banking;
/**
* @author Kunwar
*/
public class BankAccountFactory {
public BankAccount createAccount(String type){
BankAccount bankAccount = null;
if (type.equals("P")){
bankAccount = new PersonalAccount();
} else if (type.equals("B")){
bankAccount = new BusinessAccount();
} else if (type.equals("C")){
bankAccount = new CheckingAccount();
} else {
System.out.println("Invalid type");
}
return bankAccount;
}
}

View File

@@ -0,0 +1,22 @@
package javadevjournal.design.creational.factory.banking;
import java.util.Scanner;
/**
* @author Kunwar
*/
public class Branch {
public static void main(String[] args) {
BankAccount bankAccount = null;
BankAccountFactory bankAccountFactory = new BankAccountFactory();
Scanner in = new Scanner(System.in);
System.out.println("Please enter\n" +
" P for Personal account\n" +
" B for Business account\n" +
" C for Checking account\n" +
"----------------------------");
String accountType = in.nextLine();
bankAccount = bankAccountFactory.createAccount(accountType);
bankAccount.registerAccount();;
}
}

View File

@@ -0,0 +1,11 @@
package javadevjournal.design.creational.factory.banking;
/**
* @author Kunwar
*/
public class BusinessAccount implements BankAccount {
@Override
public void registerAccount() {
System.out.println("Creating a business account");
}
}

View File

@@ -0,0 +1,11 @@
package javadevjournal.design.creational.factory.banking;
/**
* @author Kunwar
*/
public class CheckingAccount implements BankAccount{
@Override
public void registerAccount() {
System.out.println("Creating a checking account");
}
}

View File

@@ -0,0 +1,11 @@
package javadevjournal.design.creational.factory.banking;
/**
* @author Kunwar
*/
public class PersonalAccount implements BankAccount{
@Override
public void registerAccount() {
System.out.println("Creating a personal account");
}
}

View File

@@ -0,0 +1,18 @@
package javadevjournal.design.creational.singleton;
/**
* @author Kunwar
*/
public class Singleton {
/* private instance variable */
private static Singleton instance = new Singleton();
/* private constructor */
private Singleton(){}
/* returns the same object */
public static Singleton getInstance(){
return instance;
}
}

View File

@@ -0,0 +1,23 @@
package javadevjournal.design.creational.singleton;
public class SingletonMultiThreaded {
/* private instance variable */
private static volatile SingletonMultiThreaded INSTANCE;
/* private constructor */
private SingletonMultiThreaded() { }
public static SingletonMultiThreaded getInstance() {
/* double-checking lock */
if(null == INSTANCE){
/* synchronized block */
synchronized (SingletonMultiThreaded.class) {
if(null == INSTANCE){
INSTANCE = new SingletonMultiThreaded();
}
}
}
return INSTANCE;
}
}

View File

@@ -0,0 +1,24 @@
package javadevjournal.design.creational.singleton;
/**
* @author Kunwar
*/
public class SingletonPatternDemo {
public static void main(String[] args) {
/* Let's create 3 objects and see their hashcode and they will be same. */
System.out.println("in single threaded environment");
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
Singleton singleton3 = Singleton.getInstance();
System.out.println(singleton1.hashCode() +" "+ singleton2.hashCode() +" "+ singleton3.hashCode());
System.out.println("in multi threaded environment");
Thread1 t1 = new Thread1();
t1.run();
Thread2 t2 = new Thread2();
t2.run();
Thread3 t3 = new Thread3();
t3.run();
}
}

View File

@@ -0,0 +1,9 @@
package javadevjournal.design.creational.singleton;
public class Thread1 implements Runnable{
@Override
public void run() {
SingletonMultiThreaded singletonMultiThreaded = SingletonMultiThreaded.getInstance();
System.out.print(singletonMultiThreaded.hashCode() + " ");
}
}

View File

@@ -0,0 +1,9 @@
package javadevjournal.design.creational.singleton;
public class Thread2 implements Runnable{
@Override
public void run() {
SingletonMultiThreaded singletonMultiThreaded = SingletonMultiThreaded.getInstance();
System.out.print(singletonMultiThreaded.hashCode() + " ");
}
}

View File

@@ -0,0 +1,9 @@
package javadevjournal.design.creational.singleton;
public class Thread3 implements Runnable{
@Override
public void run() {
SingletonMultiThreaded singletonMultiThreaded = SingletonMultiThreaded.getInstance();
System.out.println(singletonMultiThreaded.hashCode());
}
}

View File

@@ -0,0 +1,27 @@
package javadevjournal.design.creational.singleton.breakit;
import java.lang.reflect.Constructor;
/**
* @author Kunwar
*/
public class BreakSingletonUsingReflection {
public static void main(String[] args) {
Singleton singleton1 = Singleton.instance;
Singleton singleton2 = null;
try {
Constructor[] constructors =
Singleton.class.getDeclaredConstructors();
for (Constructor constructor : constructors) {
// Below code will destroy the singleton pattern
constructor.setAccessible(true);
singleton2 = (Singleton) constructor.newInstance();
break;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("instance1.hashCode(): " + singleton1.hashCode());
System.out.println("instance2.hashCode(): " + singleton2.hashCode());
}
}

View File

@@ -0,0 +1,10 @@
package javadevjournal.design.creational.singleton.breakit;
/**
* @author Kunwar
*/
class Singleton{
public static Singleton instance = new Singleton();
private Singleton() {
}
}

View File

@@ -0,0 +1,14 @@
package javadevjournal.design.structural.adapter;
/**
* @author Kunwar
*/
public class AdapterPatternDemo {
public static void main(String[] args) {
AudioPlayer audioPlayer = new AudioPlayer();
audioPlayer.playMusic("mp3", "song1.mp3");
audioPlayer.playMusic("mp4", "song2.mp4");
audioPlayer.playMusic("vlc", "song3.vlc");
audioPlayer.playMusic("xyz", "song4.avi");
}
}

View File

@@ -0,0 +1,9 @@
package javadevjournal.design.structural.adapter;
/**
* @author Kunwar
*/
public interface AdvancedMediaPlayer {
void playVlcPlayer(String fileName);
void playMp4Player(String fileName);
}

View File

@@ -0,0 +1,22 @@
package javadevjournal.design.structural.adapter;
/**
* @author Kunwar
*/
public class AudioPlayer implements MediaPlayer {
private MediaAdapter mediaAdapter;
@Override
public void playMusic(String audioType, String fileName) {
//the mp3 format is supported by AudioPlayer itself and it doesn't need adapter here.
if(audioType.equalsIgnoreCase("mp3")){
System.out.println("Playing mp3 file: " + fileName);
}
//to support other formats, we will need the MediaAdapter
else if(audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")){
mediaAdapter = new MediaAdapter(audioType);
mediaAdapter.playMusic(audioType, fileName);
}else{
System.out.println("The given format: " + audioType + " is not supported");
}
}
}

View File

@@ -0,0 +1,28 @@
package javadevjournal.design.structural.adapter;
/**
* @author Kunwar
*/
public class MediaAdapter implements MediaPlayer {
public static final String VLC = "vlc";
public static final String MP_4 = "mp4";
private AdvancedMediaPlayer advancedMusicPlayer;
public MediaAdapter(String audioType){
if(audioType.equalsIgnoreCase(VLC) ){
advancedMusicPlayer = new VlcMusicPlayer();
}else if (audioType.equalsIgnoreCase(MP_4)){
advancedMusicPlayer = new Mp4MusicPlayer();
}
}
@Override
public void playMusic(String audioType, String fileName) {
if(audioType.equalsIgnoreCase(VLC)){
advancedMusicPlayer.playVlcPlayer(fileName);
}else if(audioType.equalsIgnoreCase(MP_4)){
advancedMusicPlayer.playMp4Player(fileName);
}
}
}

View File

@@ -0,0 +1,8 @@
package javadevjournal.design.structural.adapter;
/**
* @author Kunwar
*/
public interface MediaPlayer{
void playMusic(String audioType, String fileName);
}

View File

@@ -0,0 +1,17 @@
package javadevjournal.design.structural.adapter;
/**
* @author Kunwar
*/
public class Mp4MusicPlayer implements AdvancedMediaPlayer{
@Override
public void playVlcPlayer(String fileName) {
//do nothing
}
@Override
public void playMp4Player(String fileName) {
System.out.println("Playing mp4 file: "+ fileName);
}
}

View File

@@ -0,0 +1,16 @@
package javadevjournal.design.structural.adapter;
/**
* @author Kunwar
*/
public class VlcMusicPlayer implements AdvancedMediaPlayer{
@Override
public void playVlcPlayer(String fileName){
System.out.println("Playing vlc file: "+ fileName);
}
@Override
public void playMp4Player(String fileName) {
//do nothing
}
}