Pages

Tuesday, November 15, 2011

Java Crate (design pattern/idiom) example

Another example, based on example explained in the book "Navrhove vzory" (Design patterns) from Rudolf Pecionvsky. I have re-made this example just to somehow get more familiar with this design pattern (or better idiom). The "crate" is used to store the set/list of object in one place, so that the moving (passing) these objects is easier.

The example from the book is very easy, and helps to understand, how this design pattern could be applied to som very usefull application (e.g. day planner)

Code example:
 
package com.sim.crate.common;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

/**
 * The Day Plan class demonstrates the usage of crate to create simple day plan, with items that do not collide.
 * @author shimon
 *
 */
public class DayPlan {
 private final List actions = new ArrayList();
 
 /**
  * Tries to add an item to the day plan with entered start, end time and duration. Returns true, if
  * the try was successful, or false if not. The item is added only if no collision with other items in 
  * the day plan appear.
  * @param hour - start hour
  * @param minute - start minute
  * @param duration - duration
  * @param subject - item subject
  * @return - bollean true - if success, else false
  */
 public boolean add(int hour, int minute, int duration, String subject){
  int start = hour * 60 + minute;
  int end = start + duration;
  ListIterator lip = actions.listIterator();
  while(lip.hasNext()){
   Item i = lip.next();
   if (i.end <= start){
    continue;
   }
   if(i.start <= end){
    return false;
   }
  }
  lip.add(new Item(start, end, subject));
  return true;
 }
 
 /**
  * Prints all items available in the dayplan.
  */
 public void print(){
  System.out.println("\nList of actions:");
  for (Item i:actions){
   System.out.printf("%02d:%02d - %02d:%02d %s\n", i.start / 60,i.start % 60,i.end / 60,i.end % 60,i.subject);
  }
  System.out.println("--------------------------------");
 }
 
 /**
  * Inner class used to store the items.
  * @author shimon
  *
  */
 private static class Item{
  int start;
  int end;
  String subject;
  
  Item(int start, int end, String subject){
   this.start = start;
   this.end = end;
   this.subject = subject;
  }
 }
 
 public void testAdd(int h, int m, int d, String txt){
  boolean success;
  System.out.printf("Adding %d minutes from %02d:%02d for %s\n", d, h, m, txt);
  success = add(h, m, d, txt);
  System.out.println("             " + (success?"OK":"FAIL"));
 }
}

Test class:
 
package com.sim.crate.common;


import org.junit.Test;

public class DayPlanTest {

 @Test
 public void test() {
  DayPlan dp = new DayPlan();
  dp.testAdd(8, 0, 30, "Waking up");
  dp.testAdd(10, 30, 90, "Relax");
  dp.testAdd(8, 30, 30, "Breakfast");
  dp.testAdd(9, 30, 90, "Work");
  dp.print();
 }
}


No comments: