├── factory_design_pattern └── FactoryPattern.java ├── adapter_design_pattern └── AdapterPattern.java ├── prototype_design_pattern └── PrototypePattern.java ├── proxy_design_pattern └── ProxyPattern.java ├── singleton_design_pattern └── SingletonPattern.java ├── composite_design_pattern └── CompositePattern.java ├── decorator_design_pattern └── DecoratorPattern.java ├── facade_design_pattern └── FacadePattern.java ├── bridge_design_pattern └── BridgePattern.java ├── flyweight_design_pattern └── FlyweightPattern.java ├── observer_design_pattern └── ObserverPattern.java ├── README.md └── Design Pattern tutorials.txt /factory_design_pattern/FactoryPattern.java: -------------------------------------------------------------------------------- 1 | package factory_design_pattern; 2 | 3 | abstract class Vehicle 4 | { 5 | public abstract int getWheel(); 6 | public String toString() 7 | { 8 | return "Wheel: " + this.getWheel(); 9 | } 10 | } 11 | 12 | class Car extends Vehicle 13 | { 14 | int wheel; 15 | Car(int wheel) 16 | { 17 | this.wheel = wheel; 18 | } 19 | 20 | @Override 21 | public int getWheel() 22 | { 23 | return this.wheel; 24 | } 25 | } 26 | 27 | class Bike extends Vehicle 28 | { 29 | int wheel; 30 | Bike(int wheel) 31 | { 32 | this.wheel = wheel; 33 | } 34 | 35 | @Override 36 | public int getWheel() 37 | { 38 | return this.wheel; 39 | } 40 | } 41 | 42 | class VehicleFactory 43 | { 44 | public static Vehicle getInstance(String type, int wheel) 45 | { 46 | if(type == "car") 47 | { 48 | return new Car(wheel); 49 | } 50 | else if(type == "bike") 51 | { 52 | return new Bike(wheel); 53 | } 54 | return null; 55 | } 56 | } 57 | 58 | public class FactoryPattern 59 | { 60 | public static void main(String[] args) 61 | { 62 | Vehicle car = VehicleFactory.getInstance("car", 4); 63 | System.out.println(car); 64 | 65 | Vehicle bike = VehicleFactory.getInstance("bike", 2); 66 | System.out.println(bike); 67 | } 68 | } -------------------------------------------------------------------------------- /adapter_design_pattern/AdapterPattern.java: -------------------------------------------------------------------------------- 1 | package adapter_design_pattern; 2 | 3 | interface WebDriver 4 | { 5 | public void getElement(); 6 | public void selectElement(); 7 | } 8 | 9 | class ChromeDriver implements WebDriver 10 | { 11 | @Override 12 | public void getElement() 13 | { 14 | System.out.println("Get element from ChromeDriver"); 15 | } 16 | 17 | @Override 18 | public void selectElement() 19 | { 20 | System.out.println("Select element from ChromeDriver"); 21 | 22 | } 23 | 24 | } 25 | 26 | class IEDriver 27 | { 28 | public void findElement() 29 | { 30 | System.out.println("Find element from IEDriver"); 31 | } 32 | 33 | public void clickElement() 34 | { 35 | System.out.println("Click element from IEDriver"); 36 | } 37 | 38 | } 39 | 40 | class WebDriverAdapter implements WebDriver 41 | { 42 | IEDriver ieDriver; 43 | public WebDriverAdapter(IEDriver ieDriver) 44 | { 45 | this.ieDriver = ieDriver; 46 | } 47 | 48 | @Override 49 | public void getElement() 50 | { 51 | ieDriver.findElement(); 52 | 53 | } 54 | 55 | @Override 56 | public void selectElement() 57 | { 58 | ieDriver.clickElement(); 59 | } 60 | 61 | } 62 | 63 | public class AdapterPattern 64 | { 65 | public static void main(String[] args) 66 | { 67 | ChromeDriver a = new ChromeDriver(); 68 | a.getElement(); 69 | a.selectElement(); 70 | 71 | IEDriver e = new IEDriver(); 72 | e.findElement(); 73 | e.clickElement(); 74 | 75 | WebDriver wID = new WebDriverAdapter(e); 76 | wID.getElement(); 77 | wID.selectElement(); 78 | 79 | } 80 | } -------------------------------------------------------------------------------- /prototype_design_pattern/PrototypePattern.java: -------------------------------------------------------------------------------- 1 | package prototype_design_pattern; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | class Vehicle implements Cloneable 7 | { 8 | private List vehicleList; 9 | 10 | public Vehicle() 11 | { 12 | this.vehicleList = new ArrayList(); 13 | } 14 | 15 | public Vehicle(List list) 16 | { 17 | this.vehicleList = list; 18 | } 19 | 20 | public void insertData() 21 | { 22 | vehicleList.add("Honda amaze"); 23 | vehicleList.add("Audi A4"); 24 | vehicleList.add("Hyundai Creta"); 25 | vehicleList.add("Maruti Baleno"); 26 | vehicleList.add("Renault Duster"); 27 | } 28 | 29 | public List getVehicleList() 30 | { 31 | return this.vehicleList; 32 | } 33 | 34 | @Override 35 | public Object clone() throws CloneNotSupportedException 36 | { 37 | List tempList = new ArrayList(); 38 | 39 | for(String s : this.getVehicleList()) 40 | { 41 | tempList.add(s); 42 | } 43 | 44 | return new Vehicle(tempList); 45 | } 46 | } 47 | 48 | public class PrototypePattern 49 | { 50 | public static void main(String[] args) throws CloneNotSupportedException 51 | { 52 | Vehicle a = new Vehicle(); 53 | a.insertData(); 54 | 55 | Vehicle b = (Vehicle) a.clone(); 56 | List list = b.getVehicleList(); 57 | list.add("Honda new Amaze"); 58 | 59 | System.out.println(a.getVehicleList()); 60 | System.out.println(list); 61 | 62 | b.getVehicleList().remove("Audi A4"); 63 | System.out.println(list); 64 | System.out.println(a.getVehicleList()); 65 | } 66 | 67 | } -------------------------------------------------------------------------------- /proxy_design_pattern/ProxyPattern.java: -------------------------------------------------------------------------------- 1 | package proxy_design_pattern; 2 | 3 | interface DatabaseExecuter 4 | { 5 | public void executeDatabase(String query) throws Exception; 6 | } 7 | 8 | class DatabaseExecuterImpl implements DatabaseExecuter 9 | { 10 | @Override 11 | public void executeDatabase(String query) throws Exception 12 | { 13 | System.out.println("Going to execute Query: " + query); 14 | } 15 | } 16 | 17 | class DatabaseExecuterProxy implements DatabaseExecuter 18 | { 19 | boolean ifAdmin; 20 | DatabaseExecuterImpl dbExecuter; 21 | 22 | public DatabaseExecuterProxy(String name, String passwd) 23 | { 24 | if(name == "Admin" && passwd == "Admin@123") 25 | { 26 | ifAdmin = true; 27 | } 28 | dbExecuter = new DatabaseExecuterImpl(); 29 | } 30 | 31 | @Override 32 | public void executeDatabase(String query) throws Exception 33 | { 34 | if(ifAdmin) 35 | { 36 | dbExecuter.executeDatabase(query); 37 | } 38 | else 39 | { 40 | if(query.equals("DELETE")) 41 | { 42 | throw new Exception("DELETE not allowed for non-admin user"); 43 | } 44 | else 45 | { 46 | dbExecuter.executeDatabase(query); 47 | } 48 | } 49 | } 50 | } 51 | 52 | public class ProxyPattern 53 | { 54 | public static void main(String[] args) throws Exception 55 | { 56 | DatabaseExecuter nonAdminExecuter = new DatabaseExecuterProxy("NonAdmin", "Admin@123"); 57 | nonAdminExecuter.executeDatabase("DELEE"); 58 | 59 | DatabaseExecuter nonAdminExecuterDELETE = new DatabaseExecuterProxy("NonAdmin", "Admin@123"); 60 | nonAdminExecuterDELETE.executeDatabase("DELETE"); 61 | 62 | DatabaseExecuter adminExecuter = new DatabaseExecuterProxy("Admin", "Admin@123"); 63 | adminExecuter.executeDatabase("DELETE"); 64 | } 65 | } -------------------------------------------------------------------------------- /singleton_design_pattern/SingletonPattern.java: -------------------------------------------------------------------------------- 1 | package singleton_design_pattern; 2 | 3 | class SingletonEagar 4 | { 5 | private static SingletonEagar instance = new SingletonEagar(); 6 | private SingletonEagar() 7 | { 8 | 9 | } 10 | public static SingletonEagar getInstance() 11 | { 12 | return instance; 13 | } 14 | } 15 | 16 | class Singleton 17 | { 18 | private static Singleton instance; 19 | private Singleton() 20 | { 21 | 22 | } 23 | public static Singleton getInstance() 24 | { 25 | if(instance == null) 26 | { 27 | instance = new Singleton(); 28 | } 29 | return instance; 30 | } 31 | } 32 | 33 | class SingletonSynchronizedMethod 34 | { 35 | private static SingletonSynchronizedMethod instance; 36 | private SingletonSynchronizedMethod() 37 | { 38 | 39 | } 40 | public static synchronized SingletonSynchronizedMethod getInstance() 41 | { 42 | if(instance == null) 43 | { 44 | instance = new SingletonSynchronizedMethod(); 45 | } 46 | return instance; 47 | } 48 | } 49 | 50 | class SingletonSynchronized 51 | { 52 | private static SingletonSynchronized instance; 53 | private SingletonSynchronized() 54 | { 55 | 56 | } 57 | public static SingletonSynchronized getInstance() 58 | { 59 | if(instance == null) 60 | { 61 | synchronized (SingletonSynchronized.class) 62 | { 63 | if(instance == null) 64 | { 65 | instance = new SingletonSynchronized(); 66 | } 67 | } 68 | } 69 | return instance; 70 | } 71 | } 72 | 73 | public class SingletonPattern 74 | { 75 | public static void main(String[] args) 76 | { 77 | SingletonSynchronized instance = SingletonSynchronized.getInstance(); 78 | System.out.println(instance); 79 | SingletonSynchronized instance1 = SingletonSynchronized.getInstance(); 80 | System.out.println(instance1); 81 | } 82 | } -------------------------------------------------------------------------------- /composite_design_pattern/CompositePattern.java: -------------------------------------------------------------------------------- 1 | package composite_design_pattern; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | abstract class Account 7 | { 8 | public abstract float getBalance(); 9 | } 10 | 11 | class DepositeAccount extends Account 12 | { 13 | private String accountNo; 14 | private float accountBalance; 15 | 16 | public DepositeAccount(String accountNo, float accountBalance) 17 | { 18 | super(); 19 | this.accountNo = accountNo; 20 | this.accountBalance = accountBalance; 21 | } 22 | 23 | public float getBalance() 24 | { 25 | return accountBalance; 26 | } 27 | } 28 | 29 | class SavingAccount extends Account 30 | { 31 | private String accountNo; 32 | private float accountBalance; 33 | 34 | public SavingAccount(String accountNo, float accountBalance) 35 | { 36 | super(); 37 | this.accountNo = accountNo; 38 | this.accountBalance = accountBalance; 39 | } 40 | 41 | public float getBalance() 42 | { 43 | return accountBalance; 44 | } 45 | } 46 | 47 | class CompositeAccount extends Account 48 | { 49 | private float totalBalance; 50 | private List accountList = new ArrayList(); 51 | 52 | public float getBalance() 53 | { 54 | totalBalance = 0; 55 | for (Account f : accountList) 56 | { 57 | totalBalance = totalBalance + f.getBalance(); 58 | } 59 | return totalBalance; 60 | } 61 | 62 | public void addAccount(Account acc) 63 | { 64 | accountList.add(acc); 65 | } 66 | 67 | public void removeAccount(Account acc) 68 | { 69 | accountList.add(acc); 70 | } 71 | } 72 | 73 | public class CompositePattern 74 | { 75 | public static void main(String[] args) 76 | { 77 | CompositeAccount component = new CompositeAccount(); 78 | 79 | component.addAccount(new DepositeAccount("DA001", 100)); 80 | component.addAccount(new DepositeAccount("DA002", 150)); 81 | component.addAccount(new SavingAccount("SA001", 200)); 82 | 83 | float totalBalance = component.getBalance(); 84 | System.out.println("Total Balance : " + totalBalance); 85 | } 86 | } -------------------------------------------------------------------------------- /decorator_design_pattern/DecoratorPattern.java: -------------------------------------------------------------------------------- 1 | package decorator_design_pattern; 2 | 3 | interface Dress 4 | { 5 | public void assemble(); 6 | } 7 | 8 | class BasicDress implements Dress 9 | { 10 | @Override 11 | public void assemble() 12 | { 13 | System.out.println("Basic Dress Features"); 14 | } 15 | } 16 | 17 | class DressDecorator implements Dress 18 | { 19 | protected Dress dress; 20 | public DressDecorator(Dress c) 21 | { 22 | this.dress = c; 23 | } 24 | 25 | @Override 26 | public void assemble() 27 | { 28 | this.dress.assemble(); 29 | } 30 | } 31 | 32 | class CasualDress extends DressDecorator 33 | { 34 | public CasualDress(Dress c) 35 | { 36 | super(c); 37 | } 38 | 39 | @Override 40 | public void assemble() 41 | { 42 | super.assemble(); 43 | System.out.println("Adding Casual Dress Features"); 44 | } 45 | } 46 | 47 | 48 | class SportyDress extends DressDecorator 49 | { 50 | public SportyDress(Dress c) 51 | { 52 | super(c); 53 | } 54 | 55 | @Override 56 | public void assemble() 57 | { 58 | super.assemble(); 59 | System.out.println("Adding Sporty Dress Features"); 60 | } 61 | } 62 | 63 | class FancyDress extends DressDecorator 64 | { 65 | public FancyDress(Dress c) 66 | { 67 | super(c); 68 | } 69 | 70 | @Override 71 | public void assemble() 72 | { 73 | super.assemble(); 74 | System.out.println("Adding Fancy Dress Features"); 75 | } 76 | } 77 | 78 | public class DecoratorPattern 79 | { 80 | public static void main(String[] args) 81 | { 82 | Dress sportyDress = new SportyDress(new BasicDress()); 83 | sportyDress.assemble(); 84 | System.out.println(); 85 | 86 | Dress fancyDress = new FancyDress(new BasicDress()); 87 | fancyDress.assemble(); 88 | System.out.println(); 89 | 90 | Dress casualDress = new CasualDress(new BasicDress()); 91 | casualDress.assemble(); 92 | System.out.println(); 93 | 94 | Dress sportyFancyDress = new SportyDress(new FancyDress(new BasicDress())); 95 | sportyFancyDress.assemble(); 96 | System.out.println(); 97 | 98 | Dress casualFancyDress = new CasualDress(new FancyDress(new BasicDress())); 99 | casualFancyDress.assemble(); 100 | } 101 | } -------------------------------------------------------------------------------- /facade_design_pattern/FacadePattern.java: -------------------------------------------------------------------------------- 1 | package facade_design_pattern; 2 | 3 | import java.sql.Driver; 4 | 5 | class Firefox 6 | { 7 | public static Driver getFirefoxDriver() 8 | { 9 | return null; 10 | } 11 | 12 | public static void generateHTMLReport(String test, Driver driver) 13 | { 14 | System.out.println("Generating HTML Report for Firefox Driver"); 15 | } 16 | 17 | public static void generateJUnitReport(String test, Driver driver) 18 | { 19 | System.out.println("Generating JUNIT Report for Firefox Driver"); 20 | } 21 | } 22 | 23 | class Chrome 24 | { 25 | public static Driver getChromeDriver() 26 | { 27 | return null; 28 | } 29 | 30 | public static void generateHTMLReport(String test, Driver driver) 31 | { 32 | System.out.println("Generating HTML Report for Chrome Driver"); 33 | } 34 | 35 | public static void generateJUnitReport(String test, Driver driver) 36 | { 37 | System.out.println("Generating JUNIT Report for Chrome Driver"); 38 | } 39 | } 40 | 41 | class WebExplorerHelperFacade 42 | { 43 | public static void generateReports(String explorer, String report, String test) 44 | { 45 | Driver driver = null; 46 | switch(explorer) 47 | { 48 | case "firefox": 49 | driver = Firefox.getFirefoxDriver(); 50 | switch(report) 51 | { 52 | case "html": 53 | Firefox.generateHTMLReport(test, driver); 54 | break; 55 | case "junit": 56 | Firefox.generateJUnitReport(test, driver); 57 | break; 58 | } 59 | break; 60 | case "chrome": 61 | driver = Chrome.getChromeDriver(); 62 | switch(report) 63 | { 64 | case "html": 65 | Chrome.generateHTMLReport(test, driver); 66 | break; 67 | case "junit": 68 | Chrome.generateJUnitReport(test, driver); 69 | break; 70 | } 71 | } 72 | } 73 | } 74 | 75 | public class FacadePattern 76 | { 77 | public static void main(String[] args) 78 | { 79 | String test = "CheckElementPresent"; 80 | 81 | WebExplorerHelperFacade.generateReports("firefox", "html", test); 82 | WebExplorerHelperFacade.generateReports("firefox", "junit", test); 83 | WebExplorerHelperFacade.generateReports("chrome", "html", test); 84 | WebExplorerHelperFacade.generateReports("chrome", "junit", test); 85 | } 86 | 87 | } -------------------------------------------------------------------------------- /bridge_design_pattern/BridgePattern.java: -------------------------------------------------------------------------------- 1 | package bridge_design_pattern; 2 | 3 | abstract class TV 4 | { 5 | Remote remote; 6 | TV(Remote r) 7 | { 8 | this.remote = r; 9 | } 10 | abstract void on(); 11 | abstract void off(); 12 | } 13 | 14 | class Sony extends TV 15 | { 16 | Remote remoteType; 17 | Sony(Remote r) 18 | { 19 | super(r); 20 | this.remoteType = r; 21 | } 22 | 23 | public void on() 24 | { 25 | System.out.print("Sony TV ON: "); 26 | remoteType.on(); 27 | } 28 | 29 | public void off() 30 | { 31 | System.out.print("Sony TV OFF: "); 32 | remoteType.off(); 33 | } 34 | } 35 | 36 | class Philips extends TV 37 | { 38 | Remote remoteType; 39 | Philips(Remote r) 40 | { 41 | super(r); 42 | this.remoteType = r; 43 | } 44 | 45 | public void on() 46 | { 47 | System.out.print("Philips TV ON: "); 48 | remoteType.on(); 49 | } 50 | 51 | public void off() 52 | { 53 | System.out.print("Philips TV OFF: "); 54 | remoteType.off(); 55 | } 56 | } 57 | 58 | interface Remote 59 | { 60 | public void on(); 61 | public void off(); 62 | } 63 | 64 | class OldRemote implements Remote 65 | { 66 | @Override 67 | public void on() 68 | { 69 | System.out.println("ON with Old Remote"); 70 | } 71 | 72 | @Override 73 | public void off() 74 | { 75 | System.out.println("OFF with old Remote"); 76 | } 77 | 78 | } 79 | 80 | class NewRemote implements Remote 81 | { 82 | @Override 83 | public void on() 84 | { 85 | System.out.println("ON with New Remote"); 86 | } 87 | 88 | @Override 89 | public void off() 90 | { 91 | System.out.println("OFF with New Remote"); 92 | } 93 | } 94 | 95 | public class BridgePattern 96 | { 97 | public static void main(String[] args) 98 | { 99 | TV sonyOldRemote = new Sony(new OldRemote()); 100 | sonyOldRemote.on(); 101 | sonyOldRemote.off(); 102 | System.out.println(); 103 | 104 | TV sonyNewRemote = new Sony(new NewRemote()); 105 | sonyNewRemote.on(); 106 | sonyNewRemote.off(); 107 | System.out.println(); 108 | 109 | TV philipsOldRemote = new Philips(new OldRemote()); 110 | philipsOldRemote.on(); 111 | philipsOldRemote.off(); 112 | System.out.println(); 113 | 114 | TV philipsNewRemote = new Philips(new NewRemote()); 115 | philipsNewRemote.on(); 116 | philipsNewRemote.off(); 117 | } 118 | } -------------------------------------------------------------------------------- /flyweight_design_pattern/FlyweightPattern.java: -------------------------------------------------------------------------------- 1 | package flyweight_design_pattern; 2 | 3 | import java.util.HashMap; 4 | import java.util.Random; 5 | 6 | interface Employee 7 | { 8 | public void assignSkill(String skill); 9 | public void task(); 10 | } 11 | 12 | class Developer implements Employee 13 | { 14 | 15 | private final String JOB; 16 | private String skill; 17 | 18 | public Developer() 19 | { 20 | JOB = "Fix the issue"; 21 | } 22 | 23 | @Override 24 | public void assignSkill(String skill) 25 | { 26 | this.skill = skill; 27 | } 28 | 29 | @Override 30 | public void task() 31 | { 32 | System.out.println("Developer with skill: " + this.skill + " with Job: " + JOB); 33 | } 34 | 35 | } 36 | 37 | class Tester implements Employee 38 | { 39 | private final String JOB; 40 | private String skill; 41 | public Tester() 42 | { 43 | JOB = "Test the issue"; 44 | } 45 | 46 | @Override 47 | public void assignSkill(String skill) 48 | { 49 | this.skill = skill; 50 | } 51 | 52 | @Override 53 | public void task() 54 | { 55 | System.out.println("Tester with Skill: " + this.skill + " with Job: " + JOB); 56 | } 57 | 58 | } 59 | 60 | 61 | class EmployeeFactory 62 | { 63 | private static HashMap m = new HashMap(); 64 | 65 | public static Employee getEmployee(String type) 66 | { 67 | Employee p = null; 68 | if(m.get(type) != null) 69 | { 70 | p = m.get(type); 71 | } 72 | else 73 | { 74 | switch(type) 75 | { 76 | case "Developer": 77 | System.out.println("Developer Created"); 78 | p = new Developer(); 79 | break; 80 | case "Tester": 81 | System.out.println("Tester Created"); 82 | p = new Tester(); 83 | break; 84 | default: 85 | System.out.println("No Such Employee"); 86 | } 87 | 88 | m.put(type, p); 89 | } 90 | return p; 91 | } 92 | } 93 | 94 | public class FlyweightPattern 95 | { 96 | private static String employeeType[] = {"Developer", "Tester"}; 97 | private static String skills[] = {"Java", "C++", ".Net", "Python"}; 98 | public static void main(String[] args) 99 | { 100 | for(int i = 0; i < 10; i++) 101 | { 102 | Employee e = EmployeeFactory.getEmployee(getRandEmployee()); 103 | e.assignSkill(getRandSkill()); 104 | e.task(); 105 | } 106 | } 107 | 108 | public static String getRandEmployee() 109 | { 110 | Random r = new Random(); 111 | int randInt = r.nextInt(employeeType.length); 112 | return employeeType[randInt]; 113 | } 114 | 115 | public static String getRandSkill() 116 | { 117 | Random r = new Random(); 118 | int randInt = r.nextInt(skills.length); 119 | return skills[randInt]; 120 | } 121 | } -------------------------------------------------------------------------------- /observer_design_pattern/ObserverPattern.java: -------------------------------------------------------------------------------- 1 | package observer_design_pattern; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | interface Subject 7 | { 8 | void register(Observer obj); 9 | void unregister(Observer obj); 10 | void notifyObservers(); 11 | } 12 | 13 | class DeliveryData implements Subject 14 | { 15 | private List observers; 16 | private String location; 17 | 18 | public DeliveryData() 19 | { 20 | this.observers = new ArrayList<>(); 21 | } 22 | 23 | @Override 24 | public void register(Observer obj) 25 | { 26 | observers.add(obj); 27 | } 28 | 29 | @Override 30 | public void unregister(Observer obj) 31 | { 32 | observers.remove(obj); 33 | } 34 | 35 | @Override 36 | public void notifyObservers() 37 | { 38 | for(Observer obj : observers) 39 | { 40 | obj.update(location); 41 | } 42 | } 43 | 44 | public void locationChanged() 45 | { 46 | this.location = getLocation(); 47 | notifyObservers(); 48 | } 49 | 50 | public String getLocation() 51 | { 52 | return "YPlace"; 53 | } 54 | } 55 | 56 | 57 | interface Observer 58 | { 59 | public void update(String location); 60 | } 61 | 62 | 63 | class Seller implements Observer 64 | { 65 | private String location; 66 | 67 | @Override 68 | public void update(String location) 69 | { 70 | this.location = location; 71 | showLocation(); 72 | } 73 | 74 | public void showLocation() 75 | { 76 | System.out.println("Notification at Seller - Current Location: " + location); 77 | } 78 | } 79 | 80 | class User implements Observer 81 | { 82 | private String location; 83 | 84 | @Override 85 | public void update(String location) 86 | { 87 | this.location = location; 88 | showLocation(); 89 | } 90 | 91 | public void showLocation() 92 | { 93 | System.out.println("Notification at User - Current Location: " + location); 94 | } 95 | } 96 | 97 | class DeliveryWarehouseCenter implements Observer 98 | { 99 | private String location; 100 | 101 | @Override 102 | public void update(String location) 103 | { 104 | this.location = location; 105 | showLocation(); 106 | } 107 | 108 | public void showLocation() 109 | { 110 | System.out.println("Notification at Warehouse - Current Location: " + location); 111 | } 112 | } 113 | 114 | public class ObserverPattern 115 | { 116 | public static void main(String[] args) 117 | { 118 | DeliveryData topic = new DeliveryData(); 119 | 120 | Observer obj1 = new Seller(); 121 | Observer obj2 = new User(); 122 | Observer obj3 = new DeliveryWarehouseCenter(); 123 | 124 | topic.register(obj1); 125 | topic.register(obj2); 126 | topic.register(obj3); 127 | 128 | topic.locationChanged(); 129 | topic.unregister(obj3); 130 | 131 | System.out.println(); 132 | topic.locationChanged(); 133 | } 134 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JAVA DESIGN PATTERNS ❤️ 2 | 3 | ![](https://img.shields.io/github/languages/count/CodeJamm/JAVA_Design_Patterns) ![](https://img.shields.io/github/languages/top/CodeJamm/JAVA_Design_Patterns) 4 | 5 | 👋 I have created this module which consists of the Detailed definitions about the JAVA Design Patterns and their practical implementation through Codes. 6 | 7 | # 🌱 History of Design Patterns 8 | 9 | - In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides published a book titled Design Patterns - Elements of Reusable Object-Oriented Software which initiated the concept of Design Pattern in Software development. 10 | - These authors are collectively known as Gang of Four (GOF). According to these authors design patterns are primarily based on the following principles of object orientated design. 11 | 1) Program to an interface not an implementation 12 | 2) Favor object composition over inheritance 13 | 14 | # 🔭 Types of Design Patterns 15 | 16 | # Creational Patterns 17 | - These design patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. 18 | - This gives program more flexibility in deciding which objects need to be created for a given use case. 19 | 20 | # Structural Patterns 21 | - These design patterns concern class and object composition. 22 | - Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities. 23 | 24 | # Behavioral Patterns 25 | - These design patterns are specifically concerned with communication between objects. 26 | 27 | # J2EE Patterns 28 | - These design patterns are specifically concerned with the presentation tier. 29 | - These patterns are identified by Sun Java Center. 30 | 31 | # 👯 some of the most used Design Patterns available in JAVA are: 32 | 33 | - Singleton Design Pattern 34 | - Factory Design Pattern 35 | - Builder Design Pattern 36 | - Prototype Design Pattern 37 | - Proxy Design Pattern 38 | - Facade Design Pattern 39 | - Composite Design Pattern 40 | - Decorator Design Pattern 41 | - Flyweight Design Pattern 42 | - Adapter Design Pattern 43 | - Bridge Design Pattern 44 | - Observer Design Pattern 45 | 46 | # Singleton Design Pattern 47 | 48 | - Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. 49 | - This pattern involves a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class. 50 | 51 | 52 | ![image](https://user-images.githubusercontent.com/43011442/117574182-83d43580-b0f9-11eb-8cc9-c799a659f0e8.png) 53 | 54 | 55 | # Factory Design Pattern 56 | 57 | - Factory pattern is one of the most used design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. 58 | - In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface. 59 | 60 | 61 | ![image](https://user-images.githubusercontent.com/43011442/117574213-abc39900-b0f9-11eb-9cc3-f601b8c2c223.png) 62 | 63 | 64 | # Builder Design Pattern 65 | 66 | - Builder pattern builds a complex object using simple objects and using a step by step approach. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. 67 | - A Builder class builds the final object step by step. This builder is independent of other objects. 68 | 69 | 70 | ![image](https://user-images.githubusercontent.com/43011442/117574235-c990fe00-b0f9-11eb-8b8d-5c20c5388047.png) 71 | 72 | 73 | # Prototype Design Pattern 74 | 75 | - Prototype pattern refers to creating duplicate object while keeping performance in mind. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. 76 | - This pattern involves implementing a prototype interface which tells to create a clone of the current object. This pattern is used when creation of object directly is costly. For example, an object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls. 77 | 78 | 79 | ![image](https://user-images.githubusercontent.com/43011442/117574418-9b5fee00-b0fa-11eb-9143-880e563fc020.png) 80 | 81 | 82 | # Proxy Design Pattern 83 | 84 | - In proxy pattern, a class represents functionality of another class. This type of design pattern comes under structural pattern. 85 | - In proxy pattern, we create object having original object to interface its functionality to outer world. 86 | 87 | 88 | ![image](https://user-images.githubusercontent.com/43011442/117574433-ae72be00-b0fa-11eb-8d4a-5bbea4c4a744.png) 89 | 90 | 91 | # Facade Design Pattern 92 | 93 | - Facade pattern hides the complexities of the system and provides an interface to the client using which the client can access the system. This type of design pattern comes under structural pattern as this pattern adds an interface to existing system to hide its complexities. 94 | - This pattern involves a single class which provides simplified methods required by client and delegates calls to methods of existing system classes. 95 | 96 | 97 | ![image](https://user-images.githubusercontent.com/43011442/117574467-d4985e00-b0fa-11eb-96fe-69a3218f9952.png) 98 | 99 | 100 | # Composite Design Pattern 101 | 102 | - Composite pattern is used where we need to treat a group of objects in similar way as a single object. Composite pattern composes objects in term of a tree structure to represent part as well as whole hierarchy. This type of design pattern comes under structural pattern as this pattern creates a tree structure of group of objects. 103 | - This pattern creates a class that contains group of its own objects. This class provides ways to modify its group of same objects. 104 | 105 | 106 | ![image](https://user-images.githubusercontent.com/43011442/117574495-ef6ad280-b0fa-11eb-9ce1-8153da0059c6.png) 107 | 108 | 109 | # Decorator Design Pattern 110 | 111 | - Decorator pattern allows a user to add new functionality to an existing object without altering its structure. This type of design pattern comes under structural pattern as this pattern acts as a wrapper to existing class. 112 | - This pattern creates a decorator class which wraps the original class and provides additional functionality keeping class methods signature intact. 113 | 114 | 115 | ![image](https://user-images.githubusercontent.com/43011442/117574697-ef1f0700-b0fb-11eb-9d88-794867df11a3.png) 116 | 117 | 118 | # Flyweight Design Pattern 119 | 120 | - Flyweight pattern is primarily used to reduce the number of objects created and to decrease memory footprint and increase performance. This type of design pattern comes under structural pattern as this pattern provides ways to decrease object count thus improving the object structure of application. 121 | - Flyweight pattern tries to reuse already existing similar kind objects by storing them and creates new object when no matching object is found. 122 | 123 | 124 | ![image](https://user-images.githubusercontent.com/43011442/117574668-dadb0a00-b0fb-11eb-957b-b51b1dc3450d.png) 125 | 126 | 127 | # Adapter Design Pattern 128 | 129 | - Adapter pattern works as a bridge between two incompatible interfaces. This type of design pattern comes under structural pattern as this pattern combines the capability of two independent interfaces. 130 | - This pattern involves a single class which is responsible to join functionalities of independent or incompatible interfaces. A real life example could be a case of card reader which acts as an adapter between memory card and a laptop. 131 | - You plugin the memory card into card reader and card reader into the laptop so that memory card can be read via laptop. 132 | 133 | 134 | ![image](https://user-images.githubusercontent.com/43011442/117574817-8c7a3b00-b0fc-11eb-844f-fd823476f330.png) 135 | 136 | 137 | # Bridge Design Pattern 138 | 139 | - Bridge is used when we need to decouple an abstraction from its implementation so that the two can vary independently. This type of design pattern comes under structural pattern as this pattern decouples implementation class and abstract class by providing a bridge structure between them. 140 | - This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes independent from interface implementer classes. 141 | - Both types of classes can be altered structurally without affecting each other. 142 | 143 | 144 | ![image](https://user-images.githubusercontent.com/43011442/117574800-72d8f380-b0fc-11eb-813b-b229aacfed71.png) 145 | 146 | 147 | # Observer Design Pattern 148 | 149 | - Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its depenedent objects are to be notified automatically. 150 | - Observer pattern falls under behavioral pattern category. 151 | 152 | 153 | ![image](https://user-images.githubusercontent.com/43011442/117574853-bfbcca00-b0fc-11eb-8e46-c0126653f38f.png) 154 | 155 | 156 | # Some of the Other Common Design Patterns are : 157 | 158 | - Filter Design Pattern 159 | - Command Design Pattern 160 | - Interpreter Design Pattern 161 | - Iterator Design Pattern 162 | - Mediator Design Pattern 163 | - Momento Design Pattern 164 | - State Design Pattern 165 | - Null Object Design Pattern 166 | - Stratergy Design Pattern 167 | - Template Design Pattern 168 | - Visitor Design pattern 169 | - MVC pattern 170 | - Business Deligate Pattern 171 | - Composite Entity Pattern 172 | - Data Access object Pattern 173 | - Front Controller Pattern 174 | - Intercepting Filter Pattern 175 | - Service Locator Pattern 176 | - Transfer Object Pattern 177 | 178 | # Filter Design Pattern 179 | 180 | - Filter pattern or Criteria pattern is a design pattern that enables developers to filter a set of objects using different criteria and chaining them in a decoupled way through logical operations. 181 | - This type of design pattern comes under structural pattern as this pattern combines multiple criteria to obtain single criteria. 182 | 183 | 184 | ![image](https://user-images.githubusercontent.com/43011442/117575193-66559a80-b0fe-11eb-91f3-2e03430e06de.png) 185 | 186 | 187 | # Command Design Pattern 188 | 189 | - Command pattern is a data driven design pattern and falls under behavioral pattern category. 190 | - A request is wrapped under an object as command and passed to invoker object. 191 | - Invoker object looks for the appropriate object which can handle this command and passes the command to the corresponding object which executes the command. 192 | 193 | 194 | ![image](https://user-images.githubusercontent.com/43011442/117575212-7d948800-b0fe-11eb-8377-02eb5a13e6be.png) 195 | 196 | 197 | # Interpreter Design Pattern 198 | 199 | - Interpreter pattern provides a way to evaluate language grammar or expression. 200 | - This type of pattern comes under behavioral pattern. This pattern involves implementing an expression interface which tells to interpret a particular context. 201 | - This pattern is used in SQL parsing, symbol processing engine etc. 202 | 203 | 204 | ![image](https://user-images.githubusercontent.com/43011442/117607829-6dba8980-b17a-11eb-9385-05eefaf0331b.png) 205 | 206 | 207 | # Iterator Design Pattern 208 | 209 | - Iterator pattern is very commonly used design pattern in Java and .Net programming environment. 210 | - This pattern is used to get a way to access the elements of a collection object in sequential manner without any need to know its underlying representation. 211 | 212 | 213 | ![image](https://user-images.githubusercontent.com/43011442/117607920-9f335500-b17a-11eb-80d6-35078ff9fe57.png) 214 | 215 | 216 | # Mediator Design Pattern 217 | 218 | - Mediator pattern is used to reduce communication complexity between multiple objects or classes. 219 | - This pattern provides a mediator class which normally handles all the communications between different classes and supports easy maintenance of the code by loose coupling. 220 | - Mediator pattern falls under behavioral pattern category. 221 | 222 | ![image](https://user-images.githubusercontent.com/43011442/117607974-c2f69b00-b17a-11eb-9cbc-5e66ffff9110.png) 223 | 224 | 225 | # Momento Design Pattern 226 | 227 | - Memento pattern is used to restore state of an object to a previous state. 228 | - Memento pattern falls under behavioral pattern category. 229 | 230 | 231 | ![image](https://user-images.githubusercontent.com/43011442/117608015-dbff4c00-b17a-11eb-91e0-1548b8fa5328.png) 232 | 233 | 234 | # State Design Pattern 235 | 236 | - In State pattern a class behavior changes based on its state. 237 | - This type of design pattern comes under behavior pattern. 238 | - In State pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes. 239 | 240 | 241 | ![image](https://user-images.githubusercontent.com/43011442/117608086-f9ccb100-b17a-11eb-9e15-6fe58d85c4d9.png) 242 | 243 | 244 | # Null Object Design Pattern 245 | 246 | - In Null Object pattern, a null object replaces check of NULL object instance. 247 | - Instead of putting if check for a null value, Null Object reflects a do nothing relationship. 248 | - Such Null object can also be used to provide default behaviour in case data is not available. 249 | - In Null Object pattern, we create an abstract class specifying various operations to be done, concrete classes extending this class and a null object class providing do nothing implemention of this class and will be used seemlessly where we need to check null value. 250 | 251 | 252 | ![image](https://user-images.githubusercontent.com/43011442/117608151-1cf76080-b17b-11eb-9789-a72eda69c333.png) 253 | 254 | 255 | # Stratergy Design Pattern 256 | 257 | - In Strategy pattern, a class behavior or its algorithm can be changed at run time. This type of design pattern comes under behavior pattern. 258 | - In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object. 259 | - The strategy object changes the executing algorithm of the context object. 260 | 261 | 262 | ![image](https://user-images.githubusercontent.com/43011442/117608202-38fb0200-b17b-11eb-9706-98a80b55982b.png) 263 | 264 | 265 | # Template Design Pattern 266 | 267 | - In Template pattern, an abstract class exposes defined way(s)/template(s) to execute its methods. 268 | - Its subclasses can override the method implementation as per need but the invocation is to be in the same way as defined by an abstract class. 269 | - This pattern comes under behavior pattern category. 270 | 271 | 272 | ![image](https://user-images.githubusercontent.com/43011442/117608252-55973a00-b17b-11eb-8dc6-3f2d0ac9854d.png) 273 | 274 | 275 | # Visitor Design pattern 276 | 277 | - In Visitor pattern, we use a visitor class which changes the executing algorithm of an element class. 278 | - By this way, execution algorithm of element can vary as and when visitor varies. 279 | - This pattern comes under behavior pattern category. As per the pattern, element object has to accept the visitor object so that visitor object handles the operation on the element object. 280 | 281 | 282 | ![image](https://user-images.githubusercontent.com/43011442/117608294-6e075480-b17b-11eb-9905-68dbc3978507.png) 283 | 284 | 285 | # MVC pattern 286 | 287 | - MVC Pattern stands for Model-View-Controller Pattern. 288 | - This pattern is used to separate application's concerns. 289 | 290 | 1) Model - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes. 291 | 2) View - View represents the visualization of the data that model contains 292 | 3) Controller - Controller acts on both model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps view and model separate. 293 | 294 | 295 | ![image](https://user-images.githubusercontent.com/43011442/117608598-07366b00-b17c-11eb-9973-a2547873a617.png) 296 | 297 | 298 | # Business Deligate Pattern 299 | 300 | - Business Delegate Pattern is used to decouple presentation tier and business tier. 301 | - It is basically use to reduce communication or remote lookup functionality to business tier code in presentation tier code. 302 | - In business tier we have following entities: 303 | 304 | 1) Client - Presentation tier code may be JSP, servlet or UI java code. 305 | 2) Business Delegate - A single entry point class for client entities to provide access to Business Service methods. 306 | 3) LookUp Service - Lookup service object is responsible to get relative business implementation and provide business object access to business delegate object. 307 | 4) Business Service - Business Service interface. Concrete classes implement this business service to provide actual business implementation logic. 308 | 309 | 310 | ![image](https://user-images.githubusercontent.com/43011442/117609033-dd317880-b17c-11eb-947a-927ab3cedf3c.png) 311 | 312 | 313 | # Composite Entity Pattern 314 | 315 | - Composite Entity pattern is used in EJB persistence mechanism. 316 | - A Composite entity is an EJB entity bean which represents a graph of objects. 317 | - When a composite entity is updated, internally dependent objects beans get updated automatically as being managed by EJB entity bean. 318 | - Following are the participants in Composite Entity Bean: 319 | 320 | 1) Composite Entity - It is primary entity bean. It can be coarse grained or can contain a coarse grained object to be used for persistence purpose. 321 | 2) Coarse-Grained Object - This object contains dependent objects. It has its own life cycle and also manages life cycle of dependent objects. 322 | 3) Dependent Object - Dependent object is an object which depends on coarse grained object for its persistence lifecycle. 323 | 4) Strategies - Strategies represents how to implement a Composite Entity. 324 | 325 | 326 | ![image](https://user-images.githubusercontent.com/43011442/117609115-08b46300-b17d-11eb-9c0f-c71eca6aa876.png) 327 | 328 | 329 | # Data Access object Pattern 330 | 331 | - Data Access Object Pattern or DAO pattern is used to separate low level data accessing API or operations from high level business services. 332 | - Following are the participants in Data Access Object Pattern: 333 | 334 | 1) Data Access Object Interface - This interface defines the standard operations to be performed on a model object(s). 335 | 2) Data Access Object concrete class - This class implements above interface. This class is responsible to get data from a data source which can be database / xml or any other storage mechanism. 336 | 3) Model Object or Value Object - This object is simple POJO containing get/set methods to store data retrieved using DAO class. 337 | 338 | 339 | ![image](https://user-images.githubusercontent.com/43011442/117610670-c0e30b00-b17f-11eb-8436-396d15d4db6f.png) 340 | 341 | 342 | # Front Controller Pattern 343 | 344 | - The front controller design pattern is used to provide a centralized request handling mechanism so that all requests will be handled by a single handler. 345 | - This handler can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers. 346 | - Following are the entities of this type of design pattern: 347 | 348 | 1) Front Controller - Single handler for all kinds of requests coming to the application (either web based/ desktop based). 349 | 2) Dispatcher - Front Controller may use a dispatcher object which can dispatch the request to corresponding specific handler. 350 | 3) View - Views are the object for which the requests are made. 351 | 352 | 353 | ![image](https://user-images.githubusercontent.com/43011442/117610745-dfe19d00-b17f-11eb-89f5-42943b264e4a.png) 354 | 355 | 356 | # Intercepting Filter Pattern 357 | 358 | - The intercepting filter design pattern is used when we want to do some pre-processing / post-processing with request or response of the application. 359 | - Filters are defined and applied on the request before passing the request to actual target application. 360 | - Filters can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers. 361 | - Following are the entities of this type of design pattern: 362 | 363 | 1) Filter - Filter which will performs certain task prior or after execution of request by request handler. 364 | 2) Filter Chain - Filter Chain carries multiple filters and help to execute them in defined order on target. 365 | 3) Target - Target object is the request handler 366 | 4) Filter Manager - Filter Manager manages the filters and Filter Chain. 367 | 5) Client - Client is the object who sends request to the Target object 368 | 369 | 370 | ![image](https://user-images.githubusercontent.com/43011442/117610867-16b7b300-b180-11eb-80d2-db2874db67e8.png) 371 | 372 | 373 | # Service Locator Pattern 374 | 375 | - The service locator design pattern is used when we want to locate various services using JNDI lookup. 376 | - Considering high cost of looking up JNDI for a service, Service Locator pattern makes use of caching technique. 377 | - For the first time a service is required, Service Locator looks up in JNDI and caches the service object. 378 | - Further lookup or same service via Service Locator is done in its cache which improves the performance of application to great extent. 379 | - Following are the entities of this type of design pattern: 380 | 381 | 1) Service - Actual Service which will process the request. Reference of such service is to be looked upon in JNDI server. 382 | 2) Context / Initial Context - JNDI Context carries the reference to service used for lookup purpose. 383 | 3) Service Locator - Service Locator is a single point of contact to get services by JNDI lookup caching the services. 384 | 4) Cache - Cache to store references of services to reuse them 385 | 5) Client - Client is the object that invokes the services via ServiceLocator. 386 | 387 | 388 | ![image](https://user-images.githubusercontent.com/43011442/117610959-3bac2600-b180-11eb-8a66-901c8feb46a9.png) 389 | 390 | 391 | # Transfer Object Pattern 392 | 393 | - The Transfer Object pattern is used when we want to pass data with multiple attributes in one shot from client to server. 394 | - Transfer object is also known as Value Object. 395 | - Transfer Object is a simple POJO class having getter/setter methods and is serializable so that it can be transferred over the network. 396 | - It does not have any behavior. 397 | - Server Side business class normally fetches data from the database and fills the POJO and send it to the client or pass it by value. 398 | - For client, transfer object is read-only. 399 | - Client can create its own transfer object and pass it to server to update values in database in one shot. 400 | - Following are the entities of this type of design pattern: 401 | 402 | 1) Business Object - Business Service fills the Transfer Object with data. 403 | 2) Transfer Object - Simple POJO having methods to set/get attributes only. 404 | 3) Client - Client either requests or sends the Transfer Object to Business Object. 405 | 406 | 407 | ![image](https://user-images.githubusercontent.com/43011442/117611244-c856e400-b180-11eb-9b63-6a7032902b0a.png) 408 | 409 | 410 | # ⚡ Links on Design Patterns 411 | 412 | - [Design Patterns - Wikipeida](https://en.wikipedia.org/wiki/Software_design_pattern) 413 | 414 | - [Java Programming/Design Patterns](https://en.wikibooks.org/wiki/Java_Programming/Design_Patterns) 415 | 416 | - [The JavaTM Tutorials](https://docs.oracle.com/javase/tutorial/) 417 | 418 | - [JavaTM 2 SDK, Standard Edition](https://docs.oracle.com/javase/1.4.2/docs/) 419 | 420 | - [Java DesignPatterns](https://www.javaworld.com/category/design-patterns/) 421 | 422 | # 📺 Youtube Videos 423 | 424 | - [Telusko Learning](https://www.youtube.com/playlist?list=PLsyeobzWxl7r2ZX1fl-7CKnayxHJA_1ol) 425 | 426 | - [coding Simplified](https://www.youtube.com/playlist?list=PLt4nG7RVVk1h9lxOYSOGI9pcP3I5oblbx) 427 | 428 | - [KK Java Tutorials](https://www.youtube.com/playlist?list=PLzS3AYzXBoj8t5hPykr5VU7jG-kEim-LX) 429 | 430 | - [Derek Beans](https://www.youtube.com/playlist?list=PLF206E906175C7E07) 431 | 432 | - [Christopher Okrhavi](https://www.youtube.com/playlist?list=PLrhzvIcii6GNjpARdnO4ueTUAVR9eMBpc) 433 | 434 | - [Rajesh Kumar](https://www.youtube.com/playlist?list=PLZ0uoluqqCdcAln2Hu9J3BlIUHQIMClEN) 435 | 436 | - [Tutorials Point](https://www.youtube.com/playlist?list=PLWPirh4EWFpGeQoTYL5YpzBz8Gjw-sxJb) 437 | 438 | - [Edurekha](https://www.youtube.com/watch?v=C_oPLDaSy-8) 439 | 440 | # 🥅 Useful Books on Java Design Patterns 441 | 442 | [](https://www.amazon.com/exec/obidos/ASIN/0201485397/httpwwwtuto0a-20) 443 | 444 | 445 | [](https://www.amazon.com/exec/obidos/ASIN/0596007124/httpwwwtuto0a-20) 446 | 447 | 448 | [](https://www.amazon.com/exec/obidos/ASIN/0956575803/httpwwwtuto0a-20) 449 | 450 | 451 | [](https://www.amazon.com/exec/obidos/ASIN/0201633612/httpwwwtuto0a-20) 452 | 453 | 454 | [](https://www.amazon.com/exec/obidos/ASIN/0321333020/httpwwwtuto0a-20) 455 | 456 | 457 | [](https://www.amazon.com/exec/obidos/ASIN/0201743973/httpwwwtuto0a-20) 458 | 459 |

460 | **For more queries, reach me through gowthamraj692@gmail.com or whatsapp @ 9698382306** 461 | 462 |

463 |
464 | 465 | # Show some ❤️ by starring this repository !!! 466 | 467 |
468 | 469 | ## Organization Created & Maintained By 470 | 471 | # ![](https://img.shields.io/static/v1?style=for-the-badge&message=Gowthamraj+K&color=007396&label=) 😄 472 | 473 | ![](https://img.shields.io/static/v1?style=for-the-badge&message=Fullstack+Web+Developer&color=0b3d36&label=) ![](https://img.shields.io/static/v1?style=for-the-badge&message=UI+Designer&color=d92323&label=) ![](https://img.shields.io/static/v1?style=for-the-badge&message=Learning+new+things&color=0c0c4f&label=) ![](https://img.shields.io/static/v1?style=for-the-badge&message=Design+Thinker&color=0b3d17&label=) 474 | 475 | ### Connect with me 👋: 476 | 477 | [code-Jamm.in][website1] 478 | [GowthamRaj | YouTube][youtube] 479 | [GowthamRaj ][hackerrank] 480 | [GowthamRaj  | Twitter][twitter] 481 | [GowthamRaj  | LinkedIn][linkedin] 482 | [GowthamRaj  | Instagram][instagram] 483 | [![](https://img.shields.io/badge/9698382306-25D366?style=social&logo=whatsapp&logoColor=green)]() 484 | 485 | ## Copyright-and-license 📌 486 | 487 | Code and documentation Copyright 2021 : **Gowthamraj K** 488 | 489 | 490 | [website1]: https://gowthamrajk.github.io/gowthamrajk-portfolio/ 491 | [hackerrank]: https://www.hackerrank.com/gowthamraj692 492 | [website]: https://github.com/gowthamrajk 493 | [twitter]: https://twitter.com/Gowtham29341737 494 | [youtube]: https://www.youtube.com/channel/UC_Q5Zet9Oz-UVAeJ-oE_uGQ?view_as=subscriber 495 | [instagram]: https://instagram.com/gow_t_h_a_m_r_a_j 496 | [linkedin]: https://www.linkedin.com/in/gowtham-kittusamy-54b835174/ 497 | -------------------------------------------------------------------------------- /Design Pattern tutorials.txt: -------------------------------------------------------------------------------- 1 | 2 | DESIGN PATTERNS : 3 | 4 | - Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the 5 | solution to that problem in such a way that you can use this solution a million times over, without ever doing it the 6 | same way twice. 7 | - Pattern occur in every facet of software development, at every phase, and at every level of detail. 8 | - the ability to recognize patterns allow us to classify problem solutions in terms of problems and contexts. 9 | 10 | - represents the best practices followed by experienced software developers. 11 | - targetted to reduce the problems of object relation & integration. 12 | - Design patterns acts as a template for real world problems 13 | - discoverd in 1994 by a group of 4 members, hence called as GOF patterns (Gang Of Four) 14 | 15 | Categories : 16 | 17 | 1) Creational ==> deals with object creation & initialization (Singleton, Factory, Abstract Factory, Builder, Prototype) 18 | 19 | 2) Structural ==> decoupling Interfaces & implementation (Adapter, Composite, Proxy, FlyWeight, Facade, Bridge, Decorator) 20 | 21 | 3) Behavioural ==> communication between classes and objects (Template method, Mediator, Chain of Responsiblities, Observer, 22 | Stratergy, Command, State, Visitor, Iterator, Interpretor, 23 | Momento) 24 | 25 | - In general, pattern has 4 attributes 26 | NAME => a handle we can use to refer the pattern 27 | PROBLEM => describes when to apply the pattern 28 | SOLUTION => describe the elements that makes up the pattern 29 | CONSEQUENCES => describes the result of using that pattern 30 | 31 | ***************************************************************************************************************************** 32 | 33 | CREATIONAL DESGIN PATTERNS : 34 | 35 | - deals with object creation & Instantiation 36 | - creates objects based on the usecase, reduces the complexity of object creation by adopting the best way to do it. 37 | 38 | ==> (Singleton, Factory, Abstract Factory, Builder, Prototype) 39 | 40 | Abstract Factory -> creates an instance of several families of classes 41 | Builder -> builds complete object from scratch 42 | Factory -> creates object for several group of classes 43 | Prototype -> copy or clone objects 44 | Singleton -> only one instance can be created 45 | Object Pool -> recycle/reuse the objects 46 | 47 | ***************************************************************************************************************************** 48 | 49 | STRUCTURAL DESIGN PATTERNS : 50 | 51 | - These design patterns concern class and object composition. 52 | - decoupling Interfaces & implementation. 53 | - Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities. 54 | 55 | ==> (Adapter, Composite, Proxy, FlyWeight, Facade, Bridge, Decorator) 56 | 57 | ***************************************************************************************************************************** 58 | 59 | BEHAVIOURAL DESIGN PATTERNS : 60 | 61 | - These design patterns are specifically concerned with communication between objects. 62 | 63 | ==> (Template method, Mediator, Chain of Responsiblities, Observer, Stratergy, Command, State, Visitor, Iterator, 64 | Interpretor, Momento) 65 | 66 | ############################################################################################################################# 67 | 68 | 69 | Model View Controller (MVC) : 70 | 71 | - This is the base of all the design patterns 72 | - The main aim of this is to decouple the things (clear seperation of layers so that it won't be tightly coupled) 73 | 74 | MODEL => holds data & manipulates it. eg: student object holds marks, subject, class, etc... 75 | 76 | VIEW => Presentation layer. eg: UI page, charts, tables, etc... 77 | 78 | CONTROLLER => acts as a mediator between model & view, defines the way which the UI wraps with the user. 79 | 80 | ############################################################################################################################# 81 | ############################################################################################################################# 82 | 83 | 84 | JAVA STANDARD PATTERNS : 85 | 86 | 1) Intercepting Filter Pattern : 87 | 88 | - It is used when we want to do some pre-processing / post-processing with request or response of the application. 89 | - Filters are defined and applied on the request before passing the request to actual target application. 90 | - Filters can do the authentication/ authorization/ logging or tracking of request and then pass the requests to 91 | corresponding handlers. 92 | 93 | Filter => Filter which will performs certain task prior or after execution of request by request handler. 94 | 95 | Filter Chain => Filter Chain carries multiple filters and help to execute them in defined order on target. 96 | 97 | Target => Target object is the request handler 98 | 99 | Filter Manager => Filter Manager manages the filters and Filter Chain. 100 | 101 | Client => Client is the object who sends request to the Target object. 102 | 103 | ############################################################################################################################# 104 | 105 | 2) Front Controller Pattern : 106 | 107 | - The front controller design pattern is used to provide a centralized request handling mechanism so that all requests 108 | will be handled by a single handler. 109 | - This handler can do the authentication/ authorization/ logging or tracking of request and then pass the requests to 110 | corresponding handlers. 111 | 112 | Front Controller => Single handler for all kinds of requests coming to the application (either web based/ desktop based). 113 | 114 | Dispatcher => Front Controller may use a dispatcher object which can dispatch the request to corresponding specific handler. 115 | 116 | View => Views are the object for which the requests are made 117 | 118 | 119 | working : 120 | 121 | HTTP request ===> DispatcherServlet <===> Handler Mapping 122 | | <===> Controller 123 | | <===> View Resolver 124 | | <===> View 125 | |<================================= HTTP response 126 | 127 | ############################################################################################################################# 128 | 129 | 3) View Helper Pattern : 130 | 131 | - View Helper Pattern separates the static view such as JSP's from the processing of the business model data. 132 | - Frameworks like Spring and Struts provide their own tag libraries to encapsulate processing logic in a helper instead of 133 | a view such as JSP files. 134 | - Mingling control logic, data access logic and formatting logic within view components lead to problems with modularity, 135 | reuse, maintenance, and role separation. 136 | - Use Views to encapsulate formatting code and Helpers to encapsulate view-processing logic. 137 | - A View delegates its processing responsibilities to its helper classes, implemented as POJOs, custom tags, or tag files. 138 | - Helpers serve as adapters between the view and the model, and perform processing related to formatting logic, such as 139 | generating an HTML table. 140 | 141 | Client => A Client dispatches to the View. 142 | 143 | View => A View represents and displays information to the Client. The information that is used in a dynamic display is 144 | retrieved and converted from a presentation model by helpers. 145 | 146 | Helper1, Helper2 => A helper encapsulates processing logic for generating and formatting a View. A helper typically adapts 147 | a PresentationModel for a view or provides access to the raw data of the PresentationModel. 148 | A view works with any number of helpers, typically implemented as Java- Beans, custom tags, or tag files. 149 | 150 | Presentation Model => The PresentationModel holds the data retrieved from the business service, used to generate the View. 151 | 152 | ############################################################################################################################# 153 | 154 | 4) Business Delegate Pattern : 155 | 156 | - Business Delegate Pattern is used to decouple presentation tier and business tier. 157 | - It is basically use to reduce communication or remote lookup functionality to business tier code in presentation tier code. 158 | 159 | Client => Presentation tier code may be JSP, servlet or UI java code. 160 | 161 | Business Delegate => A single entry point class for client entities to provide access to Business Service methods. 162 | 163 | LookUp Service => Lookup service object is responsible to get relative business implementation and provide business object access to business delegate object. 164 | 165 | Business Service => Business Service interface. Concrete classes implement this business service to provide actual business implementation logic. 166 | 167 | ############################################################################################################################# 168 | 169 | 5) Service Locator Pattern : 170 | 171 | - The service locator design pattern is used when we want to locate various services using JNDI lookup. 172 | - Considering high cost of looking up JNDI for a service, Service Locator pattern makes use of caching technique. 173 | - For the first time a service is required, Service Locator looks up in JNDI and caches the service object. 174 | - Further lookup or same service via Service Locator is done in its cache which improves the performance of application to great extent. 175 | 176 | Service => Actual Service which will process the request. Reference of such service is to be looked upon in JNDI server. 177 | 178 | Context / Initial Context => JNDI Context carries the reference to service used for lookup purpose. 179 | 180 | Service Locator => Service Locator is a single point of contact to get services by JNDI lookup caching the services. 181 | 182 | Cache => Cache to store references of services to reuse them 183 | 184 | Client => Client is the object that invokes the services via ServiceLocator. 185 | 186 | ############################################################################################################################# 187 | 188 | 6) Composite View Pattern : 189 | 190 | - Use Composite Views that are composed of multiple atomic subviews. 191 | - Each subview of the overall template can be included dynamically in the whole, and the layout of the page can be managed 192 | independently of the content. 193 | - For example, the portal sites that include numerous independent subviews, such as news feeds, weather information, and 194 | stock quotes on a single page. 195 | - The layout of the page is managed and modified independently of the subview content. 196 | 197 | Client => A Client dispatches to a View. 198 | View => A View represents the display. 199 | SimpleView => A SimpleView represents an atomic portion of a composite whole. It is also referred to as a view segment or subview. 200 | CompositeView => A CompositeView is composed of multiple Views. Each of these Views is either a SimpleView or itself potentially a CompositeView. 201 | Template => A Template represents the view layout. 202 | 203 | ############################################################################################################################# 204 | 205 | 7) Session Facade Pattern : 206 | 207 | - Facade pattern hides the complexities of the system and provides an interface to the client using which the client can 208 | access the system. 209 | - This type of design pattern comes under structural pattern as this pattern adds an interface to existing system to hide 210 | its complexities. 211 | - This pattern involves a single class which provides simplified methods required by client and delegates calls to methods 212 | of existing system classes. 213 | 214 | Eg : Payment through credit card in swiping machine (It can facilitate to pay options like pin validation, dail, print receipt, 215 | debit card payment, credit card payment, food card, EMI based payment, etc... but don't show its underlying implementation) 216 | 217 | ############################################################################################################################# 218 | 219 | 8) Data Access object Pattern : 220 | 221 | - Data Access Object Pattern or DAO pattern is used to separate low level data accessing API or operations from high level 222 | business services. 223 | - This pattern is used for DAO layered architecture while interacting with the Database. 224 | - This takes care of opening connection, executing query, fetching the resultset data, etc... 225 | 226 | Data Access Object Interface => This interface defines the standard operations to be performed on a model object(s). 227 | 228 | Data Access Object concrete class => This class implements above interface. This class is responsible to get data from a data source which can be database / xml or any other storage mechanism. 229 | 230 | Model Object or Value Object => This object is simple POJO containing get/set methods to store data retrieved using DAO class. 231 | 232 | ############################################################################################################################# 233 | 234 | 9) Value List Handler Pattern : 235 | 236 | - This pattern is mainly used to Iterate over a large result set of values. 237 | - Use a Value List Handler to search, cache the results, and allow the client to traverse and select items from the results. 238 | 239 | - This pattern creates a ValueListHandler to control query execution functionality and results caching. 240 | - The ValueListHandler directly accesses a DAO that can execute the required query. 241 | - The ValueListHandler stores the results obtained from the DAO as a collection of Transfer Objects. 242 | - The client requests the ValueListHandler to provide the query results as needed. 243 | - The ValueListHandler implements an Iterator pattern [GoF] to provide the solution. 244 | 245 | eg: searching the contents in a website by applying various filters on the result 246 | 247 | ############################################################################################################################# 248 | 249 | 10) Transfer Object Pattern : 250 | 251 | - It is mainly used to transfer multiple data elements over a tier. 252 | - The Transfer Object pattern is used when we want to pass data with multiple attributes in one shot from client to server. 253 | - Transfer object is also known as Value Object. 254 | - Transfer Object is a simple POJO class having getter/setter methods and is serializable so that it can be transferred over 255 | the network. It does not have any behavior. 256 | - Server Side business class normally fetches data from the database and fills the POJO and send it to the client or pass 257 | it by value. For client, transfer object is read-only. 258 | - Client can create its own transfer object and pass it to server to update values in database in one shot. 259 | 260 | Business Object => Business Service fills the Transfer Object with data. 261 | 262 | Transfer Object => Simple POJO having methods to set/get attributes only. 263 | 264 | Client => Client either requests or sends the Transfer Object to Business Object. 265 | 266 | ############################################################################################################################# 267 | ############################################################################################################################# 268 | 269 | 270 | CREATIONAL DESIGN PATTERNS : 271 | 272 | 273 | 1) Singleton Design Pattern : 274 | 275 | - It creates only one instance 276 | - It aims to keep a check on initialization of objects of a particular class by ensuring that only one instance of the object 277 | exists throughout the JVM. 278 | - If a class does the common functionalities, singleton objects can be used. 279 | - But if the class do some specific values for each object, there singleton cannot be used. 280 | 281 | Advantages : 282 | 283 | - saves memory 284 | - improves performance 285 | 286 | Implementation rules : 287 | 288 | - private constructors should be used. 289 | 290 | Realtime examples : 291 | 292 | - runtime classes 293 | 294 | eg: 295 | 296 | public class Singleton { 297 | 298 | private static Singleton single_instance = null; 299 | public String s; 300 | 301 | private Singleton() { 302 | s = "Hello, this is Singleton class"; 303 | } 304 | 305 | public static Singleton getInstance() { 306 | if(single_instance == null) { 307 | single_instance = new Singleton(); 308 | } 309 | return single_instance; 310 | } 311 | } 312 | 313 | Calender calenderObj = Calender.getInstance(); 314 | 315 | - Only one instance is ever created and this same shared instance is injected into each colloborating object. 316 | 317 | ***************************************************************************************************************************** 318 | 319 | 2) Factory Design Pattern : 320 | 321 | - This pattern defines an interface for creating object, but let subclasses decide which class to instantiate. 322 | - The Fatory method lets a class defer instantiation to subclass. 323 | 324 | Eg: buying a soap from shop (hamam, rexona, lux) . We only say what soap we need by its name, but we dont need to know 325 | how that soap is manufactured. 326 | 327 | eg: 328 | 329 | public class PolygonFactory { 330 | public Polygon getPolygon(int numberOfSides) { 331 | if(numberOfSides == 3) { 332 | return new Triangle(); 333 | } 334 | if(numberOfSides == 4) { 335 | return new Square(); 336 | } 337 | if(numberOfSides == 5) { 338 | return new Pentagon(); 339 | } 340 | if(numberOfSides == 6) { 341 | return new Hexagon(); 342 | } 343 | if(numberOfSides == 7) { 344 | return new Heptagon(); 345 | } 346 | if(numberOfSides == 8) { 347 | return new Octagon(); 348 | } 349 | return null; 350 | } 351 | } 352 | 353 | ***************************************************************************************************************************** 354 | 355 | 3) Abstract Factory Design Pattern : 356 | 357 | - It adds one level of abstraction to Factory Design Pattern 358 | - It says that just define an abstract class or interface for creating families of related objects but without specifying 359 | their concrete sub-classes. 360 | - Abstract factory lets a class return a factory of classes. 361 | 362 | Java Eg: in java, DocumentBuilderFactory is an abstract factory used to parse the xml documents. 363 | 364 | eg: 365 | 366 | public class GlobalCarFactory { 367 | public CarFactory getCarFactory(String location) { 368 | if(location.equals("USA")) { 369 | return new USACarFactory(); 370 | } 371 | if(location.equals("INDIA")) { 372 | return new IndianCarFactory(); 373 | } 374 | if(location.equals("EUROPE")) { 375 | return new EuropianCarFactory(); 376 | } 377 | if(location.equals("RUSSIA")) { 378 | return new RussianCarFactory(); 379 | } 380 | return null; 381 | } 382 | } 383 | 384 | ***************************************************************************************************************************** 385 | 386 | 4) Prototype Design Pattern : 387 | 388 | - It says that cloning of an existing object instead of creating new one and can also be customized as per the requirement. 389 | - For example, an object is to be created after a costly database operation. 390 | We can cache the object, returns its clone on next request and update the database as and when needed thus reducing 391 | database calls. 392 | 393 | Advantages : 394 | 395 | - saves memory, improves computation process. 396 | 397 | Realtime Eg : download a movie from internet and share it with friends through copying in dvd, pendrive,etc... 398 | 399 | ***************************************************************************************************************************** 400 | 401 | 5) Object Pool Design Pattern : 402 | 403 | - It is a container which contains specified amount of objects. 404 | - when an object is taken from the pool, it is not available in the pool until it is put back. 405 | - Objects in the pool have a lifecycle: creation, validation & destroy. 406 | 407 | Advantages : 408 | 409 | - saves memory 410 | - increases performance 411 | - reduces object creation and saves resources 412 | 413 | Realtime Eg: library - there will be many books in library. If one person needs a book which already one person is reading, 414 | new person has to wait until he returns that book. Same way the objects in the pool are reused. 415 | 416 | Java Eg: creation database connection through DataSource object and managing it in connection pool. 417 | 418 | ***************************************************************************************************************************** 419 | 420 | 6) Builder Design Pattern : 421 | 422 | - It says that construct a complex object from simple objects using step-by-step approach. 423 | - This type of design pattern comes under creational pattern as this pattern provides one 424 | of the best ways to create an object. 425 | 426 | eg: Meal builder class, which can build a meal(veg/non-veg) with the meal details as a class, packing as seperate class, etc... 427 | 428 | Realtime Eg: laptop (plugin memory disk, plugin processor, display screen etc... And assesmble as a single laptop) 429 | 430 | Preparing pizza => pizza base+toppins+spices,etc... 431 | 432 | ***************************************************************************************************************************** 433 | ***************************************************************************************************************************** 434 | 435 | STRUCTURAL DESIGN PATTERNS : 436 | 437 | 7) Adapter Design Pattern : 438 | 439 | - just convert the interface of a class to another interface that a client wants. 440 | - Adapter pattern works as a bridge between two incompatible interfaces. 441 | - This pattern involves a single class which is responsible to join functionalities of independent or incompatible interfaces. 442 | 443 | - A real life example could be a case of card reader which acts as an adapter between memory card and a laptop. 444 | You plugin the memory card into card reader and card reader into the laptop so that memory card can be read via laptop. 445 | 446 | Java example : adapter that can adapt to different database configurations like oracledb, sybase, mysql, postgresql, etc.. 447 | 448 | Realtime examples : 449 | - Mac usbc to usb, memory card reader, phone charger to plug 220v to 9v. 450 | 451 | - Let's take a look at a person travelling in different countries with their laptop and mobile device. we have a different 452 | electric socket, volt, frequency in different countries and adapter makes use of any appliance free to work. 453 | 454 | ***************************************************************************************************************************** 455 | 456 | 8) Decorator Design Pattern : 457 | 458 | - It says that just attach a flexible additional responsiblities to an oject dynamically. 459 | - Decorator pattern allows a user to add new functionality to an existing object without altering its structure. 460 | - This type of design pattern comes under structural pattern as this pattern acts as a wrapper to existing class. 461 | - This pattern creates a decorator class which wraps the original class and provides additional functionality keeping 462 | class methods signature intact. 463 | 464 | - whenever an objects wants to behave dynamically based on the request / when we want to add some additional responsiblity 465 | without affecting the actual one, we can use this pattern. 466 | 467 | Java Eg: 468 | 469 | -> adding red border to a shape drawn (square/rectangle/circle) 470 | -> Logger (it is one of the best example for decorator pattern) 471 | 472 | Realtime Example : 473 | 474 | -> Ice cream => the ice cone will be already prepared and kept, based on the customer need, the vannila/chocoloate/strawberry 475 | cream will be filled at runtime and given to the user. 476 | Pizza => the pizza base will be common. the spice and topings will be different based on the customer need. 477 | 478 | ***************************************************************************************************************************** 479 | 480 | 9) Bridge Design Pattern : 481 | 482 | - It says that decouple the functional abstraction from the implementation so that the two can vary independently. 483 | - This type of design pattern comes under structural pattern as this pattern decouples implementation class and 484 | abstract class by providing a bridge structure between them. 485 | - This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes independent 486 | from interface implementer classes. 487 | - Both types of classes can be altered structurally without affecting each other. 488 | 489 | eg: creating a circle by shape object and using an interface as a bridge which can create object for drawing red/green circles. 490 | 491 | Realtime example : 492 | 493 | when user click on a send message button, the message will be sent. but user don't need to know the underlying implementation 494 | behind the process of sending message. here button will be hiding/abstracting the behind mechanisms and acts like a bridge. 495 | 496 | ***************************************************************************************************************************** 497 | 498 | 10) FlyWeight Design Pattern : 499 | 500 | - It says that just to reuse already existing similar kind of objects by storing them and create new object when no matching 501 | object is found. 502 | - creating large number of objects can be avoided by using this flyweight pattern. 503 | - It is primarily used to reduce the number of objects created and to decrease memory footprint and increase performance. 504 | - This type of design pattern comes under structural pattern as this pattern provides ways to decrease object count thus 505 | improving the object structure of application. 506 | - Flyweight pattern tries to reuse already existing similar kind objects by storing them and creates new object when 507 | no matching object is found. 508 | - Objects are shared which are of similar nature. 509 | 510 | eg: Drawing 20 circles of different locations, but create only 5 objects. 511 | Only 5 colors are available so color property is used to check already existing Circle objects. 512 | 513 | Realtime Eg : 514 | 515 | - Taking one printout copy and taking 1000 xerox copies to save money instead of directly taking 1000 print outs. 516 | 517 | ***************************************************************************************************************************** 518 | 519 | 11) Proxy Design Pattern : 520 | 521 | - In proxy pattern, a class represents functionality of another class. 522 | - This type of design pattern comes under structural pattern. 523 | - In proxy pattern, we create object having original object to interface its functionality to outer world. 524 | - provides the control for accessing the original object. 525 | - so we can perform many operations like hiding the information or original object, on demand loading, etc... 526 | 527 | => 3 types of proxy are widely used : 528 | 529 | Virtual Proxy => the real object is only created when the client request/access the object. 530 | 531 | Remote Proxy => provides a local representative for an object that resides in a different address space. 532 | 533 | Protective Proxy => It controls access to the master object by checking the accessiblity, etc... 534 | 535 | eg: real image and proxy image classes which implements image interface. 536 | 537 | -> when the client calls the real object, the proxy object comes into act and controls the access by checking whether the 538 | client is accessible to that real object or not. 539 | 540 | Realtime Eg: 541 | 542 | -> when we need some money, we have two ways. 1) directly go to bank, fill the chalan, get the amount. 2) go to nearby ATM, 543 | enter PIN and amount, get amount. here 2nd approach is most prefered since it saves time and effort. here, ATM is a proxy 544 | object. when we enter the card PIN & amount, the proxy object now invokes the master object(bank) to check the credentials, 545 | check sufficient balance, debit amount and the proxy object returns result(money) to the user. 546 | 547 | ***************************************************************************************************************************** 548 | 549 | 12) Composite Design Pattern : 550 | 551 | - The objects are represented in a Tree structure. 552 | - Composite pattern is used where we need to treat a group of objects in similar way as a single object. 553 | - This type of design pattern comes under structural pattern as this pattern creates a tree structure of group of objects. 554 | - This pattern creates a class that contains group of its own objects & this class provides ways to modify its group of 555 | same objects. 556 | 557 | - If any operation is applied on any of the leaf objects, it should also be performed on other leaf and composite objects. 558 | 559 | Eg: Car 560 | / \ 561 | engine tyre 562 | / \ 563 | electrical valves 564 | / \ 565 | wires sensors 566 | 567 | -> car having engine & tyre as child objects, engine has electrical & valves as child objects, electrical has wires & sensors 568 | as child objects. 569 | -> any object that has some child objects is called as composite objects (car, engine, electrical) 570 | -> tyre, valves, wires, sensors are called as leaf objects hence they don't have any child objects. 571 | 572 | ***************************************************************************************************************************** 573 | 574 | 13) Facade Design Pattern : 575 | 576 | - Facade means Front view(what ever we see at the front) 577 | - It means single class representing the entire system 578 | - A simple Interface provided for a comples system environment. 579 | - It is a structural design pattern since it given a structure to the object system. 580 | 581 | Realtime Eg : 582 | 583 | - ATM => The end user will get a simple user interface just to enter PIN and enter amount. but at the backside, It does 584 | various complex process like account number validation, checking sufficient funds, pin validation, security code, 585 | money debit, etc... 586 | 587 | ***************************************************************************************************************************** 588 | ***************************************************************************************************************************** 589 | 590 | BEHAVIOURAL DESIGN PATTERNS : 591 | 592 | 14) Chain of Responsiblities Design Pattern : 593 | 594 | - Avoid coupling the sender of a request to its receiver by giving multiple objects a chance to handle the request. 595 | eg: an ATM uses this pattern in cash withdrawal process. 596 | 597 | - The chain of responsibility pattern creates a chain of receiver objects for a request. 598 | - This pattern decouples sender and receiver of a request based on type of request. 599 | - This pattern comes under behavioral patterns. 600 | - In this pattern, normally each receiver contains reference to another receiver. 601 | - If one object cannot handle the request then it passes the same to the next receiver and so on. 602 | 603 | eg: filter chain is also an example of chain of responsiblities 604 | 605 | Realtime Eg : 606 | 607 | -> One receiver => when a person asks question to person1 in a quiz competetion, if he don't know the answer, he will pass 608 | the question to person2, and if he don't know, passes to person3 and so on. 609 | One or more receivers => ATM cash withdraw machine (when rs 620 is withdrawn, 1*500 = 500, 1*100 = 100, 1*20 = 20. here 610 | three types of receivers acts and gives the money accordingly) 611 | 612 | ***************************************************************************************************************************** 613 | 614 | 15) Iterator Design Pattern : 615 | 616 | - To access the elements of an aggregate object sequentially without exposing its underlying implementation. 617 | - Iterator pattern is very commonly used design pattern in Java and .Net programming environment. 618 | - This pattern is used to get a way to access the elements of a collection object in sequential manner without any need to 619 | know its underlying representation. 620 | 621 | eg: a helper boy helps a farmer to sell his goods to people who are standing in a queue with a token based system where 622 | when one person is completed, farmer calls next and the boy send the next person in the queue. (the farmer don't know 623 | the actual process which the boy follows) 624 | 625 | List numbers = Arrays.asList(1,2,3,4,5,6,7,8); 626 | numbers.forEach(number -> { 627 | System.out.print("."); 628 | System.out.print(number); 629 | }); 630 | 631 | ***************************************************************************************************************************** 632 | 633 | 16) Observer Design Pattern : 634 | 635 | - Also called as Listener design pattern. 636 | - It just define a One-to-many dependency so that when one object changes state, all its dependent are notified and updated 637 | automatically. 638 | - Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, 639 | its depenedent objects are to be notified automatically. 640 | - more loosely coupled. 641 | 642 | notify() 643 | subject ============> SlackObserver 644 | 645 | notify() 646 | ============> EmailObserver 647 | 648 | notify() 649 | ============> screenObserver 650 | 651 | Realtime Eg : 652 | 653 | -> when we want to buy a smart Tv online, but the project is outof stock right now. we would register for that project and 654 | wait for it. once the product is available, all the perople who have registered will get notified about it. here the 655 | tv is the subject, people are the observers. each observer don't know about each other, but the subject maintains info 656 | about all the registered observers. 657 | 658 | ***************************************************************************************************************************** 659 | 660 | 17) Mediator Design Pattern : 661 | 662 | - It is used to reduce the communication complexity between multiple objects/classes. 663 | - This pattern provides a mediator class which normally handles all the communications between different classes 664 | and supports easy maintainability of the code by loose coupling. 665 | 666 | eg: user using a chatroom as a mediator to share their messages. 667 | 668 | Realtime Example : 669 | 670 | -> In an airport, if three flights A,B,C are landing at a same time, the ATC(Air Traffic Controller) will act as a mediator 671 | which communicates with other objects(flights) and handles their requests and communicate with them. 672 | 673 | ***************************************************************************************************************************** 674 | 675 | 18) Stratergy Design Pattern : 676 | 677 | - It defines a family of functionalitiy, encapsulate each one and make then interchangeable. 678 | - In Strategy pattern, a class behavior or its algorithm can be changed at run time. 679 | - In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies 680 | as per its strategy object. 681 | - The strategy object changes the executing algorithm of the context object. 682 | 683 | - It is used when there are multiple algorithms for a specific task and the client finds the best implementation. 684 | 685 | eg: executing the stratergies as addition/subtraction/multiplication/division operation classes that implements from operation 686 | interface which can be changed/called at run time dynamically. 687 | 688 | Realtime Eg : 689 | 690 | -> when we go for a shopping mall and purchase for 10,000 rs, we have multiple payment options like cash/credit card/ 691 | debit card. we can choose the appropriate option to purchase and pay through it. 692 | 693 | ***************************************************************************************************************************** 694 | 695 | 19) Command Design Pattern : 696 | 697 | - It says that encapsulate a request under an object as a command and pass it to invoker object. Invoker object looks for the 698 | appropriate object which can handle this command and pass the command to the corresponding object and that object executes 699 | the command. 700 | - It is a data driven design pattern 701 | 702 | eg: invoking the order interface which can either book order or sell order as its implementing classes. 703 | 704 | ***************************************************************************************************************************** 705 | 706 | 20) Visitor Design Pattern : 707 | 708 | - It changes the execution algorithm of various objects as the visitor varies 709 | - Element object has to accept the visitor object so that the visitor can execute its algorithm on the element object. 710 | - By this way, execution algorithm of element can vary as and when visitor varies. 711 | - This pattern comes under behavior pattern category. 712 | - As per the pattern, element object has to accept the visitor object so that visitor object handles the operation on the 713 | element object. 714 | 715 | Realtime Eg: 716 | 717 | -> considering a country which varies the tax for every month based on the food type. 718 | 719 | -> when we invite our friends, family to a function, the visitors will decide to buy gifts differently based on the function 720 | they are invited. 721 | 722 | ***************************************************************************************************************************** 723 | 724 | 21) State Design Pattern : 725 | 726 | - In State pattern a class behavior changes based on its state. 727 | - This type of design pattern comes under behavior pattern. 728 | - In State pattern, we create objects which represent various states and a context object whose behavior varies as its 729 | state object changes 730 | - Based on the state, the behaviour will be completely changes. 731 | 732 | Realtime Eg : 733 | 734 | -> ATM machine => state 1 : when card not inserted, no process will be done. 735 | state 2 : when card inserted => validate the PIN, check balance, withdraw, etc... 736 | 737 | 738 | -> Human => 8.00 am -> wakeup 739 | 9.30 am -> brakefast 740 | 10.00 am -> work started 741 | 1.00 pm -> lunch 742 | 6.00 pm -> work ended 743 | 8.00 pm -> dinner 744 | 10.00 pm -> sleep 745 | 746 | (based on the state of object, its behaviour also changes completely) 747 | 748 | ***************************************************************************************************************************** 749 | 750 | 22) Null Object Design Pattern : 751 | 752 | - It replaces "null" checks. 753 | -If we follow this pattern, we can overcome the traditional way of null checks. 754 | - Default behaviour of objects which has "null" or nothing 755 | - It would be very useful if we want some special flow for something that contains null or nothing in it. 756 | 757 | Eg: Spam classification 758 | 759 | 760 | ***************************************************************************************************************************** 761 | 762 | 23) Template Method Design Pattern : 763 | 764 | - An abstract class exposes defined way(s)/template(s) to execute its methods. 765 | - Its subclasses can override the method implementation as per need but the invocation is to be in the same way as defined 766 | by an abstract class. 767 | - This pattern comes under behavior pattern category. 768 | - It defines a sequence of steps of an algorithm. 769 | 770 | Eg: House Building => basement, pillars, side walls, roof, etc... 771 | 772 | Software Development => Analysis, Design, Development, test. 773 | 774 | - certain defined steps are followed as templates. 775 | 776 | ***************************************************************************************************************************** 777 | 778 | 24) Interpreter Design Pattern : 779 | 780 | - It provides a way to evaluate language grammer expression 781 | - Java compiler that interprets source code into byte-code. 782 | - defines a gramatical expression for a language and an interpreter to interpret the grammer 783 | - widely used in compiler used in object oriented programming languages 784 | 785 | Eg : Java compiler 786 | 787 | ***************************************************************************************************************************** 788 | 789 | 25) Momento Design Pattern : 790 | 791 | - It maintains the previous state information eg: undo / rollback 792 | - Basic objects that is stored in different states. 793 | 794 | Eg : 795 | 796 | Bank transaction -> depositing 100000, debiting 5000, balance is 95000. Now if we want to deposit 5000, then it goes to the 797 | previous transaction with balance of 100000 798 | 799 | ***************************************************************************************************************************** 800 | ***************************************************************************************************************************** 801 | 802 | 803 | 804 | --------------------------------------------------------------------------------