<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.3.3" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>twit88.com &#187; Behavioral</title>
	<link>http://twit88.com/blog</link>
	<description>Good judgement comes from experience, and experience comes from bad judgement.</description>
	<pubDate>Wed, 19 Nov 2008 06:30:21 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.3.3</generator>
	<language>en</language>
			<item>
		<title>Design Pattern: Design a Simple Workflow using Chain of Responsibility Pattern</title>
		<link>http://twit88.com/blog/2008/03/17/design-pattern-design-a-simple-workflow-using-chain-of-responsibility-pattern/</link>
		<comments>http://twit88.com/blog/2008/03/17/design-pattern-design-a-simple-workflow-using-chain-of-responsibility-pattern/#comments</comments>
		<pubDate>Mon, 17 Mar 2008 15:56:15 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Behavioral]]></category>

		<category><![CDATA[Java]]></category>

		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://twit88.com/blog/2008/03/17/design-pattern-design-a-simple-workflow-using-chain-of-responsibility-pattern/</guid>
		<description><![CDATA[Download Source Code
I was trying Apache Commons Chain when I was trying to design a simple workflow system for my back-end application using the Chain of Responsibility design pattern. 
Chain of Responsibility is a popular technique for organizing the execution of complex processing flows. It is not difficult if you want to write it yourself [...]]]></description>
			<content:encoded><![CDATA[<p><a href='http://twit88.com/blog/wp-content/uploads/2008/03/chain_source.zip' title='chain_source.zip'>Download Source Code</a></p>
<p>I was trying <a href="http://commons.apache.org/chain/">Apache Commons Chain</a> when I was trying to design a simple workflow system for my back-end application using the Chain of Responsibility design pattern. </p>
<p>Chain of Responsibility is a popular technique for organizing the execution of complex processing flows. It is not difficult if you want to write it yourself but Commons Chain has already implemented this pattern for you. </p>
<p>Commons Chain models a computation as a series of &quot;commands&quot; that can be combined into a &quot;chain&quot;. The API for a command consists of a single method (<code>execute()</code>), which is passed a &quot;context&quot; parameter containing the dynamic state of the computation, and whose return value is a boolean that determines whether or not processing for the current chain has been completed (true), or whether processing should be delegated to the next command in the chain (false).</p>
<p>E.g., first I create my custom context to be passed around my flows.</p>
<pre>
import org.apache.commons.chain.impl.ContextBase;

public class MyContext extends ContextBase {
    private String name;
    private String email;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
</pre>
<p>Then I created my processes, each one as a command.</p>
<pre>
import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;

public class Command1 implements Command {

    public boolean execute(Context context) throws Exception {
        System.out.println("First command");
        MyContext myContext = (MyContext)context;
        myContext.setName("twit88");
        return false;
    }
}

import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;

public class Command2 implements Command {

    public boolean execute(Context context) throws Exception {
        System.out.println("Second command");
        MyContext myContext = (MyContext)context;
        myContext.setEmail("admin@twit88.com");
        return false;
    }
}

import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;

public class Command3 implements Command {

    public boolean execute(Context context) throws Exception {
        System.out.println("Third command");
        MyContext myContext = (MyContext)context;
        System.out.println("name: " + myContext.getName());
        System.out.println("email: " + myContext.getEmail());
        return false;
    }
}
</pre>
<p>I defined the sequence of processing in a configuration file.</p>
<pre>
&lt;catalog&gt;

  &lt;!-- Single command "chains"
         from CatalogBaseTestCase --&gt;
  &lt;command   name="MyFirstCommand"
        className="Command1"/&gt;
  &lt;command   name="MySecondCommand"
        className="Command2"/&gt;
  &lt;command   name="MySecondCommand"
        className="Command3"/&gt;

  &lt;!-- Chains with nested commands --&gt;
  &lt;chain     name="MyFlow"&gt;
    &lt;command   id="1"
        className="Command1"/&gt;
    &lt;command   id="2"
        className="Command2"/&gt;
    &lt;command   id="3"
        className="Command3"/&gt;
  &lt;/chain&gt;

&lt;/catalog&gt;
</pre>
<p>Then I can test it.</p>
<pre>
import org.apache.commons.chain.Catalog;
import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;
import org.apache.commons.chain.config.ConfigParser;
import org.apache.commons.chain.impl.CatalogFactoryBase;

public class TestChain {

    private static final String CONFIG_FILE = "/chain.xml";
    private ConfigParser parser;
    private Catalog catalog;

    public TestChain() {
        parser = new ConfigParser();
    }

    public Catalog getCatalog() throws Exception {
        if (catalog == null) {
            parser.parse(
              this.getClass().getResource(CONFIG_FILE));

        }
        catalog = CatalogFactoryBase.getInstance().getCatalog();
        return catalog;
    }

    public static void main(String[] args) throws Exception {
        TestChain chain = new TestChain();
        Catalog catalog = chain.getCatalog();
        Command command = catalog.getCommand("MyFlow");
        Context ctx = new MyContext();
        command.execute(ctx);
    }

}
</pre>
<p>The output</p>
<pre>
First command
Second command
Third command
name: twit88
email: admin@twit88.com
</pre>
<p>Another interesting article for reading will be <a href="http://www.javaworld.com/javaworld/jw-04-2005/jw-0411-spring.html">using Spring to create the workflow</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://twit88.com/blog/2008/03/17/design-pattern-design-a-simple-workflow-using-chain-of-responsibility-pattern/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Design Pattern in Java 101 - Command Pattern (Behavioral Pattern)</title>
		<link>http://twit88.com/blog/2008/01/26/design-pattern-in-java-101-command-pattern-behavioral-pattern/</link>
		<comments>http://twit88.com/blog/2008/01/26/design-pattern-in-java-101-command-pattern-behavioral-pattern/#comments</comments>
		<pubDate>Sat, 26 Jan 2008 15:36:38 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Behavioral]]></category>

		<category><![CDATA[Java]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[design pattern]]></category>

		<guid isPermaLink="false">http://twit88.com/blog/2008/01/26/design-pattern-in-java-101-command-pattern-behavioral-pattern/</guid>
		<description><![CDATA[Download Sample Code
A Command pattern is an object behavioral pattern that allows us to achieve complete decoupling between the sender and the receiver. It allows you to encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests.
Here is a rewrite of the C# example provided in dofactory.com.
First [...]]]></description>
			<content:encoded><![CDATA[<p><a href='http://twit88.com/blog/wp-content/uploads/2008/01/java_command_pattern.zip' title='java_command_pattern.zip'>Download Sample Code</a></p>
<p>A <strong>Command</strong> pattern is an object behavioral pattern that allows us to achieve complete decoupling between the sender and the receiver. It allows you to encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests.</p>
<p>Here is a rewrite of the C# example provided in dofactory.com.</p>
<p>First define the <strong>Command</strong> interface.</p>
<pre>
public interface Command {
    public void execute();
    public void unExecute();
}
</pre>
<p>A <strong>Calculator</strong> is a good example.</p>
<pre>
public class Calculator {
    private int current = 0;

    public void operation(char operator, int operand) {
        switch (operator) {
            case '+':
                current += operand;
                break;
            case '-':
                current -= operand;
                break;
            case '*':
                current *= operand;
                break;
            case '/':
                current /= operand;
                break;
        }
        System.out.println("Current value = "
               + current + " after " + operator + " " + operand);
    }
}
</pre>
<p><strong>CalculatorCommand</strong> wraps the <strong>Calculator</strong>.</p>
<pre>
public class CalculatorCommand implements Command {

    private char operator;
    private int operand;
    private Calculator calculator;

    public CalculatorCommand(Calculator calculator,
                             char operator, int operand) {
        this.calculator = calculator;
        this.operator = operator;
        this.operand = operand;
    }

    public char getOperator() {
        return operator;
    }

    public void setOperator(char operator) {
        this.operator = operator;
    }

    public int getOperand() {
        return operand;
    }

    public void setOperand(int operand) {
        this.operand = operand;
    }

    public void execute() {
        calculator.operation(operator, operand);
    }

    public void unExecute() {
        calculator.operation(undo(operator), operand);
    }

    // Private helper function
    private char undo(char operator) {
        char undo;
        switch (operator) {
            case '+':
                undo = '-';
                break;
            case '-':
                undo = '+';
                break;
            case '*':
                undo = '/';
                break;
            case '/':
                undo = '*';
                break;
            default:
                undo = ' ';
                break;
        }
        return undo;
    }
}
</pre>
<p><strong>User</strong> invokes calculator.</p>
<pre>
import java.util.ArrayList;

public class User {
    private Calculator calculator = new Calculator();
    private ArrayList&lt;Command&gt; commands =
        new ArrayList&lt;Command&gt;();

    private int current = 0;

    public void redo(int levels) {
        System.out.println("\n---- Redo " + levels + " levels ");
        // Perform redo operations
        for (int i = 0; i &lt; levels; i++) {
            if (current &lt; commands.size()) {
                Command command = commands.get(current++);
                command.execute();
            }
        }
    }

    public void undo(int levels) {
        System.out.println("\n---- Undo " + levels + " levels ");
        // Perform undo operations
        for (int i = 0; i &lt; levels; i++) {
            if (current &gt;= 0) {
                Command command = commands.get(--current);
                command.unExecute();
            }
        }
    }

    public void compute(char operator, int operand) {
        // Create command operation and execute it
        Command command = new CalculatorCommand(
                calculator, operator, operand);
        command.execute();

        // Add command to undo list
        commands.add(command);
        current++;
    }
}
</pre>
<p>To test it</p>
<pre>
public class TestCommandPattern {

    public static void main(String[] args) {
        // Create user and let her compute
        User user = new User();

        user.compute('+', 100);
        user.compute('-', 50);
        user.compute('*', 10);
        user.compute('/', 2);

        // Undo 4 commands
        user.undo(4);

        // Redo 3 commands
        user.redo(3);

    }
}
</pre>
<p>The output</p>
<pre>
Current value = 100 after + 100
Current value = 50 after - 50
Current value = 500 after * 10
Current value = 250 after / 2

---- Undo 4 levels
Current value = 500 after * 2
Current value = 50 after / 10
Current value = 100 after + 50
Current value = 0 after - 100

---- Redo 3 levels
Current value = 100 after + 100
Current value = 50 after - 50
Current value = 500 after * 10
</pre>
]]></content:encoded>
			<wfw:commentRss>http://twit88.com/blog/2008/01/26/design-pattern-in-java-101-command-pattern-behavioral-pattern/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Design Pattern in Java 101 - Visitor Pattern (Behavioral Pattern)</title>
		<link>http://twit88.com/blog/2007/12/28/design-pattern-in-java-101-visitor-pattern-behavioral-pattern/</link>
		<comments>http://twit88.com/blog/2007/12/28/design-pattern-in-java-101-visitor-pattern-behavioral-pattern/#comments</comments>
		<pubDate>Fri, 28 Dec 2007 06:40:22 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Behavioral]]></category>

		<category><![CDATA[Java]]></category>

		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://twit88.com/blog/2007/12/28/design-pattern-in-java-101-visitor-pattern-behavioral-pattern/</guid>
		<description><![CDATA[Download Source Code
NOTE: This is written for me to recap and relearn what I learnt before&#8230;.
This article is written in order for me to recap what I have learnt and used before, though I know there are already many sites which talked about all these.
Visitor Pattern  defines a new operation to deal with the [...]]]></description>
			<content:encoded><![CDATA[<p><a href='http://twit88.com/blog/wp-content/uploads/2007/12/java_visitor_pattern.zip' title='java_visitor_pattern.zip'>Download Source Code</a></p>
<p>NOTE: This is written for me to recap and relearn what I learnt before&#8230;.</p>
<p>This article is written in order for me to recap what I have learnt and used before, though I know there are already many sites which talked about all these.</p>
<p><strong>Visitor Pattern </strong> defines a new operation to deal with the classes of the elements without changing their structures.</p>
<p>E.g., </p>
<p>Create a <strong>IProcess</strong> interface,</p>
<pre>
public interface IProcessor {
    public void process(IMessage message);
}
</pre>
<p><strong>IProcessor</strong> accepts <strong>IMessage</strong> as the parameter.</p>
<p>Create a <strong>IMessage</strong> interface,</p>
<pre>
public interface IMessage {
    public String parse();
}
</pre>
<p>Create a <strong>MessageProcessor</strong> class which implements <strong>IProcessor</strong></p>
<pre>
public class MessageProcessor implements IProcessor{

    private String messageType;

    public void process(IMessage message) {
        messageType = message.parse();
    }

    public String toString() {
        return "Processor for " + messageType ;
    }
}
</pre>
<p>Create <strong>SMSMessage</strong> and <strong>MMSMessage</strong> class which implement <strong>IMessage</strong></p>
<pre>
public class SMSMessage implements IMessage {

    public String parse() {
        return "SMS Message";
    }
}
</pre>
<pre>
public class MMSMessage implements IMessage {

    public String parse() {
        return "MMS Message";
    }
}
</pre>
<p>You can create another message processor depending on your need.</p>
<pre>
public class AnotherMessageProcessor {
    private String messageType;

    public void process(IMessage message) {
        messageType = message.parse();
    }

    public String toString() {
        return "Another Processor for " + messageType;
    }
}
</pre>
<p>To test it, use the following code stub</p>
<pre>

public class TestPattern {

    public static void main(String[] args) {
        MMSMessage mmsMessage = new MMSMessage();
        SMSMessage smsMessage = new SMSMessage();

        MessageProcessor messageProcessor = new MessageProcessor();
        AnotherMessageProcessor
                   anotherMessageProcessor =
                                   new AnotherMessageProcessor();

        messageProcessor.process(mmsMessage);
        System.out.println(messageProcessor.toString());

        messageProcessor.process(smsMessage);
        System.out.println(messageProcessor.toString());

        anotherMessageProcessor.process(mmsMessage);
        System.out.println(anotherMessageProcessor.toString());

        anotherMessageProcessor.process(smsMessage);
        System.out.println(anotherMessageProcessor.toString());
    }
}
</pre>
<p>The output</p>
<pre>
Processor for MMS Message
Processor for SMS Message
Another Processor for MMS Message
Another Processor for SMS Message
</pre>
]]></content:encoded>
			<wfw:commentRss>http://twit88.com/blog/2007/12/28/design-pattern-in-java-101-visitor-pattern-behavioral-pattern/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
