Creating a re-organizable list of Items using Drag and Drop in Oracle ADF

Sometimes the requirement is to create a list of UI Items which can be rearranged using Drag and Drop in Oracle ADF, similar to the one in jQuery.

Oracle ADF Drag and Drop doesn’t provide the ability to identify, where the drag object is being dropped in the drag target. Thus we cannot know where to place the dropped element in the list.

here is the solution to the same:
Assumption:
–each element is same and is being iterated in a for loop over a list.
–Here dummy data is being used
Here is the below jsff segment:

<af:forEach var="v" varStatus="vi" begin="0" end="10">
    <af:panelGroupLayout id="pgl1">
      <af:dropTarget dropListener="#{managedBean.itemInsertAbove}"
                     actions="MOVE">
        <af:dataFlavor flavorClass="javax.faces.component.UIComponent"/>
      </af:dropTarget>
    </af:panelGroupLayout>
    <h:panelGroup styleClass="" id="pg1232">
              <af:outputText value="#{vi.index}" id="ot1"><af:componentDragSource/></af:outputText>
    </h:panelGroup>
    <af:panelGroupLayout id="pgl1">
      <af:dropTarget dropListener="#{managedBean.itemInsertBelow}"
                     actions="MOVE">
        <af:dataFlavor flavorClass="javax.faces.component.UIComponent"/>
      </af:dropTarget>
    </af:panelGroupLayout>
</af:forEach>

below is the Java Code for the managed bean:

needed imports:

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import oracle.adf.view.rich.component.rich.layout.RichPanelGroupLayout;
import oracle.adf.view.rich.context.AdfFacesContext;
import oracle.adf.view.rich.datatransfer.DataFlavor;
import oracle.adf.view.rich.datatransfer.Transferable;
import oracle.adf.view.rich.dnd.DnDAction;
import oracle.adf.view.rich.event.DropEvent;

import org.apache.myfaces.trinidad.change.ChangeManager;
import org.apache.myfaces.trinidad.change.MoveChildComponentChange;
import org.apache.myfaces.trinidad.context.RequestContext;

    /**
     * @param dropEvent
     * @return
     */
    public DnDAction itemInsertBelow(DropEvent dropEvent) {
        Transferable transferable = dropEvent.getTransferable();
        UIComponent dragComponent = null;
        dragComponent = transferable.getData(DataFlavor.UICOMPONENT_FLAVOR);
        UIComponent dropTarget = dropEvent.getDropComponent();
        UIComponent grp = dropTarget.getParent().getParent();
        UIComponent compToMove = dragComponent.getParent();
        grp.getChildren().remove(compToMove);
        int targetIndex = grp.getChildren().indexOf(dropTarget.getParent());
        grp.getChildren().add(targetIndex + 1, compToMove);
        ADFUtils.refreshComponent(grp);
        return DnDAction.NONE;
    }

    /**
     * @param dropEvent
     * @return
     */
    public DnDAction itemInsertAbove(DropEvent dropEvent) {
        Transferable transferable = dropEvent.getTransferable();
        UIComponent dragComponent = null;
        dragComponent = transferable.getData(DataFlavor.UICOMPONENT_FLAVOR);
        UIComponent dropTarget = dropEvent.getDropComponent();
        //        System.out.println(dropTarget.getParent());
        UIComponent grp = dropTarget.getParent().getParent();
        UIComponent compToMove = dragComponent.getParent();
        grp.getChildren().remove(compToMove);
        int targetIndex = grp.getChildren().indexOf(dropTarget.getParent());
        grp.getChildren().add(targetIndex, compToMove);
        ADFUtils.refreshComponent(grp);
        return DnDAction.NONE;
    }

this code allows you place rearrange the list of items using drag and drop:

I1
I2
I3
I4
I5
I6
I7
I8

can be converted to by picking up I3 and placing it between I5 and I6 :

I1
I2
I4
I5
I3
I6
I7
I8

Parse String as Date in Java

Date and Time patterns used in java.text.SimpleDateFormat

Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text Tuesday; Tue
u Day number of week (1 = Monday, …, 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
If ‘M’ is 3 or more, then the month is interpreted as text, else number.

Examples:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
    String dateInString = "7-Jun-2013";

    try {
 
    Date date = formatter.parse(dateInString);
    System.out.println(date);//Fri Jun 07 00:00:00 MYT 2013
        System.out.println(formatter.format(date));   
       } catch (ParseException e) {
              e.printStackTrace(); 
       }
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMM dd, yyyy HH:mm:ss a");
    String dateInString = "Friday, Jun 7, 2013 12:10:56 PM";        
 
    try {
 
        Date date = formatter.parse(dateInString);
        System.out.println(date);
        System.out.println(formatter.format(date));
 
    } catch (ParseException e) {
        e.printStackTrace();
    }
Fri Jun 07 12:10:56 MYT 2013
Friday, Jun 07, 2013 12:10:56 PM

Two player game program – e.g. TIC TAC TOE…

This is an abstract State class
public abstract class State {

// This method is abstract, the extending class has to give the implementation
// It will return a list of all the possible children from the current state.
public abstract List getChildren();
public abstract String getTurn();
public abstract void setTurn(String turn);

// Find out who is the winner from the current state.
public abstract String getWinner();

// Check if the game has been finished or not.
public abstract boolean isGameOver();

// I have given the implementation specifically for TIC-TAC-TOE.
// You can override this functionality in the extending class according to your game requirements.
//
// This function will give the score of the current state.
// Then you can compare it with its siblings to check which state will be better to move to..
//
public int minimax()
{

if(!getWinner().equals(""))
{
if("X".equalsIgnoreCase(getWinner()))
{
return 1;
}
if("O".equalsIgnoreCase(getWinner()))
{
return -1;
}
if("draw".equalsIgnoreCase(getWinner()))
{
return 0;
}
}
List children = getChildren();
if(getTurn().equals("X"))
{
int maxScore = -100;
for(State child : children)
{
int childScore = child.minimax();
if(childScore > maxScore)
{
maxScore = childScore;
}
}
return maxScore;
}
else
{
int minScore = 100;
for(State child : children)
{
int childScore = child.minimax();
if(childScore < minScore)
{
minScore = childScore;
}
}
return minScore;
}

}
}

Extend the above State class and give some implementations…as follows:
Lets assume the class to be TttState…
We’ll override the abstract methods of the parent class State..

Give a member variable that’ll hold the current state of your game…In my case, I have taken it as array..

// This variable is going to hold the current state of your game.
// It can be any depending on your game requirements...
private String state[][] = null ;

Give a copy constructor

public TttState(State x)
{
TttState tState = (TttState)x;
state = new String[3][3];
for(int i=0;i<=2; i++)
{
for(int j=0; j<=2;j++)
{
this.state[i][j]=tState.state[i][j];
}
}
this.turn = x.getTurn();
}

Give a default constructor

public TttState() {
state = new String[3][3];
for(int i=0;i<=2; i++)
{
for(int j=0; j<=2;j++)
{
this.state[i][j]="";
}
}
this.turn = "X";
}

Give a toString implementation, so that you can print the current state

public String toString()
{
StringBuilder sb = new StringBuilder("");
for(int i=0;i<=2; i++)
{
for(int j=0; j<=2;j++)
{
if(state[i][j].equals(""))
{
sb.append("-");
}
else
{
sb.append(state[i][j]);
}
sb.append("t");
}
sb.append("n");
}
return sb.toString();
}

Override the method getWinner() as follows

public String getWinner()
{
// ROW CHECK BEGINS
if(state[0][0].equalsIgnoreCase("X") && state[0][1].equalsIgnoreCase("X") && state[0][2].equalsIgnoreCase("X"))
{
return "X";
}
if(state[0][0].equalsIgnoreCase("O") && state[0][1].equalsIgnoreCase("O") && state[0][2].equalsIgnoreCase("O"))
{
return "O";
}
if(state[1][0].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[1][2].equalsIgnoreCase("X"))
{
return "X";
}
if(state[1][0].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[1][2].equalsIgnoreCase("O"))
{
return "O";
}
if(state[2][0].equalsIgnoreCase("X") && state[2][1].equalsIgnoreCase("X") && state[2][2].equalsIgnoreCase("X"))
{
return "X";
}
if(state[2][0].equalsIgnoreCase("O") && state[2][1].equalsIgnoreCase("O") && state[2][2].equalsIgnoreCase("O"))
{
return "O";
}

// COLUMN CHECK BEGINS
if(state[0][0].equalsIgnoreCase("X") && state[1][0].equalsIgnoreCase("X") && state[2][0].equalsIgnoreCase("X"))
{
return "X";
}
if(state[0][0].equalsIgnoreCase("O") && state[1][0].equalsIgnoreCase("O") && state[2][0].equalsIgnoreCase("O"))
{
return "O";
}
if(state[0][1].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[2][1].equalsIgnoreCase("X"))
{
return "X";
}
if(state[0][1].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[2][1].equalsIgnoreCase("O"))
{
return "O";
}
if(state[0][2].equalsIgnoreCase("X") && state[1][2].equalsIgnoreCase("X") && state[2][2].equalsIgnoreCase("X"))
{
return "X";
}
if(state[0][2].equalsIgnoreCase("O") && state[1][2].equalsIgnoreCase("O") && state[2][2].equalsIgnoreCase("O"))
{
return "O";
}
// DIAGNONAL CHECKS
if(state[0][0].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[2][2].equalsIgnoreCase("X"))
{
return "X";
}
if(state[0][0].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[2][2].equalsIgnoreCase("O"))
{
return "O";
}

if(state[0][2].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[2][0].equalsIgnoreCase("X"))
{
return "X";
}
if(state[0][2].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[2][0].equalsIgnoreCase("O"))
{
return "O";
}
int nonBlank = 0;
for(int i=0;i<=2;i++)
{
for(int j=0;j<=2;j++)
{
if(!state[i][j].equals(""))
{
nonBlank++;
}
}
}
if(nonBlank==9)
{
return "draw";
}

return "";
}

Override the method isGameOver()

public boolean isGameOver()
{
if(!getWinner().equals("") && !getWinner().equals("draw"))
{
return true;
}
else
{
return false;
}
}

Override the method getChildren()

@Override
public List getChildren() {
List children = new ArrayList();
if(turn.equals("X"))
{
for(int i=0;i<=2; i++)
{
for(int j=0; j<=2;j++)
{
if(state[i][j].equals(""))
{
TttState child = new TttState(this);
child.state[i][j]="X";
String newTurn = "O";
child.setTurn(newTurn);
children.add(child);
}
}
}
}
else
{
for(int i=0;i<=2; i++)
{
for(int j=0; j<=2;j++)
{
if(state[i][j].equals(""))
{
TttState child = new TttState(this);
child.state[i][j]="O";
String newTurn = "X";
child.setTurn(newTurn);
children.add(child);
}
}
}
}
return children;
}

Override getTurn and setTurn

public String getTurn() {
return turn;
}

public void setTurn(String turn) {
this.turn = turn;
}

Your main program will look something like this:

public static void main(String args[])
{
TttState x = new TttState();
System.out.println("WINNER : " + x.getWinner());
x.setTurn("X");
Scanner sc = new Scanner(System.in);
while(!x.isGameOver())
{
String xIndex = sc.nextLine();
String yIndex = sc.nextLine();
int xint = Integer.parseInt(xIndex);
int yint = Integer.parseInt(yIndex);
x.getState()[xint][yint]="X";
x.setTurn("O");
int minScore = 100;
List children = x.getChildren();
TttState bestMove = new TttState(x);
for(State child : children)
{
int childScore = child.minimax();
// We are using < because we are always evaluating
// the best move from the options that O player has....
if(childScore < minScore)
{
minScore = childScore;
bestMove = (TttState)child;
bestMove.setTurn("X");
}
}
System.out.print(bestMove);
x = bestMove;
}
System.out.println("GAME OVER...");

}

Programmatically Populate View Objects Based on ArrayList of custom Bean Class In Oracle ADF

Lets say you have a Custom Bean Class EmpData defined as:

EmpData

And you wish to use the same as a View Object, Then below is the method for the same:

First create a Proxy View Object Class:
ProxyDataSourceObject

Now Create a View Object where it is populated programmatically:
Programmatic_VO

Programmatic_VO_attribs

Programmatic_VO_Java

EmpDataCustomVO

Now Edit the View Object Impl Class:

EmpDataCustomVOImpl

Now you can easily use the View Objects as a normal View Object to be used in View Controller.

Cons: The getDataFromService method will be called again and again whenever the View Object is needed. So try to keep the source separate and apply some tuning logic to the same in order to improve performance of system.

Original Referrence Source

ADFUtils Class: Best for Accessing Components in from the Managed Bean

import java.util.Iterator;
import java.util.Map;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.el.ValueExpression;

import javax.faces.application.ViewHandler;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;

import oracle.adf.model.BindingContext;
import oracle.adf.model.DataControlFrame;
import oracle.adf.view.rich.context.AdfFacesContext;

import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;


public class ADFUtils {
    private ADFUtils() {
    }

    /**
     * This method returns any UI component whose id is passed.
     * @param id the id of the component
     * @return the UIComponent
     */
    public static UIComponent getUIComponent(String id) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        if (facesContext != null) {
            UIViewRoot viewRoot = facesContext.getViewRoot();
            if (viewRoot != null) {
                return viewRoot.findComponent(id);
            }
        }
        return null;
    }


    /**
     * Refreshes the page/viewRoot.
     * @return the viewId of the current page
     */
    public static String refreshViewRoot() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        String viewId = facesContext.getViewRoot().getViewId();
        ViewHandler viewHandler =
            facesContext.getApplication().getViewHandler();
        UIViewRoot viewroot = viewHandler.createView(facesContext, viewId);
        viewroot.setViewId(viewId);
        facesContext.setViewRoot(viewroot);
        return viewId;
    }

    /**
     * Invokes the specified function with the specified params.
     * @param functionName the name of the js function
     * @param params the params to be passed
     */
    public static void runJsFunction(String functionName, String params) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExtendedRenderKitService extRenderKitSvc =
            Service.getRenderKitService(facesContext,
                                        ExtendedRenderKitService.class);
        extRenderKitSvc.addScript(facesContext,
                                  functionName + "('" + params + "');");
    }

    /**
     * Invokes the specified function with the specified params.
     * @param functionName the name of the js function
     */
    public static void runJsFunction(String functionName) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExtendedRenderKitService extRenderKitSvc =
            Service.getRenderKitService(facesContext,
                                        ExtendedRenderKitService.class);
        extRenderKitSvc.addScript(facesContext, functionName + "();");
    }

    // Get the Component based on given UIComponent ID and refresh the component

    public static void refreshComponent(String pComponentID) {
        UIComponent component = findComponentInRoot(pComponentID);
        refreshComponent(component);
    }


    // Get Faces Context, Get Root Component, Find the given Component From the root component

    public static UIComponent findComponentInRoot(String pComponentID) {
        UIComponent component = null;
        FacesContext facesContext = FacesContext.getCurrentInstance();
        if (facesContext != null) {
            UIComponent root = facesContext.getViewRoot();
            component = findComponent(root, pComponentID);
        }
        return component;
    }


    // Refresh the Component

    public static void refreshComponent(UIComponent component) {
        if (component != null) {
            AdfFacesContext.getCurrentInstance().addPartialTarget(component);
        }
    }

    // Get the specific  component from a root component tree.

    public static UIComponent findComponent(UIComponent root, String id) {
        if (id.equals(root.getId()))
            return root;

        UIComponent children = null;
        UIComponent result = null;
        Iterator childrens = root.getFacetsAndChildren();
        while (childrens.hasNext() && (result == null)) {
            children = (UIComponent)childrens.next();
            if (id.equals(children.getId())) {
                result = children;
                break;
            }
            result = findComponent(children, id);
            if (result != null) {
                break;
            }
        }
        return result;
    }
  
    /**
     * Programmatic evaluation of EL.
     *
     * @param el EL to evaluate
     * @return Result of the evaluation
     */
    public static Object evaluateEL(String el) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ELContext elContext = facesContext.getELContext();
        ExpressionFactory expressionFactory =
            facesContext.getApplication().getExpressionFactory();
        ValueExpression exp =
            expressionFactory.createValueExpression(elContext, el,
                                                    Object.class);

        return exp.getValue(elContext);
    }

    /**
     * Programmatic invocation of a method that an EL evaluates to.
     * The method must not take any parameters.
     *
     * @param el EL of the method to invoke
     * @return Object that the method returns
     */
    public static Object invokeEL(String el) {
        return invokeEL(el, new Class[0], new Object[0]);
    }

    /**
     * Programmatic invocation of a method that an EL evaluates to.
     *
     * @param el EL of the method to invoke
     * @param paramTypes Array of Class defining the types of the parameters
     * @param params Array of Object defining the values of the parametrs
     * @return Object that the method returns
     */
    public static Object invokeEL(String el, Class[] paramTypes,
                                  Object[] params) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ELContext elContext = facesContext.getELContext();
        ExpressionFactory expressionFactory =
            facesContext.getApplication().getExpressionFactory();
        MethodExpression exp =
            expressionFactory.createMethodExpression(elContext, el,
                                                     Object.class, paramTypes);

        return exp.invoke(elContext, params);
    }

    /**
     * Sets a value into an EL object. Provides similar functionality to
     * the  tag, except the from is
     * not an EL. You can get similar behavior by using the following...

     * setEL(to, evaluateEL(from))
     *
     * @param el EL object to assign a value
     * @param val Value to assign
     */
    public static void setEL(String el, Object val) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ELContext elContext = facesContext.getELContext();
        ExpressionFactory expressionFactory =
            facesContext.getApplication().getExpressionFactory();
        ValueExpression exp =
            expressionFactory.createValueExpression(elContext, el,
                                                    Object.class);

        exp.setValue(elContext, val);
    }
}

Source: Forum

Alternate Link:Alternate, includes Application Module and Binding Utils as well

How to show Popup programmatically in Oracle ADF

When trying to open a Popup on JSF/JSFF page programmatically through Managed Bean, use the following method and pass the ID of the popup to the method:

 public void openPopup(String popupId) {
         ExtendedRenderKitService erkService =
         Service.getService(FacesContext.getCurrentInstance().getRenderKit(),
         ExtendedRenderKitService.class);
         erkService.addScript(FacesContext.getCurrentInstance(),
         "var hints = {autodismissNever:true}; " +
         "AdfPage.PAGE.findComponent('" + popupId +
         "').show(hints);");
 }
OR

On the button , write a method on the action event.
 public void ShowPopup(ActionEvent actionEvent) {
          RichPopup.PopupHints hints = new RichPopup.PopupHints();
          this.getPopUp().show(hints);
 
 }

If you want to hide the popup..you can write like this

  public void HidePopup(ActionEvent actionEvent) {
           RichPopup.PopupHints hints = new RichPopup.PopupHints();
           this.getPopUp().hide();
 
  }

General use is when you wish to call the a popup from a button press but first want to execute some actions/processings in the screen on the button click.

In the button on the JSFF, just add a actionListener and then call the openPopup() method from the action listener or any other method you wish to.

Source: Forum

Week of Day String to INT

To change a Day of the week like Monday, Tuesday and so on to integer the use the following code:

  public int dayNameComparison(String dayName) {
           java.text.DateFormatSymbols objDaySymbol = new java.text.DateFormatSymbols();
           String symbolDayNames[] = objDaySymbol.getWeekdays();
           for (int countDayname = 0; countDayname < symbolDayNames.length;countDayname++) {
                if (dayName.equalsIgnoreCase(symbolDayNames[countDayname])) {
                      return countDayname;
                   }
               }
             return 0;
          }

 

This way when u pass the day as parameter the you will get the output as integer. This output can be used directly in Calendar class as input :

 

public static void main(String[] args) {
         TestMouse testMouse = new TestMouse();
         int i = testMouse.dayNameComparison("Tuesday");
         System.out.println("" + i);
         java.util.Calendar calendar = java.util.Calendar.getInstance();
         calendar.set(java.util.Calendar.DAY_OF_WEEK, i);
         System.out.println(new java.text.SimpleDateFormat("EEEE").format(calendar.getTime()));//Prints: Tuesday
}

Generate java classes using xjc

Source : Generate java class from xml schema using jaxb xjc command

Before using JAXB to create or access an XML document from Java application, we have to do the following steps:

1.Binding the schema
* Binding a schema means generating a set of Java classes that represents the schema for the XML document (Schema is not required for simple marshalling and unmarshalling).

2.Marshal the content tree /Unmarshal the XML document.
* After binding the schema, you can convert Java objects to and from XML document.
In this example we will see how to bind the schema. For that, we use Java Architecture for XML Binding (JAXB) binding compiler tool, xjc, to generate Java classes from XML schema.

‘xjc’ Command Line Options

Usage:

xjc [-options …] … [-b ] …
If dir is specified, all schema files in it will be compiled.
If jar is specified, /META-INF/sun-jaxb.episode binding file will be compiled.

Complete list of options for ‘xjc’ is available in the help option.

xjc -help

Generate Java classes using ‘xjc’

Follow the steps below to generate a set of Java source files from XML schema.

  1. Create a new Java project folder and name it as “JAXBXJCTool”.
  2. Create a new XSD file and name it as “employee.xsd” and copy the following lines. This is the XML schema in our example which is to be bound to java classes
  3. Employee.xsd
























  4. Save the file
  5. Create a new folder ‘src’ inside the project folder.
  6. In Windows open Command Prompt (Windows button + R and type cmd) or Terminal in Linux and go to the project folder (use cd command) where it exists in your machine and type the following command
  7. C:UsersiByteCodeDesktopJAXBXJCTool>xjc -d src -p com.theopentutorials.jaxb.beans employee.xsd

  8. This will generate set of Java source files with appropriate annotation inside ‘src’ folder

The selected file is a system file

Error:

 The project was not built due to “Internal error – the selected file is a system file that cannot be modified. It will be hidden.”. Fix the problem, then try refreshing this project and building it since it may be inconsistent

 Resolution:

This a problem encountered when the Clear Case plugin is added to the eclipse and then the project is imported.
Solution:
By deleting the “.copyarea.db” in the bin directory of the concerned project would make it work. What is happening here is, when the project is trying to build, this particular file “.copyarea.db” (which is a read only file) stops it from executing. Once deleted physically going to the particular directory and then refreshing the project it would work.

Link:

http://www.myeclipseide.com/PNphpBB2-printview-t-12987-start-0.html

 Solution given by dewanvaibhavgarg@gmail.com

Real time examples of Design patterns being used by Java

I am very keen to learn what all design patterns are being used by java code.

So here I am going to list them one by one.. I’ll keep on updating this article as and when I learn more about design patterns…

To begin with.. Lets learn something about strategy design pattern.

Strategy Design Pattern Examples

  • There are common situations when classes differ only in their behavior. For this cases is a good idea to isolate the algorithms in separate classes in order to have the ability to select different algorithms at runtime.
    Intent
  • Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

You must have seen how we create threads in Java… We make a class implement Runnable and override its run method. And then use that class’s object as an argument to Thread class constructor.

class xx implements Runnable  
{
@Override
public void run()
{
System.out.println("Running xx thread...");
}
}
class MyThread extends Thread
{
@Override
public void run()
{
System.out.println("mythread");
}
}
public class Main
{
public static void main(String args[])
{
xx r = new xx();
// Encapsulate what varies.. Note that
// Here the behavior of the run method varies...
// That is why it has been moved out of the Thread class..
Thread t = new Thread(r);
// Now that we have overridden the run method of Runnable interface
// and passed the object of class implementing it to the constructor of
// Thread class...
// In this case, the run method of r object will get invoked
// by the start method.
t.start();

Thread s = new MyThread();
// As we have now overriden the method of the Thread
// class itself, the start method will invoke the overridden
// run method.
// Here polymorphysm is attained by inheritance and not by
// encapsulation.. This is a weaker strategy than the first one.
s.start();


}
}

Well, if you see the definition of run() method in Thread class I think you’ll agree to what I have tried to explain above… Here is the definition in Thread class

/**
* If this thread was constructed using a separate
* Runnable run object, then that
* Runnable object's run method is called;
* otherwise, this method does nothing and returns.
*


* Subclasses of Thread should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
public void run()
{
if (target != null)
{
target.run();
}
}

And if you look at the second way of creating a Thread, i.e. extending a Thread class… In that case the start method just invokes the run method… And because we have overridden the run method of Thread class, the default implementation of Thread’s run method will not get invoked, instead the implementation that we have given in the child class will get invoked.

/**
* Causes this thread to begin execution; the Java Virtual Machine
* calls the run method of this thread.
*


* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* start method) and the other thread (which executes its
* run method).
*


* It is never legal to start a thread more than once.
* In particular, a thread may not be restarted once it has completed
* execution.
*
* @exception IllegalThreadStateException if the thread was already
* started.
* @see #run()
* @see #stop()
*/
public synchronized void start()
{
.....
}

Collections.sort(myCollections, myComparator);

This is another example of strategy design pattern, which I can think of.. As we are passing the behavior of comparison at run-time.