23 March 2010

Learning DesignPatterns: AbstractFactoryPattern

In the very next posts, I'll post my notes about the "Design Patterns". A Design Pattern is a "general reusable solution to a commonly occurring problem in software design". Here, I'll follow the patterns described at http://c2.com/cgi/wiki?DesignPatternsBook and will try to apply them to Bioinformatics. Today I'm starting with the AbstractFactoryPattern.

via Wikipedia:AbstractFactoryPattern provides a way to encapsulate a group of individual factories that have a common theme. In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interfaces to create the concrete objects that are part of the theme.
Use of this pattern makes it possible to interchange concrete classes without changing the code that uses them, even at runtime.


Example


/** the result of a pairwise alignment */
interface Alignment
{
public void print(PrintWriter out);
public double getScore();
}

/** interface for a pairwise alignment */
interface PairwiseAlignment
{
public Alignment align(CharSequence seq1,CharSequence seq2);
}

/** implementation of a global PairwiseAlignment */
class NeedlemanWunsch
implements PairwiseAlignment
{
public Alignment align(CharSequence seq1,CharSequence seq2)
{
(...)
}
}

/** implementation of a local PairwiseAlignment */
class SmithWaterman
implements PairwiseAlignment
{
public Alignment align(CharSequence seq1,CharSequence seq2)
{
(...)
}
}

/** abstract PairwiseAlignmentFactory
* contains an abstract method 'createPairwiseAligner'
* the static function 'newInstance' returns a new 'PairwiseAlignmentFactoryImpl'
*/
abstract class PairwiseAlignmentFactory
{
protected boolean global=true;

protected PairwiseAlignmentFactory()
{
}

public void setGlobal(boolean global)
{
this.global=global;
}

public boolean isGlobal()
{
return this.global;
}

/** abstract. to be implemented */
public abstract PairwiseAlignment createPairwiseAligner();

/** creates a new concrete instance of PairwiseAlignmentFactory */
static public PairwiseAlignmentFactory newInstance()
{
//described later...
return new PairwiseAlignmentFactoryImpl();
}
}

/** a concrete PairwiseAlignmentFactory
* implements createPairwiseAligner()
* instance created by PairwiseAlignment.newInstance()
*/
class PairwiseAlignmentFactoryImpl
extends
{
@Override
public PairwiseAlignment createPairwiseAligner()
{
return isGlobal() ?
new NeedlemanWunsch():
: new SmithWaterman();
}
}


That's it

Pierre

No comments: