24 March 2010

Learning DesignPatterns: The Builder Pattern

largely inspired by Wikipedia:"Builder Pattern is a software design pattern. The intention is to abstract steps of construction of objects so that different implementations of these steps can construct different representations of objects."

Example


/**
* Taxon, the class to be constructed
*/
class Taxon
{
private int id=-1;
private int parent_id=-1;
private String name=null;

public void setId(int id) { this.id=id; }
public void setParentId(int parent_id) { this.parent_id=parent_id; }
public void setName(String name) { this.name=name; }
public int getId() { return this.id;}
public int getParentId() { return this.parent_id;}
public String getName() { return this.name;}
}

/** Abstract interface for creating Taxons */
abstract class TaxonBuilder
{
protected Taxon taxon=new Taxon();

public void createNewTaxon()
{
this.taxon = new Taxon();
}

public Taxon getTaxon()
{
return this.taxon;
}
public abstract void buildId();
public abstract void buildParentId();
public abstract void buildName();
}
/** concrete TaxonBuilder builder for HomoSapiens */
class HomoSapiensBuilder extends TaxonBuilder
{
public void buildId() { super.taxon.setId(9606);}
public void buildParentId() { super.taxon.setParentId(9605);}
public void buildName() { super.taxon.setName("Homo Sapiens");}
}

/** concrete TaxonBuilder builder for Platypus */
class PlatypusBuilder extends TaxonBuilder
{
public void buildId() { super.taxon.setId(9258);}
public void buildParentId() { super.taxon.setParentId(9257);}
public void buildName() { super.taxon.setName("Platypus");}
}

/** constructs a Taxon object by calling its TaxonBuilder */
class TaxonAssembler
{
private TaxonBuilder builder;

public void setTaxonBuilder(TaxonBuilder builder)
{
this.builder=builder;
}

public void assemble()
{
this.builder.createNewTaxon();
this.builder.buildId();
this.builder.buildParentId();
this.builder.buildName();
}
}

public class Test
{
public static void main(String[] args) {
{
TaxonBuilder builder=new PlatypusBuilder();
TaxonAssembler assembler=new TaxonAssembler();
assembler.setBuilder(builder);
assembler.assemble();
Taxon taxon=builder.getTaxon();
}
}

That's it.

Pierre

No comments: