Design pattern



Abstract design pattern, factory design pattern and other design patterns



Factory-->
       create a interface 
    create multiple type implementation class of interface
    create a factory class where return type should be your interface or abstract class one method should be present
    Eample:
    class GetPlanFactory{  
   //use getPlan method to get object of type Plan   
       public Plan getPlan(String planType){  
            if(planType == null){  
             return null;  
            }  
          if(planType.equalsIgnoreCase("DOMESTICPLAN")) {  
                 return new DomesticPlan();  
               }   
           else if(planType.equalsIgnoreCase("COMMERCIALPLAN")){  
                return new CommercialPlan();  
            }   
          else if(planType.equalsIgnoreCase("INSTITUTIONALPLAN")) {  
                return new InstitutionalPlan();  
          } 


Abstract Factory:--->
   create two more then one interface.
   create every interface have more implementation class
   create abstract another one factory interface which hold of other two or more interface
   create implementation of abstract factory which like every method have same implementation of factory
   https://www.baeldung.com/java-abstract-factory-pattern
       
Adapter -->While implementing Adapter pattern, there are two approaches – class adapter and object adapter – however both these approaches produce same result.
          Class Adapter – This form uses java inheritance and extends the source interface, in our case Socket class.
   Object Adapter – This form uses Java Composition and adapter contains the source object.
  public class BankCustomer extends BankDetails implements CreditCard{
  }
Builder-->
  1>interface 
  2>have implements of interface
  3>createType Class and inside class have below two method 
  xxxxxType {  
             private List<InterfaceName> items=new ArrayList<InterfaceName>();  
             public void addItem(InterfaceName packs) {    
                    items.add(packs);  
             } 
   showDetails(Item item:Items){
  }
  
  4>create builder class and have different type of builder method of create type 
  like public class CDBuilder {  
                  public xxxxxType buildSonyCD(){   
                     xxxxxType cds=new xxxxxType();  
                     cds.addItem(new Sony());  
                     return cds;  
              }  
              public xxxxxType buildSamsungCD(){  
             xxxxxType cds=new xxxxxType();  
             cds.addItem(new Samsung());  
             return cds;  
              }  
  }
  5>call builder design pattern
  CDBuilder cdBuilder=new CDBuilder();  
  CDType cdType1=cdBuilder.buildSonyCD();  
  cdType1.showItems();  
  CDType cdType2=cdBuilder.buildSamsungCD();  
  cdType2.showItems(); 

Delegate--->
  1>first implement a factory design pattern
  2>create a delegate class where you need to call factory class and interface both.
  Example:
  public class BusinessDelegate {
     private GetPlanFactory lookupService = new GetPlanFactory();
     private Plan businessService;
     private String serviceType;

     public void setServiceType(String serviceType){
     this.serviceType = serviceType;
     }

     public void doTask(){
     businessService = lookupService.getBusinessService(serviceType);
     businessService.doProcessing();  
     }
  }
 
    3>Now call via:
   BusinessDelegate businessService;

     public Client(BusinessDelegate businessService){
     this.businessService  = businessService;
     }

     public void doTask(){  
     businessService.doTask();
     }

Chain --->
  1>create a interface and inside interface have one method which parameter name interface itself.
  2>and have another one or more  method for your operation
  Example:
  interface Chain 
   { 
    void setNext(Chain nextInChain); 
    void process(Number request); 
   }
  3>create multiple implementation class which have composite implementation
  Example:
   class NegativeProcessor implements Chain 
    { 
     private Chain nextInChain; 
      
     public void setNext(Chain c) 
     { 
      nextInChain = c; 
     } 
   or 
   class ZeroProcessor implements Chain 
    { 
       
     private Chain nextInChain; 
      
     public void setNext(Chain c) 
     { 
      nextInChain = c; 
     } 
      4>call like
      Chain c1 = new NegativeProcessor(); 
   Chain c2 = new ZeroProcessor(); 
   Chain c3 = new PositiveProcessor(); 
   c1.setNext(c2); 
   c2.setNext(c3); 
   
   //calling chain of responsibility 
   c1.process(new Number(90)); 
   c1.process(new Number(-50)); 
   c1.process(new Number(0)); 
   c1.process(new Number(91)); 
   
Prototype-->
     1>create an interface of Prototype and inside interface have return type Prototype have any method
  example:
  interface Prototype {  
     public Prototype getClone();  
  --------------
  }
  2>have implementation and overridden of getClone method 
  class EmployeeRecord implements Prototype{  
      private int id;  
      private String name, designation;  
  //setter method getter method and constructor ur choice
  
  @Override  
    public Prototype getClone() {  
        return new EmployeeRecord(id,name,designation,salary,address);  
    } 
  
  }

proxy--->>
    1>create an interface 
 2>and create one is real implementation and one is proxy implementation
 2-1>real implementation like as it is of interface implementation
 2-2>proxy implementation little bit tricky. and inside implementation method you do if it is proxy something else something
 Example:
 public class ProxyInternet implements Internet 
  { 
        private Internet internet = new RealInternet();
  
 3>call
  Internet internet = new ProxyInternet(); 
        try
        { 
            internet.connectTo("geeksforgeeks.org"); 
            internet.connectTo("abc.com"); 
        } 
Singleton --->>>
      class JDBCSingleton  implements serializable{ 
   private static JDBCSingleton jdbc; 
   private JDBCSingleton() {  } 
   public static JDBCSingleton getInstance() {    
                         if (jdbc==null){  
       synchronized(JDBCSingleton.class){  
        if (jdbc == null){  
         jdbc=new  JDBCSingleton();    
          } 
                              }  
                   return jdbc;  
             }
    
 private static Connection getConnection()throws ClassNotFoundException, SQLException  
          {  
                
              Connection con=null;  
              Class.forName("oracle.jdbc.driver.OracleDriver");  
              con= DriverManager.getConnection("jdbc:oracle:thin:@192.168.114.52:1521:indqa15", "kartik", "kartik");  
              return con;  
                
          }  
            
 
          public int insert(String name, String pass) throws SQLException  
          {  
              Connection c=null;  
                
              PreparedStatement ps=null;  
                
              int recordCounter=0;  
                
              try {  
                    
                      c=this.getConnection();  // this is main 
                      ps=c.prepareStatement("insert into userdata(uname,upassword)values(?,?)");  
                      ps.setString(1, name);  
                      ps.setString(2, pass);  
                      recordCounter=ps.executeUpdate();  
                        
              } catch (Exception e) { e.printStackTrace(); } finally{  
                    if (ps!=null){  
                      ps.close();  
                  }if(c!=null){  
                      c.close();  
                  }   
              }  
             return recordCounter;  
          }
@override
private void readResolver(){
return getInstance();}
Call:

JDBCSingleton jdbc= JDBCSingleton.getInstance();  
jdbc.insert(username, password);


  

How to create an abstract factory design pattern


Create a factor of bank

package com.kartik.abstct.factory;

public interface Bank {
  String getBankName();
}




package com.kartik.abstct.factory;

public class BankHDFCImpl implements Bank {
 private final String BNAME;

 public BankHDFCImpl() {
  BNAME = "HDFC BANK";
 }

 @Override
 public String getBankName() {
  return BNAME;
 }

}

package com.kartik.abstct.factory;

public class BankICICIImpl implements Bank{  
    private final String BNAME;  
    BankICICIImpl(){  
             BNAME="ICICI BANK";  
     }  
    @Override
     public String getBankName() {  
               return BNAME;  
    }  
} 


package com.kartik.abstct.factory;

public class BankFactory {
  public Bank getBank(String bank){  
       if(bank == null){  
          return null;  
       }  
       if(bank.equalsIgnoreCase("HDFC")){  
          return new BankHDFCImpl();  
       } else if(bank.equalsIgnoreCase("ICICI")){  
          return new BankICICIImpl();  
       }/* else if(bank.equalsIgnoreCase("SBI")){  
          return new SBI();  
       } */ 
       return null; 
  }
}



Create a factor of loan



package com.kartik.abstct.factory;

public interface Loan {
 double getInterestRate(double r,double loanamount,int years);
}




package com.kartik.abstct.factory;

public class LoanBusiness implements Loan{

 @Override
    public double getInterestRate(double rate,double loanamount,int years){  
     Util util=new Util(rate);  
     return util.calculateLoanPayment(loanamount, years);
   }
}


package com.kartik.abstct.factory;

public class LoanHome implements Loan{
 
 @Override
    public double getInterestRate(double rate,double loanamount,int years){  
     Util util=new Util(rate);  
     return util.calculateLoanPayment(loanamount, years);
   }

  
}


package com.kartik.abstct.factory;

public class LoanFactory {

  public Loan getLoan(String loan){  
       if(loan == null){  
          return null;  
       }  
       if(loan.equalsIgnoreCase("BUSINESS")){  
          return new LoanBusiness();  
       } else if(loan.equalsIgnoreCase("HOME")){  
          return new LoanHome();  
       }/* else if(bank.equalsIgnoreCase("SBI")){  
          return new SBI();  
       } */ 
       return null; 
  }
}


package com.kartik.abstct.factory;

public class Util {

 double rate=0.0;
 public Util(int data) {
  this.rate=data;
 }
 public Util(double data) {
  this.rate=data;
 }
 public double calculateLoanPayment(double loanamount, int years)  
    {  
         /* 
               to calculate the monthly loan payment i.e. EMI   
                             
               rate=annual interest rate/12*100; 
               n=number of monthly installments;            
               1year=12 months. 
               so, n=years*12; 
  
             */  
                 
          double EMI;  
          int n;  
   
          n=years*12;  
          rate=rate/1200;  
          EMI=((rate*Math.pow((1+rate),n))/((Math.pow((1+rate),n))-1))*loanamount;  
   
 System.out.println("your monthly EMI is "+ EMI +" for the amount"+loanamount+" you have borrowed"); 
 return EMI;
  }
}



Create a factor of bank or loan



package com.kartik.abstct.factory;

public interface FactoryOfFactoryInterface<T> {
 T create(String type) ;
}




package com.kartik.abstct.factory;

public class FactoryOfFactoryBankImpl implements
  FactoryOfFactoryInterface<Bank> {

 @Override
 public Bank create(String type) {
  if ("Hdfc".equalsIgnoreCase(type)) {
   return new BankHDFCImpl();
   } else if ("icici".equalsIgnoreCase(type)) {
    return new BankICICIImpl();
     }
  return null;
 }

}

package com.kartik.abstct.factory;

public class FactoryOfFactoryLoanImpl implements
  FactoryOfFactoryInterface<Loan> {

 @Override
 public  Loan create(String type) {
  if ("Business".equalsIgnoreCase(type)) {
   return new LoanBusiness();
   } else if ("Home".equalsIgnoreCase(type)) {
    return new LoanHome();
     }
  return null;
 }

}



package com.kartik.abstct.factory;

public class FactoryCreator {
 @SuppressWarnings("rawtypes")
 public static FactoryOfFactoryInterface getFactory(String choice){  
       if(choice.equalsIgnoreCase("Bank")){  
          return new FactoryOfFactoryBankImpl();  
       } else if(choice.equalsIgnoreCase("Loan")){  
          return new FactoryOfFactoryLoanImpl();  
       }  
       return null;  
    }  
}




package com.kartik.abstct.factory;

public class Client {

 public static void main(String[] args) {
  @SuppressWarnings({ "static-access", "rawtypes" })
  FactoryOfFactoryInterface loanFactory = new FactoryCreator().getFactory("Loan");
  Loan l=(Loan) loanFactory.create("Business"); 
  double d=l.getInterestRate(20, 200000, 12);
  System.out.println(d);
  
  l=(Loan) loanFactory.create("Home"); 
  d=l.getInterestRate(30, 200000, 12);
  System.out.println(d);
  
  @SuppressWarnings({ "rawtypes", "static-access" })
  FactoryOfFactoryInterface bacnkFactory = new FactoryCreator().getFactory("Bank");
  Bank b=(Bank) bacnkFactory.create("HDFC");
  System.out.println(b.getBankName());
  
 }

}
Output:your monthly EMI is 3673.2170901416903 for the amount200000.0 you have borrowed
3673.2170901416903
your monthly EMI is 35340.526716348555 for the amount3900000.0 you have borrowed
35340.526716348555
HDFC BANK








    



Other Links:
Abstract Design pattern
Inheritance Understand Part 2
Inheritance Understand Part 3
Robot move
GENERATING KEYSTORE FILES





Previous
Next Post »