Saturday 1 October 2022

 Design Pattern: Command

a)Command Design Pattern:

In command design pattern, we overwrite a method in interface in such a way that we can automate operations like LIGHTS ON or OFF, BUTTON ON or OFF, MODE ON or OFF, MACHINE ON or OFF, etc.

Basically, this design pattern is used to execute binary (ON or OFF), ternary (ON, HOLD, OFF) or multiple stages of operation (like MODE 1, 2, 3 , 4, 5, 6, etc in various machines)

//create an interface with execute method defined in it

a) interface Command{

    public void execute();

}

// create a concrete class which will have different operations in it

b) public class Bulb {

   public void on(){

       System.out.println("Bulb is turned on");

}

  public void off(){

     System.out.println("Bulb is turned off");

}

}

//Create a concrete class which will execute command design pattern

c) public class BulbOnCommand implements Command {

     private Bulb bulb;

     public BulbOnCommand(Bulb bulb){

     this.bulb = bulb;

}

  public void execute(){

 bulb.on();  }

}

d) public class BulbOffCommand implements Command {

     private Bulb bulb;

     public BulbOffCommand(Bulb bulb){

     this.bulb = bulb;

}

  public void execute(){

 bulb.off();  }

}

//User class which will execute command logic

e) public class CommandDemo {

    Command command = new 



}

 Design Pattern: Strategy 

a)Strategy Design Pattern:

In strategy design pattern, we can change class behaviour or algorithm on fly.

E.g.: We create interface which accepts two numbers. Now, we can call either of the concrete class which is implementing logic for this interface and thus change the behavior of final calling class.


//Create an interface

a) public interface Numbers {

     int operation(int a, int b);

}

//Create concrete classes which will implement above interface

b) public class AddNumber implement Numbers {

  @Override

   public int operation(int a, intb){

   int c = a+b;

return c;

}

}

c) public class SubtractNumber implement Numbers {

@Override

   public int operation(int a, intb){

   int c = a-b;

return c;

}

}

//Create intermediate class which implements the strategy classes above

d) public class Context {

private Numbers numbers;


//this is parametrized class instance of Context

public class Context(Numbers numbers){

this.numbers = numbers;

}

public int mathOperation(int c, int d){

   numbers.operation(c,d)

}

}

//Now implement strategy class

e) public class StrategyDemo {

  

        public void strategyMethod(){

Context addContext = new Context(new AddNumber());

addContext.mathOperation(7,8); 

//output here is 15 because it call operation method from AddNumber class

Context subContext = new Context(new SubtractNumber());

subContext.mathOperation(4,2);

// output is 2 because it will call operation method from SubstractNumber class

}

}

//If you see here, we can either call the SubtractNumber or AddNumber class and thus change the final outcome of the strategyMethod()


 Design Pattern: Mediator

a)Mediator Design Pattern:

In mediator pattern,  we develop as class which act as coupling among different  concrete classes. It can look like Facade or bridge design pattern at times, but difference lies in it that it calls object of different classes and their methods as per need.


E.g.: We want to build a bottle filling plant. 

The processes in it are: 

a) Create a bottle,

b) Fill it with juice,

c) Put air-tight cap on it,

d) Put label,

e) Dispatch it

1) Create multiple classes for functionality:

a) public class Bottle(){

  public String createBot(String message){

System.out.println(message);

}

}

b) public class FillJuice {

int processValue;

print int processParam(){

int formula = (3.14*7.9(12)+12*34);

formula = processValue;

return formula;

}

  public String fill(){

System.out.println("Fill juice in bottle with process prameter: " + processValue);

}

}

c) public class BottlePack{

  public String pack(){

  System.out.println("Bottle capped, labelled & ready for dispatch");

}

}

//Create concrete class which calls all the above classes and executes the bottle filling process

d) public class BottleFill {

Bottle bottle = new Bottle();

FillJuice fillJuice = new FillJuice();

BottlePack bottlePack = new BottlePack();

bottle.createBot("Create a glass bottle for juice");

fillJuice.fill();

bottlePack.pack();

}


 Design Pattern: Bridge  & Facade 

a)Bridge Design Pattern:

In bridge design pattern, we design in such a way that we keep abstract class/ interface functioning separate from Concrete class.

This way, we can alter the abstract class methods and still not affect the functioning of concrete class. Bridge design pattern is mostly designed for bridging between abstract class and concrete class, because in abstract class can add or delete methods and it shouldn't affect functioning of concrete class.

a) abstract class bottle(){

  void cap();

int shape();

public String color(){

System.out.println("The bottle color by default is white");

}

}

//Concrete class

b) public class GlassBottle extends bottle{


@Overwrite

public void cap(){

System.out.println("The bottle has red cap");

}

@Overwrite

public int shape(){

int width =10;

int height = 10;

int area = width* height;

System.out.println("The bottle cross-section is:" + area);

}


public String message(){

System.out.println("The bottle is for cold-drink purpose");

}

}

// Bridging class

c) public class BridgingClass {

GlassBottle glassBot = new GlassBottle();

glassBot.message();

glassBot.shape();

glassBot.cap();

glassBot.color();

}

b)Facade Design Pattern:

In facade design pattern, we design in such a way that we share a different class which is not concrete or implementation class of interface or abstract class.

This way, we donot expose the logic used in concrete class and if saved from changes by external user.

1) Create products in form of interfaces:

a) interface bottle(){

  void cap();

int shape();

String color();

}

//Concrete class to implement logic for interface

b) public class OilBottle implements Bottle {

  String capShape = "Circular";

 String capMaterial = "aluminium";

  @Override

   public void cap() {

   System.out.println("The cap is : " + capShape +  "and " + capMaterial + "with company logo on it");

}

 String bottleShape = "Cylindrical";

 int height = 12;

 int diameter = 10;

int volumeBottle;

  

  public int shape(){

   System.out.println("The bottleShape is : " + bottleShape);

  int areaBottle = 3.14 * height * (diameter/2)*(diameter/2);

  return areaBottle;

}


 String bottleColor = "red";  

public String color(){

  return bottleColor;

}

}

//Another concrete class

c) public class JuiceBottle implements Bottle {

  String capShape = "Circular";

 String capMaterial = "plastic";

  @Override

   public void cap() {

   System.out.println("The cap is : " + capShape +  "and " + capMaterial + "with company logo on it");

}

 String bottleShape = "Cylindrical";

 int height = 12;

 int diameter = 10;

int volumeBottle;

  

  public int shape(){

   System.out.println("The bottleShape is : " + bottleShape);

  int areaBottle = 3.14 * height * (diameter/2)*(diameter/2);

  return areaBottle;

}


 String bottleColor = "white";  

public String color(){

  return bottleColor;

}

}

d)Intermediate class

public class BottleClass {

         JuiceBottle juiceBot = new JuiceBottle();

       OilBottle oilBottle = new OilBottle();

     public void oilBottleMet(){

      oilBottle.cap();

       oilBottle.shape();

      oilBottle.color();

}


//This method will call all the methods of juice bottle class

 public void juiceBottleMet(){

      juiceBottle.cap();

       juiceBottle.shape();

      juiceBottle.color();

}


}

//Facade class is calling intermediate class which will publish all the methods of required concrete class

d) public FacadeClass {

BottleClass productJuiceBot = new BottleClass();

productJuiceBot.juiceBottleMet();

BottleClass productOilBot = new BottleClass();

productOilBot.oilBottleMet();

}

Sunday 25 September 2022

 Design Pattern: Prototype & Singleton Design pattern 

a)Prototype Design Pattern:

This design pattern is next step of Abstract Factory, Factory or Builder design pattern. It will use a concrete class which is ready-made with all the parameter values  or most of them available. 

E.g. A shop X design comes with 6 chairs, 3 tables, 1 fridge, 200 juice bottles &

A shop Y design comes with 10 chairs, 3 tables, 2 fridge, 400 juice bottles, 200 glass soda bottles.

So user who needs X, he will directly chose that and one who needs Y, he will get all the facilities in ready-made format.

public  Shop selectShop(int budget){

 Shop shop;

if(budget > 1000000 && bugdet < 20 00 000){

  shop = new ShopX();

}

else if(budget > 20 00 000){

 shop = new ShopY();

}

else 

 shop = null;


return shop;

}

 Design Pattern: Builder

a)Builder Design Pattern:

In builder design pattern, we use same logic like abstract factory but only difference is that apart from implementing methods of abstract factory class, the concrete class also has extra methods which will impart additional functionality to the final user who will use that concrete class.

Refer to abstract factory page for understanding the logic.

Only change is in concrete class (JuiceShop), apart from methods for creating chair, table, shelf & bottles, we have extra methods like designRoom, ventilationSystem, paymentSystem, etc. 

4) Create concrete class which will implement above abstract class and its methods as per requirements

public class JuiceShop implements shopSetUp(){

          Chair chair;

         Shelf shelf;

         Table table;

         Bottle bottle;

//All the above classes will be used in methods below

           public  chair createChair(String material){

          if(material.equalsIgnoreCase("WOODEN")){

             chair = new WoodenChair();

         else if(material.equalsIgnoreCase("METAL")){

            chair = new MetalChair();

         else if(material.equalsIgnoreCase("PLASTIC")){

           chair = new PlasticChair();

         else if(material.equalsIgnoreCase("FIBREGLASS"){

         chair = new FibreChair();

        else 

           chair = null;

       return chair;

}


             public  table createTable(String material){

          if(material.equalsIgnoreCase("WOODEN")){

             table = new WoodenTable();

         else if(material.equalsIgnoreCase("METAL")){

           table = new MetalTable();

         else if(material.equalsIgnoreCase("PLASTIC")){

           table = new PlasticTable();

         else if(material.equalsIgnoreCase("FIBREGLASS"){

         table = new FibreTable();

        else 

           table = null;

       return table;

}

   public  shelf createShelf(String material){

          if(material.equalsIgnoreCase("WOODEN")){

             shelf = new WoodenShelf();

         else if(material.equalsIgnoreCase("METAL")){

           shelf = new MetalShelf();

         else if(material.equalsIgnoreCase("PLASTIC")){

           shelf = new PlasticShelf();

         else if(material.equalsIgnoreCase("FIBREGLASS"){

         shelf = new FibreShelf();

        else 

           shelf = null;

       return shelf;

}

 public  bottle createBottle(String material){

          if(material.equalsIgnoreCase("BAMBOO")){

             bottle = new BambooBottle();

         else if(material.equalsIgnoreCase("METAL")){

           bottle = new MetalBottle();

         else if(material.equalsIgnoreCase("PLASTIC")){

           bottle = new PlasticBottle();

         else if(material.equalsIgnoreCase("FIBREGLASS"){

         bottle = new FibreBottle();

        else 

           bottle = null;

       return bottle;

}

   public String paymentSystem(String location){

    String payment;

   if(location.equalsIgnoreCase("as shop"){

     payment = "Cash & card";

   else if(location.equalsIgnoreCase("on stall"){

    payment = "Cash & mobile digital";

 else if(location.equalsIgnoreCase("in mall"){

  payment = "Cash, card & online digital";

 else

  payment = "Cash";

     }

public String ventilationSystem(String location){

    String ventilation;

   if(location.equalsIgnoreCase("as shop"){

     ventilation = "Fan & natural vents";

   else if(location.equalsIgnoreCase("on stall"){

    ventilation = "Fan";

 else if(location.equalsIgnoreCase("in mall"){

  ventilation = "Fan & AC";

 else

  ventilation = "natural ventilation";

     }


public String designRoom(String location){

    String space;

   if(location.equalsIgnoreCase("as shop"){

     space = "Buy shop as per expected customer capacity & goods";

   else if(location.equalsIgnoreCase("on stall"){

    space = "Buy simple cart with minimal size to accommodate goods";

 else if(location.equalsIgnoreCase("in mall"){

  space = "Standard shop outlet as franchaise or outlet";

 else

  space = "needs calculation to decide";

     }

}


Design Pattern: Abstract Factory 

a)Abstract Factory Design Pattern:

In factory design pattern, we saw that for particular product like bottle, we have methods defined in it and then we implement them. In abstract factory, we go one more step ahead and it combine multiple products which final user may need. 

E.g. A shop will need bottle, chair, table, refrigerator, cupboard/ shelves to stack products, payment system and so on.

So what abstract factory will do is composed of multiple steps:

1) Create Abstract products in form of interfaces:

a) interface bottle(){

  void cap();

int shape();

String color();

}

b) interface chair(){

  void designType();

int specifications();

String color();

}

c) interface table(){

  void designType();

int material();

String color();

}

d) interface shelf(){

String design();

int material();

String specifications();

}

2) Create concrete classes which will implement the above interfaces for each product:

a) public class OilBottle implements Bottle {

  String capShape = "Circular";

 String capMaterial = "aluminium";

  @Override

   public void cap() {

   System.out.println("The cap is : " + capShape +  "and " + capMaterial + "with company logo on it");

}

 String bottleShape = "Cylindrical";

 int height = 12;

 int diameter = 10;

int volumeBottle;

  

  public int shape(){

   System.out.println("The bottleShape is : " + bottleShape);

  int areaBottle = 3.14 * height * (diameter/2)*(diameter/2);

  return areaBottle;

}


 String bottleColor = "red";  

public String color(){

  return bottleColor;

}

}


In same way, we will implement classes like juiceBottle, plasticBottle, sauceChair, chemicalChair, etc. 

b) public class WoodenChair implements Chair {

void designType();

int specifications();

String color();

  String chairType = "Victorian era";

 String chairSize = "rigid & heavy";

  @Override

   public void designType() {

   System.out.println("The chair is : " + chairType +  "and " + chairSize + "with company logo on it");

}

 String chairShape = "Four sturdy twisted legs & two hand-supports with flat - thick walled back with neck support");

 int legVolume = 88;

 int baseInSqIN = 336;

String dimensions= "in";

  

  public int specification(){

   System.out.println("The chairShape is : " + chairShape);

  int specChair = legVolume*4 + baseInSqIN;

  return specChair;

}


 String chairColor = "red";  

public String color(){

  return chairColor;

}

}

In same way, we will implement classes like metalicChair, plasticChair, fibreglassChair, epoxyMetalChair, etc. 

In same way, we will implement classes for table like metalTable, plasticTable, epoxyTable, chemicalResinTable, etc. & for shelf like metalShelf, plasticShelf, epoxyShelf, chemicalResinShelf, etc

3) Create abstract classes which will have methods defined to create above different products:

interface shopSetUp(){

  chair createChair(String material);

bottle createBottle(String material);

table createTable(String material);

shelf createShelf(String material);

}

4) Create concrete class which will implement above abstract class and its methods as per requirements

public class JuiceShop implements shopSetUp(){

          Chair chair;

         Shelf shelf;

         Table table;

         Bottle bottle;

//All the above classes will be used in methods below

           public  chair createChair(String material){

          if(material.equalsIgnoreCase("WOODEN")){

             chair = new WoodenChair();

         else if(material.equalsIgnoreCase("METAL")){

            chair = new MetalChair();

         else if(material.equalsIgnoreCase("PLASTIC")){

           chair = new PlasticChair();

         else if(material.equalsIgnoreCase("FIBREGLASS"){

         chair = new FibreChair();

        else 

           chair = null;

       return chair;

}


             public  table createTable(String material){

          if(material.equalsIgnoreCase("WOODEN")){

             table = new WoodenTable();

         else if(material.equalsIgnoreCase("METAL")){

           table = new MetalTable();

         else if(material.equalsIgnoreCase("PLASTIC")){

           table = new PlasticTable();

         else if(material.equalsIgnoreCase("FIBREGLASS"){

         table = new FibreTable();

        else 

           table = null;

       return table;

}

   public  shelf createShelf(String material){

          if(material.equalsIgnoreCase("WOODEN")){

             shelf = new WoodenShelf();

         else if(material.equalsIgnoreCase("METAL")){

           shelf = new MetalShelf();

         else if(material.equalsIgnoreCase("PLASTIC")){

           shelf = new PlasticShelf();

         else if(material.equalsIgnoreCase("FIBREGLASS"){

         shelf = new FibreShelf();

        else 

           shelf = null;

       return shelf;

}

 public  bottle createBottle(String material){

          if(material.equalsIgnoreCase("BAMBOO")){

             bottle = new BambooBottle();

         else if(material.equalsIgnoreCase("METAL")){

           bottle = new MetalBottle();

         else if(material.equalsIgnoreCase("PLASTIC")){

           bottle = new PlasticBottle();

         else if(material.equalsIgnoreCase("FIBREGLASS"){

         bottle = new FibreBottle();

        else 

           bottle = null;

       return bottle;

}


}


 Design Patterns (Java): Factory Design Pattern

a)Factory Design Pattern:

In this design pattern, we have an interface with methods defined in it and then that interface is called and methods are implemented with logic internally.


E.g.:


public interface Bottle {

void cap();

int shape();

String color();

}

This interface: bottle, is now implemented by concrete classes below:

a) public class OilBottle implements Bottle {

  String capShape = "Circular";

 String capMaterial = "aluminium";

  @Override

   public void cap() {

   System.out.println("The cap is : " + capShape +  "and " + capMaterial + "with company logo on it");

}

 String bottleShape = "Cylindrical";

 int height = 12;

 int diameter = 10;

int volumeBottle;

  

  public int shape(){

   System.out.println("The bottleShape is : " + bottleShape);

  areaBottle = 3.14 * height * (diameter/2)*(diameter/2);

  return areaBottle;

}


 String bottleColor = "red";  

public String color(){

  return bottleColor;

}

}

Now, if we want to create different product bottles like juice bottle, sauce, ketchup, solutions, spray, chemical formula, baby product and so on, we have to call interface Bottle and implement its methods with logic in it.

Thursday 15 September 2022

                             JPA (Java Persistence API)

This method is use to map any Database table with Java class. 


Take example, we have a table named user_profile in schema: user

We run an SQL query to create a table:  

 CREATE TABLE [user_profile](
    [user_ID] [bigint] IDENTITY(1,1),
    [user_code] [varchar](50) NOT NULL,
    [user_name] [varchar](50),
    [Address] [varchar](25),
    [City] [varchar](50),
    [AppointmentDate] [datetime],

  ) ON [PRIMARY]



Now, we create a Java class which will be mapped to the table as well as fields present in it. The purpose of this is that we can either use the Java Class to fetch data or insert data into table.


UserEntity.java

@Entity
@Table(name = "user_profile")
public class UserEntity implements Serializable {

@Id
@Column(name = "user_id")
private int userId;

@JsonInclude(Include.NON_EMPTY)
@Column(name = "user_code")
private int userCode;

@JsonInclude(Include.NON_EMPTY)
@Column(name = "user_name")
private String userName;

@Column(name = "Address")
private String address;

@Column(name = "City")
private String city;

@Columns(name = "Appointment")
private Date appointment;



}