JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven







Strategy Pattern
  • Algorithms can be selected on the fly.
  • In computer programming, the strategy pattern (also known as the policy pattern)
    is a particular software design pattern, whereby algorithms can be selected at runtime.
  • The strategy pattern is useful for situations where it is necessary to dynamically
    swap the algorithms used in an application.
  • The strategy pattern is intended to provide a means to define a family
    of algorithms, encapsulate each one as an object, and make them interchangeable.
  • The strategy pattern lets the algorithms vary independently from clients that use them.
Purpose
  • Define a family of algorithms, encapsulate each one, and make them interchangeable.
  • Strategy lets the algorithm vary independently from clients that use it.


Applications
  • Many related classes differ only in their behavior. Strategies provide
    a way to configure a class with one of many behaviors.
  • You need different variants of an algorithm.
    For example, you might define algorithms reflecting different space/time trade-offs.
  • Strategies can be used when these variants are implemented as a class hierarchy of algorithms.
  • An algorithm uses data that clients shouldn't know about. Use the Strategy pattern to avoid
    exposing complex, algorithm-specific data structures.
  • A class defines many behaviors, and these appear as multiple conditional statements in its
    operations. Instead of many conditionals, move related conditional branches into their own
    Strategy class.
Move with the Strategy Pattern
  • The Strategy design pattern says that you should extract the volatile parts of your code and encapsulate them as objects; you can use those objects as you need them.
  • Now you can customize your code by creating composites of objects.
  • At runtime, you just use polymorphism to choose the object(s) you want to work with.

Example:-1

CalculatorService.java
package com.service;

import com.model.InterestCalculator;

public class CalculatorService {
  private InterestCalculator ic;
  public CalculatorService(InterestCalculator ic){
    this.ic=ic;
  }
  public double service(double amt){
    return ic.calculate(amt);
  }
}

InterestCalculator.java
package com.model;

public interface InterestCalculator {
  public double calculate(double amt);
}

FDAccountCalculator.java
package com.model;

public class FDAccountCalculator implements InterestCalculator {
  private double roi=8.0;
  private int duration=3;
  @Override
  public double calculate(double amt) {
    return roi/100.0*amt*duration;
  }

}

SavingAccountInterestCalculator.java
package com.model;

public class SavingAccountInterestCalculator
implements 
InterestCalculator {

  private double roi=3.5;
  @Override
  public double calculate(double amt) {
    // TODO Auto-generated method stub
    return (roi/100.0)*amt/12.0;
  }

}

Test.java
package com.test;

import com.model.FDAccountCalculator;
import com.model.SavingAccountInterestCalculator;
import com.service.CalculatorService;

public class Test {
  public static void main(String arg[]){
    CalculatorService servicer=new
CalculatorService(new SavingAccountInterestCalculator());
    System.out.println("Interest for
 Savings Account for the amount 10000 [Current Month]: " 
+
        ""+servicer.service(10000));
    
  }
}

Output:-


Download zip code

Example:- 2

BubbleSort.java
public class BubbleSort implements SortInterface {
    public void sort(int[] list) {
        int temp; 
        for(int i = 0;i < list.length; i++) {
            for(int j = 0; j < list.length - 1; j++) { 
                if(list[i< list[j]) {  
                    temp = list[i];      
                    list[i= list[j];       
                    list[j= temp;     
                }   
            }
        }
        
    }

QuickSort.java
public class QuickSort implements SortInterface {

    public void sort(int[] a) {
        quicksort(a, 0, a.length - 1);
    }
    private void quicksort(int[] a, int left, int right) {
        if (right <= leftreturn;
        int i = partition(a, left, right);
        quicksort(a, left, i-1);
        quicksort(a, i+1, right);
    }
    private int partition(int[] a, int left, int right) {
        int i = left; int j = right;
        while (true) {
            while (a[i]<a[right])
                i++;
            while (less(a[right], a[--j]))
                if (j == left)
                    break;
            if (i >= j)
                break;
            exch(a, i, j);
        }
        exch(a, i, right);

        return i;
    }
    private boolean less(int x, int y)
    {
        return (x < y);
    }
    private void exch(int[] a, int i, int j){
        int swap = a[i];
        a[i= a[j]; a[j= swap;
    }
}

SortingContext.java
public class SortingContext {
    private SortInterface sorter = null;
    public void sortInt(int[] list) {
                sorter.sort(list);
            
            }
    public SortInterface getSorter() { 
        return sorter;
    }
    public void setSorter(SortInterface sorter) { 
        this.sorter = sorter;
    }
}

SortInterface
public interface SortInterface {
  public void sort(int[] list);
  }


SortingClient.java
 public class SortingClient 
        public static void main(String[] args) {  
            int[] list = {1,2,7,3,1,0,10,14,12,16,17,21,19};
            SortingContext context = new SortingContext();
            context.setSorter(new QuickSort());
            context.sortInt(list)
            for(int i =0; i< list.length; i++) {
                System.out.println(list[i]);
            }
        }
    }

Output:-


Download Zip code

Example:-3

Singleton.java



public class Singleton {

  
  private static Singleton instance;
  private Singleton() {
  }
  public static Singleton getInstance() {
    if (instance == null) {
      instance = new Singleton();
    }
    return instance;
  }
}

DvdNameContext.java
package Context;
import Strategy.DvdNameAllCapStrategy;
import Strategy.DvdNameReplaceSpacesStrategy;
import Strategy.DvdNameStrategy;
import Strategy.DvdNameTheAtEndStrategy;

public class DvdNameContext {
   private DvdNameStrategy dvdNameStrategy; 
   
   public DvdNameContext(char strategyTypeIn) {
       switch (strategyTypeIn) {
           case 'C' 
             this.dvdNameStrategy = new DvdNameAllCapStrategy()
             break;
           case 'E' 
             this.dvdNameStrategy = new DvdNameTheAtEndStrategy()
             break;
           case 'S' 
             this.dvdNameStrategy = 
               new DvdNameReplaceSpacesStrategy();
             break;
           default  
             this.dvdNameStrategy = new DvdNameTheAtEndStrategy();
       }     
   }  
   
   public String[] formatDvdNames(String[] namesIn) {
       return this.formatDvdNames(namesIn, ' ');
   }    
   
   public String[] formatDvdNames(String[] namesIn, char replacementIn) {
       String[] namesOut = new String[namesIn.length];
       for (int i = 0; i < namesIn.length; i++) {
           namesOut[i
             dvdNameStrategy.formatDvdName(namesIn[i], replacementIn);
           System.out.println(
             "Dvd name before formatting: " + namesIn[i]);
           System.out.println(
             "Dvd name after formatting:  " + namesOut[i]);
           System.out.println("==========================");
       }
       return namesOut;
   }
}

DvdNameAllCapStrategy.java
package Strategy;

public class DvdNameAllCapStrategy extends DvdNameStrategy {
   public String formatDvdName(String dvdName, char charIn) {
       return dvdName.toUpperCase();
   }
}

DvdNameReplaceSpacesStrategy.java
package Strategy;

public class DvdNameReplaceSpacesStrategy extends DvdNameStrategy {
   public String formatDvdName(String dvdName, char charIn) {
       return dvdName.replace(' ', charIn);
   }
}

DvdNameStrategy.java
package Strategy;
public abstract class DvdNameStrategy {   
   public abstract String 
     formatDvdName(String dvdName, char charIn);
}

DvdNameTheAtEndStrategy.java
package Strategy;

public class DvdNameTheAtEndStrategy extends DvdNameStrategy {
   public String formatDvdName(String dvdName, char charIn) {
       if (dvdName.startsWith("The ")) {
           return new String(dvdName.substring(4
             (dvdName.length())) ", The");
       }
       if (dvdName.startsWith("THE ")) {
           return new String(dvdName.substring(4
             (dvdName.length())) ", THE");
       }       
       if (dvdName.startsWith("the ")) {
           return new String(dvdName.substring(4
             (dvdName.length())) ", the");
       }         
       return dvdName;
   }
}

TestDvdStrategy
package Test;
import Context.DvdNameContext;

class TestDvdStrategy {            
    
   public static void main(String[] args) {
       DvdNameContext allCapContext = 
           new DvdNameContext('C');
       DvdNameContext theEndContext = 
           new DvdNameContext('E');
       DvdNameContext spacesContext = 
           new DvdNameContext('S');
       
       String dvdNames[] new String[3];
       dvdNames[0"Jay and Silent Bob Strike Back";
       dvdNames[1"The Fast and the Furious";
       dvdNames[2"The Others";
       
       char replaceChar = '*';       
       
       System.out.println("Testing formatting with all caps");
       String[] dvdCapNames =allCapContext.formatDvdNames(dvdNames);
       
       System.out.println(" ");         
       System.out.println(
           "Testing formatting with beginning the at end");
       
  String[] dvdEndNames =theEndContext.formatDvdNames(dvdNames);     
       
       System.out.println(" ");       
       System.out.println("Testing formatting
 with all spaces replaced with " 

           replaceChar);
       String[] dvdSpcNames =spacesContext.
formatDvdNames
(dvdNames, replaceChar);
   }
}      

Output:-


Download Zip code