Skip to main content

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(Point p);
 
 public Point getPosition();
  
}
Implementation (Triangle.java):
package com.shimon.servant.objects;

import java.awt.Point;

import com.shimon.servant.IMovable;

public class Triangle implements IMovable {

 private int sideA;
 private int sideB;
 private int sideC;
 
 
 Point position = null;
 
 public Triangle(int sideA,int sideB,int sideC,Point p){
  this.sideA = sideA;
  this.sideB = sideB;
  this.sideC = sideC;
  this.position = p;
 }
 
 @Override
 public void setPosition(Point p) {
  this.position = p;
 }

 @Override
 public Point getPosition() {
  return this.position;
 }

 public int getSideA() {
  return sideA;
 }

 public void setSideA(int sideA) {
  this.sideA = sideA;
 }

 public int getSideB() {
  return sideB;
 }

 public void setSideB(int sideB) {
  this.sideB = sideB;
 }

 public int getSideC() {
  return sideC;
 }

 public void setSideC(int sideC) {
  this.sideC = sideC;
 }

}
Servant class (Mover.java)
package com.shimon.servant;

import java.awt.Point;

/**
 * Mover servant - moves the provided IMovable objects to specified position or increases their x an y axis position 
 * using the provided arguments.
 * @author shimon
 *
 */
public class Mover {
 
 /**
  * Private constructor
  */
 private Mover(){};
 
 /**
  * Move movable object to specified position.
  * @param moved - moved object
  * @param position - final position
  */
 public static void moveTo(IMovable moved, Point position){
  Point previousPosition = moved.getPosition();
  System.out.printf("Moving smoothly from position x=%d,y=%d to position x=%d,y=%d \n",
    previousPosition.x,
    previousPosition.y,
    position.x,
    position.y);
  moved.setPosition(position);
 }
 
 /**
  * Move movable object by specified distances.
  * @param moved - object to be moved
  * @param x - difference in x-axis
  * @param y - difference in y-axis
  */
 public static void moveBy(IMovable moved, int x, int y){
  Point previousPosition = moved.getPosition();
  System.out.printf("Moving smoothly from position x=%d,y=%d to position x=%d,y=%d \n",
    previousPosition.x,
    previousPosition.y,
    previousPosition.x + x,
    previousPosition.y + y);
  moved.setPosition(new Point(previousPosition.x + x, previousPosition.y + y));
 }
}
The servant method call is showed in the JUnit test method.
package com.shimon.servant;

import static org.junit.Assert.*;

import java.awt.Point;

import org.junit.Test;

import com.shimon.servant.objects.Rectangle;
import com.shimon.servant.objects.Square;
import com.shimon.servant.objects.Triangle;

public class MoverTest {

 @Test
 public void test() {
  Triangle triangle = new Triangle(1, 3, 2, new Point(-1,0));
  Square square = new Square(2, 4, new Point(2,5));
  Rectangle rec = new Rectangle(4, 3, new Point(-3,6));
  Mover.moveTo(rec, new Point(3,2));
  //assert equals on new position of rectangle object
  assertEquals(new Point(3,2), rec.getPosition());
  Mover.moveBy(square, 2, 4);
  assertEquals(new Point(4,9), square.getPosition());
  Mover.moveTo(triangle, new Point(-4,0));
  assertEquals(new Point(-4,0), triangle.getPosition());
 }

}
Console output:
Moving smoothly from position x=-3,y=6 to position x=3,y=2 
Moving smoothly from position x=2,y=5 to position x=4,y=9 
Moving smoothly from position x=-1,y=0 to position x=-4,y=0 

Comments

Popular posts from this blog

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…

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 f…