Options available for heating water

The simplest and easiest way is to get a big utensil and fill it up with water and heat it on the stove. Remember to cover it up, and it gets hot faster.

Another option that we used when we were living as tenants was an electric rod. It costs between 200 to 500 INR and depending upon the wattage heats up water fast – a bucket gets heated in say 15 minutes if you are using an element of around 2KW. It is cheap and electric – so wont work if you have power cuts. But it saves the trouble of lighting up your gas and placing an utencil above it. The bigger the bucket the more water you can heat. Be careful, if the element gets sorted, you might get a shock or even trip your main supply.

Third option is getting an electric water geaser. It has its own pros and cons. Electric water geasers cost from around 4000 INR and move up. All of them have a plastic body, a heating element, a tank, a thermostat and some electronic stuff. The difference between a cheap one and an expensive one is basically the quality of these things. A cheap one may have a steel tank, whereas an expensive one may have a copper tank, and some even have tanks lined with glass – to prevent damage to the tank due to hard water. The life of an element is minimum 3 months, after which depending on the quality of water that you get, it will get sorted. Once it gets sorted, you will experience an electric shock whenever you try getting water from a geaser which is switched on. Imagine getting a “shocking” shower. The worst that can happen is when the tank leaks, it will sort the thermostat, maybe the electronics and you will again get a “shocking” shower – but this time the water might be either very cold or very hot. The thermostat costs around 300 INR, the element costs around 500 INR, the tank costs around 1000 INR. Other logistical issues with a storage type of water heater is the pressure. In case you are on the ground floor and the water comes from a tank at the 10th floor, the pressure will be too much for the tank to handle (dont worry, it wont explode, it will simply leak). To avoid it, you will need to get a pressure valve.

Another option in the electrical segment is the “non-storage” type of water heater. It has an element and heats water on the fly. It is cheaper, cause it does not have a tank but it has not been very successful mainly because the water does not get very hot – just warm. And, again if the element gets sorted, be ready to experience a “shocking shower”.

If we move out of the electrical option, there are two other options available, the solar option and the gas option. Lets talk about the gas option.

No this is not the “heat in pan” option. There are geasers available in market which run on gas and heat water. Basically a gas geaser has two inputs (water & gas) and an output (hot water). It does not store water. Water runs through pipes among a burning stove and heats up. The cost of a gas geaser is around 2500 INR with installation – you need to have your own gas supply ofcourse. Again this thing does not have a storage, so water is heated on the fly. Gas geaser is supposed to be a lot cheaper (running cost) as compared to an electric geaser – mainly because gas is cheaper than electricity and the effeciency of gas is better than electricity while heating. Here it says that yearly savings are around 3500/- INR. The bad thing about the gas geaser is that it burns up oxygen wherever it is installed. So if you install it in a bathroom without any ventilation, you might experience dizziness due to low oxygen. This geaser has to be installed near a open window so that it gets all the air it can burn. Installation and usage in a non-ventilated space may cause Carbon Monoxide (CO) poisoning (if there is not enough oxygen to burn CO is produced). So be careful while using it. The benefit as compared to electric water heater is the cheaper running cost and the possibility of not getting an electric shock.

And the last one is the solar water heater. Unless you are not living in an appartment and have your own private sunlight from morning till night, it is not worth exploring. Solar water heaters are a lot expensive but environment friendly and very safe.

Design Patterns : Composite Design Pattern

A composite design pattern builds complex objects out of simple objects and itself like a tree structure. Its goal is managing a hierarchy of objects where both leaf objects and composition of other objects conform to a common interface.

The client sends a message to the head component. The component declares the interface that various parts of the graph should respect. A leaf is a concrete class that has no children. A composite is a concrete class that composes other components.

PHP Code :

/**
 * Component interface.
 * The Client depends only on this abstraction, whatever graph is built using
 * the specializations.
 */
interface HtmlElement
{
  /**
   * @return string   representation
   */
  public function __toString();
}

/**
 * Leaf sample implementation.
 * Represents an <h1> element.
 */
class H1 implements HtmlElement
{
  private $_text;

  public function __construct($text)
  {
    $this->_text = $text;
  }

  public function __toString()
  {
    return "<h1>{$this->_text}</h1>";
  }
}

/**
 * Leaf sample implementation.
 * Represents a <p> element.
 */
class P implements HtmlElement
{
  private $_text;

  public function __construct($text)
  {
    $this->_text = $text;
  }

  public function __toString()
  {
    return "<p>{$this->_text}</p>";
  }
}

/**
 * A Composite implementation, which accepts as children generic Components.
 * These children may be H1, P or even other Divs.
 */
class Div implements HtmlElement
{
  private $_children = array();

  public function addChild(HtmlElement $element)
  {
    $this->_children[] = $element;
  }

  public function __toString()
  {
    $html = "<div>n";
    foreach ($this->_children as $child) {
      $childRepresentation = (string) $child;
      $childRepresentation = str_replace("n", "n    ", $childRepresentation);
      $html .= '    ' . $childRepresentation . "n";
    }
    $html .= "</div>";
    return $html;
  }
}

// Client code
$div = new Div();
$div->addChild(new H1('Title'));
$div->addChild(new P('Lorem ipsum...'));
$sub = new Div();
$sub->addChild(new P('Dolor sit amet...'));
$div->addChild($sub);
echo $div, "n";


Output

<div>
  <h1>Title</h1>
  <p>Lorem ipsum...</p>
  <div>
    <p>Dolor sit amet...</p>
  </div>
</div>

Java Code : 

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

/** "Component" */
interface Graphic {

  //Prints the graphic.
  public void print();
}

/** "Composite" */
class CompositeGraphic implements Graphic {

  //Collection of child graphics.
  private List mChildGraphics = new ArrayList();

  //Prints the graphic.
  public void print() {
    for (Graphic graphic : mChildGraphics) {
      graphic.print();
    }
  }

  //Adds the graphic to the composition.
  public void add(Graphic graphic) {
    mChildGraphics.add(graphic);
  }

  //Removes the graphic from the composition.
  public void remove(Graphic graphic) {
    mChildGraphics.remove(graphic);
  }
}

/** "Leaf" */
class Ellipse implements Graphic {

  String myname = "Ellipse";

  public Ellipse(int i){
    this.myname = myname + ":"+i;
  }

  //Prints the graphic.
  public void print() {
    System.out.println(this.myname);
  }
}

/** Client */
public class Program {

  public static void main(String[] args) {
    //Initialize four ellipses
    Ellipse ellipse1 = new Ellipse();
    Ellipse ellipse2 = new Ellipse();
    Ellipse ellipse3 = new Ellipse();
    Ellipse ellipse4 = new Ellipse();

    //Initialize three composite graphics
    CompositeGraphic graphic = new CompositeGraphic();
    CompositeGraphic graphic1 = new CompositeGraphic();
    CompositeGraphic graphic2 = new CompositeGraphic();

    //Composes the graphics
    graphic1.add(ellipse1);
    graphic1.add(ellipse2);
    graphic1.add(ellipse3);

    graphic2.add(ellipse4);

    graphic.add(graphic1);
    graphic.add(graphic2);

    //Prints the complete graphic (four times the string "Ellipse").
    graphic.print();
  }
}

OUTPUT:

Ellipse:1
Ellipse:2
Ellipse:3
Ellipse:4

Design patterns : Bridge Design Pattern

Bridge pattern decouples the abstraction from its implementation so that both can vary independently. It is quite similar to the adapter pattern. An adapter pattern makes two unrelated, existing classes work together, when the two participants were not thought to be aware of each other during design. A bridge pattern separates concerns and is chosen at the design level before the creation of participating classes.

There is an abstraction that the client sees. There is an implementor which provides the interface for actual implementation. A refined abstraction which provides extension to the abstraction’s functionalities. And a ConcreteImplementor which is an implementation of the implementor.

PHP Code :

abstract class BridgeBook
{
  private $bbAuthor;
  private $bbTitle;
  private $bbImp;
  function __construct($author_in, $title_in, $choice_in)
  {
    $this->bbAuthor = $author_in;
    $this->bbTitle  = $title_in;
    if ('STARS' == $choice_in)
    {
      $this->bbImp = new BridgeBookStarsImp();
    } else
    {
      $this->bbImp = new BridgeBookCapsImp();
    }
  }
  function showAuthor()
  {
    return $this->bbImp->showAuthor($this->bbAuthor);
  }
  function showTitle()
  {
    return $this->bbImp->showTitle($this->bbTitle);
  }
}

class BridgeBookAuthorTitle extends BridgeBook
{
  function showAuthorTitle()
  {
    return $this->showAuthor() . "'s " . $this->showTitle();
  }
}

class BridgeBookTitleAuthor extends BridgeBook
{
  function showTitleAuthor()
  {
    return $this->showTitle() . ' by ' . $this->showAuthor();
  }
}

abstract class BridgeBookImp
{
  abstract function showAuthor($author);
  abstract function showTitle($title);
}

class BridgeBookCapsImp extends BridgeBookImp
{
  function showAuthor($author_in)
  {
    return strtoupper($author_in);
  }
  function showTitle($title_in)
  {
    return strtoupper($title_in);
  }
}

class BridgeBookStarsImp extends BridgeBookImp
{
  function showAuthor($author_in)
  {
    return Str_replace(" ","*",$author_in);
  }
  function showTitle($title_in)
  {
    return Str_replace(" ","*",$title_in);
  }
}

echo('BEGIN'."n");

echo('test 1 - author title with caps');
$book = new BridgeBookAuthorTitle('Larry Truett','PHP for Cats','CAPS');
echo($book->showAuthorTitle());
echo("n");

echo('test 2 - author title with stars');
$book = new BridgeBookAuthorTitle('Larry Truett','PHP for Cats','STARS');
echo($book->showAuthorTitle());
echo("n");

echo('test 3 - title author with caps');
$book = new BridgeBookTitleAuthor('Larry Truett','PHP for Cats','CAPS');
echo($book->showTitleAuthor());
echo("n");

echo('test 4 - title author with stars');
$book = new BridgeBookTitleAuthor('Larry Truett','PHP for Cats','STARS');
echo($book->showTitleAuthor());
echo("n");

echo('END'."n");

Output : 
BEGIN
test 1 - author title with capsLARRY TRUETT's PHP FOR CATS
test 2 - author title with starsLarry*Truett's PHP*for*Cats
test 3 - title author with capsPHP FOR CATS by LARRY TRUETT
test 4 - title author with starsPHP*for*Cats by Larry*Truett
END

Java Code :

/** "Implementor" */
interface DrawingAPI 
{
  public void drawCircle(double x, double y, double radius);
}

/** "ConcreteImplementor" 1/2 */
class DrawingAPI1 implements DrawingAPI 
{
  public void drawCircle(double x, double y, double radius) 
  {
    System.out.printf("API1.circle at %f:%f radius %fn", x, y, radius);
  }
}

/** "ConcreteImplementor" 2/2 */
class DrawingAPI2 implements DrawingAPI 
{
  public void drawCircle(double x, double y, double radius) 
  { 
    System.out.printf("API2.circle at %f:%f radius %fn", x, y, radius);
  }
}

/** "Abstraction" */
interface Shape 
{
  public void draw();                             // low-level
  public void resizeByPercentage(double pct);     // high-level
}

/** "Refined Abstraction" */
class CircleShape implements Shape 
{
  private double x, y, radius;
  private DrawingAPI drawingAPI;
  public CircleShape(double x, double y, double radius, DrawingAPI drawingAPI) 
  {
    this.x = x;  
    this.y = y;  
    this.radius = radius; 
    this.drawingAPI = drawingAPI;
  }

  // low-level i.e. Implementation specific
  public void draw() 
  {
    drawingAPI.drawCircle(x, y, radius);
  }   
  // high-level i.e. Abstraction specific
  public void resizeByPercentage(double pct) 
  {
    radius *= pct;
  }
}

/** "Client" */
public class Bridge
{
  public static void main(String[] args) 
  {
    Shape[] shapes = new Shape[2];
    shapes[0] = new CircleShape(1, 2, 3, new DrawingAPI1());
    shapes[1] = new CircleShape(5, 7, 11, new DrawingAPI2());

    for (Shape shape : shapes) 
    {
      shape.resizeByPercentage(2.5);
      shape.draw();
    }
  }
}

Output :

API1.circle at 1.000000:2.000000 radius 7.500000
API2.circle at 5.000000:7.000000 radius 27.500000

Design patterns : Adapter Design Pattern

Adapter design pattern converts the interface of a class into another interface that the client expects. It lets the classes work together that otherwise could not because of incompatible interfaces. It wraps the existing class in a compatible interface acceptible to the the client.

The actors here are the client – which makes use of an object which implements the target interface, the target is the point of extension of the client module, adaptee – object of different module or library and the adapter is an implementation of the target which forwards real work to the adaptee and also hides him from the client.

PHP Code :

class SimpleBook
{
  private $author;
  private $title;
  function __construct($author_in, $title_in)
  {
    $this->author = $author_in;
    $this->title  = $title_in;
  }
  function getAuthor()
  {
    return $this->author;
  }
  function getTitle()
  {
    return $this->title;
  }
}

class BookAdapter
{
  private $book;
  function __construct(SimpleBook $book_in)
  {
    $this->book = $book_in;
  }
  function getAuthorAndTitle()
  {
    return $this->book->getTitle().' by '.$this->book->getAuthor();
  }
}

// client

echo "BEGINn";

$book = new SimpleBook("PHP Author", "PHP Book on Design patterns");
$bookAdapter = new BookAdapter($book);
echo "Author and Title: ".$bookAdapter->getAuthorAndTitle()."n";

echo "ENDn";

Output:

BEGIN
Author and Title: PHP Book on Design patterns by PHP Author
END

JAVA Code:

class LegacyLine
{
  public void draw(int x1, int y1, int x2, int y2)
  {
    System.out.println("line from (" + x1 + ',' + y1 + ") to (" + x2 + ','  + y2 + ')');
  }
}

class LegacyRectangle
{
  public void draw(int x, int y, int w, int h)
  {
    System.out.println("rectangle at (" + x + ',' + y + ") with width " + w  + " and height " + h);
  }
}

interface Shape
{
  void draw(int x1, int y1, int x2, int y2);
}

class Line implements Shape
{
  private LegacyLine adaptee = new LegacyLine();
  public void draw(int x1, int y1, int x2, int y2)
  {
    adaptee.draw(x1, y1, x2, y2);
  }
}

class Rectangle implements Shape
{
  private LegacyRectangle adaptee = new LegacyRectangle();
  public void draw(int x1, int y1, int x2, int y2)
  {
    adaptee.draw(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2 - x1),   Math.abs(y2 - y1));
  }
}

public class AdapterDemo
{
  public static void main(String[] args)
  {
    Shape[] shapes = 
    {
      new Line(), new Rectangle()
    };
    // A begin and end point from a graphical editor
    int x1 = 10, y1 = 20;
    int x2 = 30, y2 = 60;
    for (int i = 0; i < shapes.length; ++i)
      shapes[i].draw(x1, y1, x2, y2);
  }
}

Output : 

line from (10,20) to (30,60)
rectangle at (10,20) with width 20 and height 40

Design Patterns : Prototype pattern

The prototype pattern specifies the kind of objects to create using a prototypical instance, and creates new objects by copying the prototype. A clone method is available in the class which can be used to create new objects of the same kind.

The pattern consists of a prototype – an interface of the cloneable classes. A ConcretePrototype implements the clone operations and a client actually clones the prototype instance to use the clones as new objects.

Simple examples

PHP

abstract class BookPrototype
{
  protected $title;
  protected $topic;
  abstract function __clone();
  function getTitle()
  {
    return $this->title;
  }
  function setTitle($titleIn)
  {
    $this->title = $titleIn;
  }
  function getTopic()
  {
    return $this->topic;
  }
}

class PHPBookPrototype extends BookPrototype
{
  function __construct()
  {
    $this->topic = 'PHP';
  }
  function __clone()
  {  }
}

class SQLBookPrototype extends BookPrototype
{
  function __construct()
  {
    $this->topic = 'SQL';
  }
  function __clone()
  {  }
}

echo("BEGIN n");

$phpProto = new PHPBookPrototype();
$sqlProto = new SQLBookPrototype();

$book1 = clone $sqlProto;
$book1->setTitle('SQL Book prototype');
echo('Book 1 topic: '.$book1->getTopic()."n");
echo('Book 1 title: '.$book1->getTitle()."n");

$book2 = clone $phpProto;
$book2->setTitle('PHP Book prototype');
echo('Book 2 topic: '.$book2->getTopic()."n");
echo('Book 2 title: '.$book2->getTitle()."n");

$book3 = clone $sqlProto;
$book3->setTitle('SQL Book prototype II');
echo('Book 3 topic: '.$book3->getTopic()."n");
echo('Book 3 title: '.$book3->getTitle()."n");

echo("ENDn");

Output:

BEGIN 
Book 1 topic: SQL
Book 1 title: SQL Book prototype
Book 2 topic: PHP
Book 2 title: PHP Book prototype
Book 3 topic: SQL
Book 3 title: SQL Book prototype II
END

Java :

public class proto 
{
  interface Xyz 
  {
    Xyz cloan();
  }

  static class Tom implements Xyz 
  {
    public Xyz cloan()    
    {
      return new Tom();
    }
    public String toString() 
    {
      return "tom prototype";
    }
  }

  static class Dick implements Xyz 
  {
    public Xyz    cloan()    
    {
      return new Dick();
    }
    public String toString() 
    {
      return "dick prototype";
    }
  }

  static class Harry implements Xyz 
  {
    public Xyz    cloan()    
    {
      return new Harry();
    }
    public String toString() 
    {
      return "harry prototype";
    }
  }

  static class Factory 
  {
    private static java.util.Map prototypes = new java.util.HashMap();
    static 
    {
      prototypes.put( "tom",   new Tom() );
      prototypes.put( "dick",  new Dick() );
      prototypes.put( "harry", new Harry() );
    }
    public static Xyz makeObject( String s ) 
    {
      return ((Xyz)prototypes.get(s)).cloan();
    }
  }

  public static void main( String[] args ) 
  {
    for (int i=0; i < args.length; i++) 
    {
      System.out.println( Factory.makeObject( args[i] ) + "  " );
    }
  }
}

Output : 
$ java proto tom dick harry harry tomtom prototype  
dick prototype  
harry prototype  
harry prototype  
tom prototype 

Design patterns : Factory Method

Factory method defines an interface for creating an object, but lets the subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.

Factory method makes the design more customizable and only a little more complicated. Other design patterns require new classes whereas factory method requires only a new operation.

Factory method is quite similar to the Abstract Factory. In fact every relevant method of Abstract Factory is a Factory Method. Factory methods could be moved out of their classes in subsequent refactoring and evolve in an external Abstract Factory.

The participating actors are the “Product” – the abstraction of the created object, a “concrete product” – an implementation of the product. “Creator” is the base class which declares a default Factory Method and “ConcreteCreator” is a subclass of the creator which overrides the Factory Method to return a Concrete Product.

Lets check some code

PHP : lets check some code similar to those we wrote for Abstract Factory

abstract class AbstractFactoryMethod
{
  abstract function makeBook($param);
}

class OReillyFactoryMethod extends AbstractFactoryMethod
{
  private $context = "OReilly";
  function makeBook($param)
  {
    $book = NULL;
    switch($param)
    {
      case "PHP":
        $book = new OReillyPHPBook;
      break;
      case "MySQL":
        $book = new OReillyMySQLBook;
      break;
      default:
      $book = new OReillyPHPBook;
      break;
    }
    return $book;
  }
}

class SAMSFactoryMethod extends AbstractFactoryMethod
{
  private $context = "SAMS";
  function makeBook($param)
  {
    $book = NULL;
    switch($param)
    {
      case "PHP":
        $book = new SamsPHPBook;
      break;
      case "MySQL":
        $book = new SamsMySQLBook;
      break;
      default:
      $book = new SamsMySQLBook;
      break;
    }
    return $book;
  }
}

abstract class AbstractBook
{
  abstract function getAuthor();
  abstract function getTitle();
}

class OReillyPHPBook extends AbstractBook
{
  private $author;
  private $title;
  function __construct()
  {
    $this->author = "Author - OReilly php";
    $this->title = "Title - OReilly php";
  }

  function getAuthor() {return $this->author;}
  function getTitle() {return $this->title;}
}

class SamsPHPBook extends AbstractBook
{
  private $author;
  private $title;
  function __construct()
  {
    $this->author = "Author - SAMS php";
    $this->title = "Title - SAMS php";
  }

  function getAuthor() {return $this->author;}
  function getTitle() {return $this->title;}
}

class OReillyMySQLBook extends AbstractBook
{
  private $author;
  private $title;
  function __construct()
  {
    $this->author = "Author - OReilly MySQL";
    $this->title = "Title - OReilly MySQL";
  }

  function getAuthor() {return $this->author;}
  function getTitle() {return $this->title;}
}

class SamsMySQLBook extends AbstractBook
{
  private $author;
  private $title;
  function __construct()
  {
    $this->author = "Author - SAMS MySQL";
    $this->title = "Title - SAMS MySQL";
  }

  function getAuthor() {return $this->author;}
  function getTitle() {return $this->title;}
}

function testFactoryMethod($factoryMethodInstance)
{
  $phpBook = $factoryMethodInstance->makeBook("PHP");
  echo "php author : ".$phpBook->getAuthor()."n";
  echo "php title : ".$phpBook->getTitle()."n";

  $mysqlBook = $factoryMethodInstance->makeBook("MySQL");
  echo "mysql author : ".$mysqlBook->getAuthor()."n";
  echo "mysql title : ".$mysqlBook->getTitle()."n";
}

echo("Beginn");
echo("Testing OReillyFactoryMethodn");
$bookMethodInstance = new OReillyFactoryMethod;
testFactoryMethod($bookMethodInstance);
echo("----n");

echo("Testing SamsFactoryMethodn");
$bookMethodInstance = new SamsFactoryMethod;
testFactoryMethod($bookMethodInstance);
echo("----n");

Output : 

Begin
Testing OReillyFactoryMethod
php author : Author - OReilly php
php title : Title - OReilly php
mysql author : Author - OReilly MySQL
mysql title : Title - OReilly MySQL
----
Testing SamsFactoryMethod
php author : Author - SAMS php
php title : Title - SAMS php
mysql author : Author - SAMS MySQL
mysql title : Title - SAMS MySQL
----

And some example in java

abstract class Pizza 
{
  public abstract int getPrice(); // count the cents
}

class HamAndMushroomPizza extends Pizza 
{
  public int getPrice() 
  {
    return 850;
  }
}

class DeluxePizza extends Pizza 
{
  public int getPrice() 
  {
    return 1050;
  }
}

class HawaiianPizza extends Pizza 
{
  public int getPrice() 
  {
    return 1150;
  }
}

class PizzaFactory 
{
  public enum PizzaType 
  {
    HamMushroom,
      Deluxe,
      Hawaiian
  }

  public static Pizza createPizza(PizzaType pizzaType) 
  {
    switch (pizzaType) 
    {
      case HamMushroom:
        return new HamAndMushroomPizza();
      case Deluxe:
        return new DeluxePizza();
      case Hawaiian:
        return new HawaiianPizza();
    }
    throw new IllegalArgumentException("The pizza type " + pizzaType + " is not recognized.");
  }
}

class myPizza
{
  // Create all available pizzas and print their prices
  public static void main (String args[]) 
  {
    for (PizzaFactory.PizzaType pizzaType : PizzaFactory.PizzaType.values()) 
    {
      System.out.println("Price of " + pizzaType + " is " + PizzaFactory.createPizza(pizzaType).getPrice());
    }
  }
}

Output : 

$ java myPizza 
 Price of HamMushroom is 850
 Price of Deluxe is 1050
 Price of Hawaiian is 1150


Design patterns : Builder

The purpose of a builder is to separate the construction process of a complex object from its representation so that the same construction process can be used to create different representations.

The participating actors are a “director” which interprets the information and invokes the “builder” to get the object built. The builder creates parts of a complex object each time it is called and maintains the state of the object. Eventually when the product is complete, the client can retrieve the product from the “builder”.

Lets check out some code:

In PHP

abstract class AbstractPageBuilder //abstract builder
{
  abstract function getPage();
}

abstract class AbstractPageDirector //abstract director
{
  abstract function __construct(AbstractPageBuilder $builder_in);
  abstract function buildPage();
  abstract function getPage();
}

class HTMLPage //product 
{
  private $page = NULL;
  private $page_title = NULL;
  private $page_heading = NULL;
  private $page_text = NULL;
  function __construct() 
  {  }
  function showPage() 
  {
    return $this->page;
  }
  function setTitle($title_in) 
  {
    $this->page_title = $title_in;
  }
  function setHeading($heading_in) 
  {
    $this->page_heading = $heading_in;
  }
  function setText($text_in) 
  {
    $this->page_text .= $text_in;
  }
  function formatPage() 
  {
    $this->page  = "<html>n";
    $this->page .= "<head><title>".$this->page_title."</title></head>n";
    $this->page .= "<body>n";
    $this->page .= "<h1>".$this->page_heading."</h1>n";
    $this->page .= $this->page_text;
    $this->page .= "n</body>n";
    $this->page .= "</html>";
  }
}

class HTMLPageBuilder extends AbstractPageBuilder //concrete builder
{
  private $page = NULL;
  function __construct() 
  {
    $this->page = new HTMLPage();
  }
  function setTitle($title_in) 
  {
    $this->page->setTitle($title_in);
  }
  function setHeading($heading_in) 
  {
    $this->page->setHeading($heading_in);
  }
  function setText($text_in) 
  {
    $this->page->setText($text_in);
  }
  function formatPage() 
  {
    $this->page->formatPage();
  }
  function getPage() 
  {
    return $this->page;
  }
}

class HTMLPageDirector extends AbstractPageDirector //concrete director
{
  private $builder = NULL;
  public function __construct(AbstractPageBuilder $builder_in) 
  {
    $this->builder = $builder_in;
  }
  public function buildPage() 
  {
    $this->builder->setTitle('Testing HTMLPage Title');
    $this->builder->setHeading('Testing HTMLPage Heading');
    $this->builder->setText('Body1 Testing, testing, testing!');
    $this->builder->setText('Body2 Testing, testing, testing, or!');
    $this->builder->setText('Body3 Testing, testing, testing, more!');
    $this->builder->formatPage();
  }
  public function getPage() 
  {
    return $this->builder->getPage();
  }
}

echo("BEGINn");

$pageBuilder = new HTMLPageBuilder();
$pageDirector = new HTMLPageDirector($pageBuilder);
$pageDirector->buildPage();
$page = $pageDirector->GetPage();
echo $page->showPage();
echo "nENDn";

Output:

BEGIN
<html>
<head><title>Testing HTMLPage Title</title></head>
<body>
<h1>Testing HTMLPage Heading</h1>
Body1 Testing, testing, testing!Body2 Testing, testing, testing, or!Body3 Testing, testing, testing, more!
</body>
</html>
END

The classic pizza example in java

/* "Product" */
class Pizza 
{
  private String dough = "";
  private String sauce = "";
  private String topping = "";

  public void setDough(String dough)     { this.dough = dough; }
  public void setSauce(String sauce)     { this.sauce = sauce; }
  public void setTopping(String topping) { this.topping = topping; }

  public void showPizza()
  {
    System.out.println("PIZZA........");
    System.out.println("Dough : "+this.dough);
    System.out.println("Sauce : "+this.sauce);
    System.out.println("Topping : "+this.topping);
    System.out.println("----------");
  }
}

/* "Abstract Builder" */
abstract class PizzaBuilder 
{
  protected Pizza pizza;

  public Pizza getPizza() { return pizza; }
  public void createNewPizzaProduct() 
  { 
    pizza = new Pizza(); 
  }

  public abstract void buildDough();
  public abstract void buildSauce();
  public abstract void buildTopping();

}

/* "ConcreteBuilder" */
class HawaiianPizzaBuilder extends PizzaBuilder 
{
  public void buildDough()   { pizza.setDough("cross"); }
  public void buildSauce()   { pizza.setSauce("mild"); }
  public void buildTopping() { pizza.setTopping("ham+pineapple"); }
}

/* "ConcreteBuilder" */
class SpicyPizzaBuilder extends PizzaBuilder 
{
  public void buildDough()   { pizza.setDough("pan baked"); }
  public void buildSauce()   { pizza.setSauce("hot"); }
  public void buildTopping() { pizza.setTopping("pepperoni+salami"); }
}

/* "Director" */
class Waiter 
{
  private PizzaBuilder pizzaBuilder;

  public void setPizzaBuilder(PizzaBuilder pb) { pizzaBuilder = pb; }
  public Pizza getPizza() { return pizzaBuilder.getPizza(); }

  public void constructPizza() 
  {
    pizzaBuilder.createNewPizzaProduct();
    pizzaBuilder.buildDough();
    pizzaBuilder.buildSauce();
    pizzaBuilder.buildTopping();
  }
}

/* A customer ordering a pizza. */
public class BuilderExample 
{
  public static void main(String[] args) 
  {
    Waiter waiter = new Waiter();
    PizzaBuilder hawaiian_pizzabuilder = new HawaiianPizzaBuilder();
    PizzaBuilder spicy_pizzabuilder = new SpicyPizzaBuilder();

    waiter.setPizzaBuilder( hawaiian_pizzabuilder );
    waiter.constructPizza();

    Pizza pizza = waiter.getPizza();
    pizza.showPizza();
  }
}

Output:

PIZZA........
Dough : cross
Sauce : mild
Topping : ham+pineapple
----------

Design patterns : Abstract Factory

The abstract factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. It encapsulates the possibility of creation of a suite of “products” which otherwise would have required a sequence of “if .. then .. else” statements. The abstract factory has the responsibility for providing creation services for the entire family of objects. Clients never create the objects directly – they ask the factory to do that for them.

This mechanism makes changing the entiry family of objects easy – because the specific class of factory object appears only once in the application – where it was instantiated. The application can replace the entire family of objects by simply instantiating a different instance of the abstract factory. It also provides for lazy creation of objects.

The participating actors here are the client, the abstract factory, the abstract product, the concrete factory and the concrete product. The abstract factory defines which objects the concrete factory will need to be able to create. The concrete factory must create the correct objects for its context, ensuring that all objects created by the concrete factory are able to work correctly for a given circumstance.

Lets take an example to explain the situation. The AbstractBookFactory specifies that two classes – the AbstractPHPBook and the AbstractMySQLBook will need to be created by the concrete factory. The concreate factory OReillyBookFactory extends the AbstractBookFactory and can create the objects for OReillyPHPBook and OReillyMySQLBook which are correct classes for the context of OReilly.

abstract class AbstractBookFactory
{
  abstract function makePHPBook();
  abstract function makeMySQLBook();
}

//for objects in context of OReilly
class OReillyBookFactory extends AbstractBookFactory
{
  private $context = "OReilly";
  function makePHPBook()
  {
    return new OReillyPHPBook;
  }
  function makeMySQLBook()
  {
    return new OReillyMySQLBook;
  }
}

//for objects in context of Sams
class SamsBookFactory extends AbstractBookFactory
{
  private $context = "Sams";
  function makePHPBook()
  {
    return new SamsPHPBook;
  }
  function makeMySQLBook()
  {
    return new SamsMySQLBook;
  }
}

//Classes for books
abstract class AbstractBook
{
  abstract function getAuthor();
  abstract function getTitle();
}

abstract class AbstractPHPBook
{
  private $subject = "PHP";
}

abstract class AbstractMySQLBook
{
  private $subject = "MySQL";
}

class OReillyPHPBook extends AbstractPHPBook
{
  private $author;
  private $title;

  function __construct()
  {
    $this->author = "OReilly : php author 1";
    $this->title = "OReilly : title for php";
  }

  function getAuthor()
  {
    return $this->author;
  }

  function getTitle()
  {
    return $this->title;
  }
}

class SamsPHPBook extends AbstractPHPBook
{
  private $author;
  private $title;

  function __construct()
  {
    $this->author = "Sams : php author";
    $this->title = "Sams : title for php";
  }

  function getAuthor()
  {
    return $this->author;
  }

  function getTitle()
  {
    return $this->title;
  }
}

class OReillyMySQLBook extends AbstractMySQLBook
{
  private $author;
  private $title;

  function __construct()
  {
    $this->author = "OReilly : MySQL author";
    $this->title = "OReilly : title for MySQL";
  }

  function getAuthor()
  {
    return $this->author;
  }

  function getTitle()
  {
    return $this->title;
  }
}

class SamsMySQLBook extends AbstractMySQLBook
{
  private $author;
  private $title;

  function __construct()
  {
    $this->author = "Sams : MySQL author";
    $this->title = "Sams : title for MySQL";
  }

  function getAuthor()
  {
    return $this->author;
  }

  function getTitle()
  {
    return $this->title;
  }
}

//testing 

echo("Beginn");
echo("Testing OReillyBookFactoryn");
$bookFactoryInstance = new OReillyBookFactory;
testConcreteFactory($bookFactoryInstance);
echo("----n");

echo("Testing SamsBookFactoryn");
$bookFactoryInstance = new SamsBookFactory;
testConcreteFactory($bookFactoryInstance);
echo("----n");

function testConcreteFactory($bookFactoryInstance)
{
  $phpBook = $bookFactoryInstance->makePHPBook();
  echo "php author : ".$phpBook->getAuthor()."n";
  echo "php title : ".$phpBook->getTitle()."n";

  $mysqlBook = $bookFactoryInstance->makeMySQLBook();
  echo "mysql author : ".$mysqlBook->getAuthor()."n";
  echo "mysql title : ".$mysqlBook->getTitle()."n";
}

//Output

Begin
Testing OReillyBookFactory
php author : OReilly : php author 1
php title : OReilly : title for php
mysql author : OReilly : MySQL author
mysql title : OReilly : title for MySQL
----
Testing SamsBookFactory
php author : Sams : php author
php title : Sams : title for php
mysql author : Sams : MySQL author
mysql title : Sams : title for MySQL
----

Another example using java

interface GUIFactory //Abstract Factory 
{
  public Button createButton();
}

class WinFactory implements GUIFactory //concrete Factory
{
  public Button createButton() 
  {
    return new WinButton();
  }
}

class OSXFactory implements GUIFactory //Concrete Factory
{
  public Button createButton() 
  {
    return new OSXButton();
  }
}

interface Button //Abstract Product 
{
  public void paint();
}

class WinButton implements Button //concrete Product
{
  public void paint() 
  {
    System.out.println("I'm a WinButton");
  }
}


class OSXButton implements Button //concrete Product
{
  public void paint() 
  {
    System.out.println("I'm an OSXButton");
  }
}


class Application //execution free of product type 
{
  public Application(GUIFactory factory)
  {
    Button button = factory.createButton();
    button.paint();
  }
}

public class ApplicationRunner 
{
  public static void main(String[] args) 
  {
    if(args.length != 1)
    {
      System.out.println("usage : java ApplicationRunner <0/1>");
      System.exit(1);
    }
    new Application(createOsSpecificFactory(args[0]));
  }

  public static GUIFactory createOsSpecificFactory(String ostype) 
  {
    if (ostype.equals("0"))
    {
      return new WinFactory();
    } 
    else 
    {
      return new OSXFactory();
    }
  }
}

Output
------

$ java ApplicationRunner 0
I'm a WinButton
$ java ApplicationRunner 1
I'm an OSXButton

Restore grub 2 after windows installation

Here is the step by step guide to recover Grub 2 (with ubuntu 9.10) after windows install. The steps are different than for recovering Grub 1 (as explained in this post:

You will need a LIVE cd if you are going to recover an Ubuntu Box. Boot the system with Live CD (I assume you are using Ubuntu Live CD). Press Alt+F2 and enter gnome-terminal command. And continue typing :

$sudo fdisk -l

This will show your partition table:

Device Boot Start End Blocks Id System
/dev/sda1 * 1 12748 102398278+ 7 HPFS/NTFS
/dev/sda2 12749 60800 385977690 f W95 Ext’d (LBA)
/dev/sda5 12749 13003 2048256 82 Linux swap / Solaris
/dev/sda6 13004 16827 30716248+ 83 Linux
/dev/sda7 16828 25272 67834431 83 Linux
/dev/sda8 25273 32125 55046302+ 7 HPFS/NTFS
/dev/sda9 32126 60800 230331906 7 HPFS/NTFS

Now we need to mount Linux (sda6 and sda7 here). sda6 is the / partition and sda7 is the /home partition. So mount them accordingly. If you have any other partitions (specially boot partition) dont forget to mount them.

$sudo mount /dev/sda6 /mnt
$sudo mount /dev/sda7 /mnt/home
$sudo mount –bind /dev /mnt/dev
$sudo mount –bind /proc /mnt/proc
$sudo mount –bind /sys /mnt/sys

Now chroot into the enviroment we made :

$sudo chroot /mnt

You may want to edit /etc/default/grub file to fit your system (timeout options etc)

$vi /etc/default/grub

Once you are thru install grub2 by using

$grub-install /dev/sda

If you get errors with that code use:

$grub-install –recheck /dev/sda

Now you can exit the chroot, umount the system and reboot your box :

$exit
$sudo umount /mnt/home
$sudo umount /mnt/sys
$sudo umount /mnt/dev
$sudo umount /mnt/proc
$sudo umount /mnt
$sudo reboot