Skip to main content

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();
 }
}


Comments

Popular posts from this blog

Servant (Design Pattern) in Java - example

The servant design pattern - or better idiom is used to provide the functionality (methods) to some group of objects. This functionality is common for all these object and therefor should not be repeated in every of these classes.
The object, which should be served is passed to the method of servant as a parameter. All the served objects should implement common interface - in this particular example IMovable interface. Also the type of argument passed to the servand method is of type IMovable.
The servant in this example is used to move objects from one position to another. In real life application these methods should change the position of object in small steps so that the final change would look like smooth movement (animation). In my servant method, only some message are printed instead for demonstration.
IMovable interface:
package com.shimon.servant; import java.awt.Point; /** * Movable interface * @author shimon * */ public interface IMovable { public void setPosition(P…

Livigno 2017

Po niekoľkých rokoch, kedy sme skončili v lete na dovolenke niekde pri Jadrane, sme si minulý rok so Zuzkou povedali, že ďalšia dovolenka musí byť iná. K tomu sa pridal obmedzený počet dní dovolenky, ktoré sme mohli cez leto využiť. Takže sme zvažovali, či vôbec ísť k moru, a aké sú ďalšie možné varianty. Po zavrhnutí niekoľkých iných alternatív sme sa nakoniec rozhodli pre "cyklo" dovolenku v horách, a ako je zrejmé už z nadpisu, v talianskom alpskom mestečku Livigno. Zastávka v Innsbrucku Na dovolenku sme chceli využiť 2 české štátne sviatky v priebehu prvého júlového týždňa, preto sme dovolenku plánovalí od soboty do nedele. Až týždeň pred odjazdom sme si uvedomili, že by sme takto zabili celú sobotu cestovaním a tak sme si povedali, že vyrazíme už v piatok po práci a zastavíme sa v niektorom z rakúskych miest po ceste. Do úvahy pripadali asi len Salzburg a Innsbruck. Keďže Innsbruch je k Švajčiarsku (cez ktoré vedie najkratšia cesta do Livigna) najbližšie, zabookovali sm…

Optimise your PDF for e-book reader

Some of you e-book enthusiasts maybe also ran into a problem when trying to read some PDF that was not optimised for reading on e-book reader (e.g. Kindle). The margins are too wide, pictures are too small, etc.

Luckily there is one very useful (command line) tool that helps you prepare your PDF document for reading on your e-book. It's name is k2pdfopt (not very lucky name I think). This utility scans the content of the provided PDF document, reorganises the columns (if there are multiple) and improves overall document readability.

Here is a saple of document before and after the optimisation:



To optimise the document use following command:

If you use unix based system (Linux, MacOS) change the downloaded k2pdfopt file to exacutable by running `chmod +x k2pdfopt`Run the k2pdfopt commang with PDF you want to optimise as parameter: `k2pdfopt /path/to/your/file.pdf`Use `d` option to choose desired target deviceYou can check other options - they may be useful for youHit `Enter` to opt…