<?xml version="1.0" encoding="UTF-8"?>
<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/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Gridshore &#187; design patterns</title>
	<atom:link href="http://www.gridshore.nl/tag/design-patterns/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.gridshore.nl</link>
	<description>A weblog about software engineering, Architecture, Technology an other things we like.</description>
	<lastBuildDate>Tue, 13 Dec 2011 15:36:58 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>The power of immutability in a Rich Domain Model</title>
		<link>http://www.gridshore.nl/2009/04/06/the-power-of-immutability-in-a-rich-domain-model/</link>
		<comments>http://www.gridshore.nl/2009/04/06/the-power-of-immutability-in-a-rich-domain-model/#comments</comments>
		<pubDate>Mon, 06 Apr 2009 19:00:00 +0000</pubDate>
		<dc:creator>Allard</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[domain model]]></category>
		<category><![CDATA[software design]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=696</guid>
		<description><![CDATA[<p>As many other developers, I’ve been used to the fat service layer and the anemic domain model of the transaction script pattern. In that programming model, immutability is pretty much as rare as a Dodo. However, I have been investigating the rich domain model pattern lately (as you can read in my previous post) [...]]]></description>
			<content:encoded><![CDATA[<p>As many other developers, I’ve been used to the fat service layer and the anemic domain model of the <a href="http://martinfowler.com/eaaCatalog/transactionScript.html" target="_blank">transaction script</a> pattern. In that programming model, immutability is pretty much as rare as a <a href="http://en.wikipedia.org/wiki/Dodo" target="_blank">Dodo</a>. However, I have been investigating the rich domain model pattern lately (as you can read in my <a href="http://www.gridshore.nl/2009/01/27/injecting-domain-objects-with-spring/">previous post</a>) and more importantly, a good migration path for “<a href="http://martinfowler.com/eaaCatalog/transactionScript.html" target="_blank">transaction script</a>” developers to get acquainted with the rich <a href="http://martinfowler.com/eaaCatalog/domainModel.html" target="_blank">Domain Model</a>, a design pattern that has been heavily underrated (and misunderstood) by many.</p>
<p>In this post, I will explain some of the advantages that immutable domain objects bring us, while showing that some of the seemingly problematic side effects aren’t really that problematic.</p>
</p>
<p> <span id="more-696"></span>
</p>
<p>A practical example is often the easiest way to explain these kind of things. Since the banking world has received enough discredit in these times, I will use another example than the infamous “withdrawal” example. Instead, we will use the almost-as-infamous product and order example.</p>
<p>Imagine an application where you can browse trough products and place an order for one or more of those products. Our simple domain will contain three entities: product, order and order line. A UML class diagram for this domain is shown below.</p>
<p><img title="power_of_immutability_class_diagram_1" style="border-top-width: 0px; display: block; border-left-width: 0px; float: none; border-bottom-width: 0px; margin-left: auto; margin-right: auto; border-right-width: 0px" height="216" alt="power_of_immutability_class_diagram_1" src="http://www.gridshore.nl/wp-content/uploads/power-of-immutability-class-diagram-12.jpg" width="323" border="0" /></p>
<h3>The anemic approach</h3>
<p>A commonly seen approach to implement this domain model is the following. The Order is implemented containing some delivery details and a list of order lines. The Order exposes getters and setters to modify each of those properties, including a getter that provides access to the list of order lines. The implementation of the OrderLine class is similar; it might contain a reference to a Product instance as well as a property to indicate the quantity ordered, resulting in the following code:</p>
<pre>
<pre class="brush: java; title: ; notranslate">
public class OrderLine {
    private Product product;
    private int quantity; 

    public Product getProduct() {
        return product;
    } 

    public void setProduct(final Product product) {
        this.product = product;
    } 

    public int getQuantity() {
        return quantity;
    } 

    public void setQuantity(final int quantity) {
        this.quantity = quantity;
    }
}
</pre>
</pre>
<p>This code has a few problems, some functional and some technical</p>
<ul>
<li>What happens if the price of the product changes? Invoices will probably show the new price (which is always higher, for some reason). </li>
<li>It’s no longer possible to delete a product, since you won’t be able to see what somebody ordered </li>
<li>You allow every other class in your application to modify the OrderLine at will. What if you have a discount for customers that order for a certain amount? Each time an order line was modified, your code would have to call a <code>calculateDiscount</code> in your order </li>
<li>If you want to calculate the total price of an order, you would have to iterate through all OrderLine and Product instances. </li>
</ul>
<p>Of course, each of those problems can be solved some way or another, but whatever you do to solve them, it only adds to the complexity already there.</p>
<h3>The immutable approach</h3>
<p>Making the OrderLine immutable will solve some of the problems outlined above. The state of immutable objects is exclusively set in the constructor, meaning that both the Product and quantity will have to be passed as constructor parameters.</p>
<p>To solve the problem of the Product changing state, we can copy some of the important fields into the OrderLine. Good candidates for copying are the product identifier, the product name and its price. In fact, we don’t need any reference to the original Product instance at all after the OrderLine has been constructed.</p>
<p>The implementation of the immutable OrderLine is then changed into the following:</p>
<pre>
<pre class="brush: java; title: ; notranslate">
public class OrderLine {

    private final String productIndentifier;
    private final String productName;
    private final Price itemPrice;
    private final Price totalPrice;
    private final int amount;

    public OrderLine(Product product, int amount) {
        this.productIndentifier = product.getIdentifier();
        this.productName = product.getName();
        this.itemPrice = product.getPrice();
        this.totalPrice = itemPrice.multiply(amount);
        this.amount = amount;
    }

    /* getters not shown for brevity */
}
</pre>
</pre>
<p>All problems solved? Well, no, not really. For starters, the last two problems enumerated above are still not solved. And then there is persistence. I use hibernate for nearly every project that requires persistence. Hibernate and immutable objects are not the best friends possible. Hibernate requires a non-private default constructor. Doesn’t seem like a problem, just add a no-argument constructor to you class. But then the <code>final</code> keyword ruins the game. You’ve got no other choice than to remove it. This removed the guaranteed visibility when your class is accessed by different threads at the same time. Solving that is a totally different ballgame and would carry me way off topic.</p>
<h3>Using an aggregate root</h3>
<p>We still have the problem that our discount is not updated when OrderLine instances are added or removed from an order. Making an order immutable in the same fashion would solve the problems. But let’s assume that a user is allowed to update and modify his orders as long they haven’t been processed by the system.</p>
<p>Exposing the list of OrderLine entries inside an order is not a good way to go, since your order is not in charge of its own lifecycle. If you take a close look at the UML diagram above, you will notice there is a composite relationship between the Order and OrderLine classes. This means that the Order class is responsible for the lifecycle of the OrderLine items that belong to it. In Domain Model terms, this means that Order is the <a href="http://domaindrivendesign.org/discussion/messageboardarchive/Aggregates.html" target="_blank">Aggregate Root</a> of these components.</p>
<p>The order would then be implemented as follows:</p>
<pre>
<pre class="brush: java; title: ; notranslate">
public class Order {

    private final List&lt;orderline&gt; orderLines = new ArrayList&lt;orderline&gt;();
    private final Customer customer;
    private Address shippingAddress;
    private Price totalAmount;

    public Order(Customer customer) {
        this.customer = customer;
    }

    public List&lt;orderline&gt; getOrderLines() {
        return Collections.unmodifiableList(orderLines);
    }

    public void addToOrder(Product product, int amount) {
        removeFromOrder(product);
        final OrderLine orderLine = new OrderLine(product, amount);
        orderLines.add(orderLine);
        totalAmount = totalAmount.add(orderLine.getTotalPrice());
        calculateDiscount();
    }

    public void removeFromOrder(Product product) {
        // implementation left to your imagination
    }

    /* rest of implementation left out for brevity */
}
</pre>
</pre>
<p>As you can see, a high level of encapsulation has been applied. It is now impossible to change any state of the Order or OrderLine without the Order knowing it. The list of OrderLine items that the Order exposes is made immutable using the utility method in the Collections class.</p>
<p>With this implementation, it the latter two of the problems enumerated above have been solved. Since the order is in charge of making the changes to its own state, it is rather easy to discover state changes that might impact applicable discounts or change the total amount of the order. Now, getting access to the amount of the order is as easy as returning the <code>totalAmount</code> property from the Order.</p>
<h3>Conclusion</h3>
<p>In this post, I’ve introduced a very powerful concept to manage the state of complex domain models: immutability. By preventing the application to change state directly, you gain more control over the the actions that need to be taken when the state changes. Especially in aggregates, immutability reduces the complexity of state management.</p>
<p>However, when using Hibernate, it is impossible to make an entity completely immutable using the final keywords. In that case it is sufficient to create a default constructor with package visibility and removing the final keywords.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2009%2F04%2F06%2Fthe-power-of-immutability-in-a-rich-domain-model%2F&amp;title=The%20power%20of%20immutability%20in%20a%20Rich%20Domain%20Model&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2009/04/06/the-power-of-immutability-in-a-rich-domain-model/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Using the Memento pattern to solve thread safety issues</title>
		<link>http://www.gridshore.nl/2008/12/27/using-the-memento-pattern-to-solve-thread-safety-issues/</link>
		<comments>http://www.gridshore.nl/2008/12/27/using-the-memento-pattern-to-solve-thread-safety-issues/#comments</comments>
		<pubDate>Sat, 27 Dec 2008 12:21:29 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[thread saftey]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/2008/12/27/using-the-memento-pattern-to-solve-thread-safety-issues/</guid>
		<description><![CDATA[Introduction <p style="FONT-SIZE: 0.8em" align="right">Author&#8217;s note: this is an article that I co-authoredwith a colleague, Robert van der Steen. It has also been published in our company newsletter.</p> <p>Many of the applications we write for our clients nowadays use the service paradigm: a dedicated and often reusable component within the application that is responsible [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p style="FONT-SIZE: 0.8em" align="right"><em>Author&#8217;s note: this is an article that I co-authored<br /></em><em>with a colleague, Robert van der Steen. It has also been<br />
published in our company newsletter.</em></p>
<p>Many of the applications we write for our clients nowadays use the service paradigm: a dedicated and often reusable component within the application that is responsible for a particular task or process. Such components are often written and used in such a way that a component is instantiated once and reused often within the runtime of the application (such as a web service or a Spring managed bean).</p>
<p>Using components in this way is a very resource-friendly way of constructing an application; resource-intensive objects are created only once and reused instead of having to be recreated and reinitialized for each request. However, they do make it necessary to pay special attention to issues that arise in reuse and concurrent use — specifically state management. A common technique to avoid such state problems is to build stateless components.</p>
<p>Unfortunately, mistakes happen in software engineering. Sometimes team members introduce state to shared components without thinking about it. This article discusses using the <a href="http://en.wikipedia.org/wiki/Memento_pattern">Memento pattern</a> as an easy way of transforming a stateful into a stateless service.</p>
<p><span id="more-552"></span><br />
<h3>The problem</h3>
<p>In order to illustrate the problem sketched above, let&#8217;s introduce an example. This example is an adaptation of a piece of code I stumbled upon in the codebase of a project:</p>
<pre>
                public class SpringManagedServiceClass {
                        private String oneField;
                        private String anotherField;

                        public boolean anOperation(final String input) {
                                oneField = someOperationOnInput(input);
                                anotherField = somethingElseInvolvingInput(input);
                                totalOperationSucceeded = operationOnTwoStrings(oneField, anotherField);
                                return totalOperationSucceeded;
                        }

                        public String getOneField() {
                                return oneField;
                        }

                        public String getAnotherField() {
                                return anotherField;
                        }
                }
</pre>
<p>The code above evolved from a class that was not managed by Spring and was instead instantiated each time the service was needed. In that form having state at the class level was no problem: each object was used once and then discarded. This meant it was also thread safe for a client of the service object to extract state using the getters. However, when moved over to Spring the class became a de facto <a href="http://en.wikipedia.org/wiki/Singleton_pattern">singleton</a> and therefore not thread safe. The person who converted the class to a Spring bean did not recognize this and so introduced a problem by allowing concurrent access to unguarded state.</p>
<p>A quick fix to this problem might be to move back from Spring to instantiation at use. Unfortunately, in this case the class had evolved to depend on a database connection managed by Spring, so moving away from Spring support would be a lot of work.</p>
<h3>Introducing the Memento</h3>
<p>The Memento pattern is a rather simple pattern that externalizes a classes (visible) state. The way it works is by following these steps:</p>
<ol start="0">
<li>Take a class C which has fields (i.e. objects with state).</li>
<li>Introduce a new class CMemento.</li>
<li>Move all the fields from C to CMemento. Make them private.</li>
<li>Introduce constructors, getters and setters into CMemento as needed.</li>
<li>In C, in your service methods, initialize a new instance of CMemento.</li>
<li>Refactor C to use the variables in CMemento instead of the variables C used to have itself.</li>
<li>Refactor the relevant methods of C to return a CMemento instead of their existing return types.</li>
<li>Refactor CMemento and C so that the previous return values of the methods of C are placed in the CMemento objects.</li>
<li>Finally, refactor the relevant methods of C again to place their previous return values in their CMemento objects before returning these objects.</li>
</ol>
<p>The CMemento classes take over the state of the class C in this pattern. C can instantiate a single CMemento instance or as many instances of CMemento as it likes and so create a set of states for itself. Each of these CMemento instances can be the &#8220;current&#8221; state of any object of type C at any time, so instances of C can roll back to a previous state easily or even swap states.</p>
<p>The Memento pattern is actually not meant to address the problem discussed in this article; it is meant to enable rolling back to a previous state. Fortunately for us the idea can be reused easily to solve our problem as well. Instead of being swappable however, we will refactor our service object to create a Memento object (an object to hold the externally visible state). The public service method will then return this Memento object and the service class will &#8220;abandon&#8221; its &#8220;state&#8221; after that, making the service completely stateless.</p>
<h3>The solution applied to the example</h3>
<p>First, let&#8217;s introduce our Memento class:</p>
<pre>
                public class ServiceMemento {
                        private String oneField;
                        private String anotherField;
                        private boolean serviceResult;

                        public ServiceMemento(final String oneField, final String anotherField, final boolean serviceResult) {
                                 this.oneField = oneField;
                                 this.anotherField = anotherField;
                                 this.serviceResult = serviceResult;
                        }

                        public String getOneField() {
                                 return oneField;
                        }

                        public String getAnotherField() {
                                 return anotherField;
                        }

                        public boolean getServiceResult() {
                                 return serviceResult;
                        }
                 }
</pre>
<p>Now we can refactor our original service class and replace its state with a Memento object:</p>
<pre>
                public class SpringManagedServiceClass {
                        public ServiceMemento anOperation(final String input) {
                                String oneField = someOperationOnInput(input);
                                String anotherField = somethingElseInvolvingInput(input);
                                boolean totalOperationSucceeded = operationOnTwoStrings(oneField, anotherField);
                                ServiceMemento result = new ServiceMemento(oneField, anotherField, totalOperationSucceeded);
                                return result;
                        }
                }
</pre>
<p>After this refactoring all the client code will of course have to be refactored as well. However, all the state access has been replaced by getter calls to the new Memento object, so that refactoring is not very difficult.</p>
<p>The most important thing is that using the Memento has allowed us transform our service class into a thread safe, stateless service class rather easily. The price for this was introducing a new class. This is not as clean a solution as we would have had if the service class had been designed to be thread safe from the very start. But it is an easy fix to implement so it allows us to avoid a lot of (potentially difficult) rework. Also, this Memento class will do nothing but hold the result of the work done by the service class. So at least instantiating and having multiple instances of this class will not be as expensive as having to create multiple instances of the service class.</p>
<h3>Summary</h3>
<p>This article discussed using the Memento pattern as a quick fix for a thread safety problem in service classes. It covered the problem of accidentally introducing concurrent access problems in singleton classes by introducing state into those classes and then showed how that state can be externalized into a Memento class to make the service class stateless once more.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2008%2F12%2F27%2Fusing-the-memento-pattern-to-solve-thread-safety-issues%2F&amp;title=Using%20the%20Memento%20pattern%20to%20solve%20thread%20safety%20issues&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2008/12/27/using-the-memento-pattern-to-solve-thread-safety-issues/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>The Life Cycle Pattern</title>
		<link>http://www.gridshore.nl/2008/08/09/the-life-cycle-pattern/</link>
		<comments>http://www.gridshore.nl/2008/08/09/the-life-cycle-pattern/#comments</comments>
		<pubDate>Sat, 09 Aug 2008 20:42:58 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[OOAD]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/2008/08/09/the-life-cycle-pattern/</guid>
		<description><![CDATA[<p>One of my current projects is responsible for delivering a library of functions that are used by several applications being built and maintained at our customer. One of those functions in particular is quite central to the operation of all the applications that use out library and is responsible for collecting, transforming and combining [...]]]></description>
			<content:encoded><![CDATA[<p>One of my current projects is responsible for delivering a library of functions that are used by several applications being built and maintained at our customer. One of those functions in particular is quite central to the operation of all the applications that use out library and is responsible for collecting, transforming and combining data from many different sources (essentially it is an orchestrating function). This function has a classical codebase, in the sense that the codebase started out being much smaller than it is now and with fewer tasks but has since grown. The library function is being developed continuously and will be expected to meet more and more requirements as more and more data must be collected and correlated. The problem, as you can imagine, is that the codebase is becoming unmanageable as more and more code goes into it. So we are faced with the question: how can we refactor the existing codebase to improve manageability?</p>
<p>As mentioned before the function in question is essentially an orchestrator, collecting data from several locations and combining these different data into one package. The collection of data is not random, however: some requests depend on the results of others, creating a natural partitioning of the function&#8217;s code into tasks with an internal ordering. Of course, this sounds like a classical orchestration setup and the first suggestion might be to use an orchestration tool like a BPEL engine. However, integrating a BPEL engine into the library seems like overkill given the current size and complexity of the function (and doesn&#8217;t fit well with the rest of the library). So instead my project is going to attempt an intermediate solution between the current pile-of-code architecture and a full orchestration tool: the Life Cycle Pattern.</p>
<p><span id="more-185"></span></p>
<h3>The setup</h3>
<p>Now, I have to admit to a little marketing here: there is (to the best of my knowledge) no official pattern called the &#8220;Life Cycle Pattern&#8221;. What I am talking about in fact is, in fact, a refactoring of our current pile-of-code collection of tasks (collecting data, transforming data, combining data and similar) into a collection of separate task objects, each of which is associated with one (or more) explicily identified steps within the overall library function.</p>
<p>Let me start from the other end to explain. I assume most people reading this article have at least heard of the <a href="http://maven.apache.org/">maven</a> build management tool. This tool (starting with version 2.0) divides the build process into a number of distinct steps or stages (<code>clean</code>, <code>generate-sources</code>, <code>compile</code>, <code>test</code>, <code>package</code>, <code>deploy</code>, etc.) which are together known as the build life cycle. A run of the maven executable runs through each of the stages in order. At each stage the executable delegates to zero or more modules (in the case of maven they&#8217;re called <em>mojo</em>s) each of which attempts to carry out a task (in maven-speak, attempts to <em>achieve a goal</em>). Which module is associated with which stage is determined by configuration.</p>
<h3>Patterns</h3>
<p>From a design pattern point of view, the &#8220;life cycle pattern&#8221; is actually a combination of two patterns: the <strong>Mediator</strong> pattern and the <strong>Command</strong> pattern. The first of these is a pattern that deals with having a central controller that delegates to a number of objects (each with their own responsibilities within the system) and controls their execution order to create a process. The second is a pattern that deals with turning system tasks into objects. The pattern actually exists to turn tasks into first-class citizens of a system so that they can be manipulated (e.g. reversed, as in an &#8220;Undo&#8221; functionality). In our case however we just want to make tasks manageable to associate them with steps. The structure we are aiming for is the following:</p>
<p><img src="http://www.gridshore.nl/wp-content/uploads/life-cycle-class-structure.jpg" alt="" align="center" /></p>
<p>In this design the <code>LifeCycleManager</code> is the class that is responsible for controlling the entire process with its different steps (in our case: the class that provides the library function). The operation that is called to kick of a process instance is referred to as the <code>publicOperation()</code> in the diagram above (in general this method will probably have one or more parameters). In the design above this method is the one that knows about the exact order in which the life cycle stages should be executed. As you can see, each stage is associated (in this design) with a list of <code>Task</code> objects. The <code>publicOperation()</code> method passes each of these lists to the <code>executeStageTasks()</code> method in the correct order. This method iterates over the <code>Task</code>s in the list it is passed and calls <code>executeTask()</code> on each <code>Task</code>. The execution of this setup is illustrated in the following sequence diagram:</p>
<p><img src="http://www.gridshore.nl/wp-content/uploads/life-cycle-execution.jpg" alt="" align="center" /></p>
<h3>Code example</h3>
<p>In the following section I will include a small code example of this &#8220;pattern&#8221;. The example is a <a href="http://www.springframework.org/">Springified</a> one, which means that the association of tasks to stages is done by dependency injection (in this case of the lists of <code>Task</code> objects into the <code>LifeCycleManager</code>). As illustrated in the design above, <code>Task</code> is just an interface that defines the <code>Task</code> hierarchy.</p>
<pre>
<pre class="brush: java; title: ; notranslate">
package nl.bentels.test; 

/**
 * This interface defines the Task type, the type of any task that can be
 * executed as part of a life cycle.
 *
 * @author ben.tels
 */
public interface Task
{
    /**
     * Method that executes a task.
     */
    void executeTask();
}
</pre>
</pre>
<p>The <code>LifeCycleManager</code> is also unsurprising:</p>
<pre>
<pre class="brush: java; title: ; notranslate">
package nl.bentels.test;

import java.util.List;

/**
 * This class is responsible for managing and executing the life cycle of
 * whatever it is that the life cycle blongs to.
 *
 * @author ben.tels
 */
public class LifeCycleManager
{
        /** Preparation tasks for stage 0. */
        private List        preStage0;
        /** Tasks for stage 0. */
        private List        stage0;
        /** Postprocessing tasks for stage 0. */
        private List        postStage0;

        /**
         * The operation that can be invoked by an external entity.
         */
        public void publicOperation()
        {
                executeStageTasks(preStage0);
                executeStageTasks(stage0);
                executeStageTasks(postStage0);
        }

        /**
         * Iterate over the tasks for a life cycle stage and execute them.
         *
         * @param tasks The tasks.
         */
        void executeStageTasks(final List tasks)
        {
                for (Task task : tasks)
                {
                        task.executeTask();
                }
        }

        /**
         * @param preStage0 the preStage0 to set
         */
        public void setPreStage0(final List preStage0)
        {
                this.preStage0 = preStage0;
        }

        /**
         * @param stage0 the stage0 to set
         */
        public void setStage0(final List stage0)
        {
                this.stage0 = stage0;
        }

        /**
         * @param postStage0 the postStage0 to set
         */
        public void setPostStage0(final List postStage0)
        {
                this.postStage0 = postStage0;
        }
}
</pre>
</pre>
<p>In order to make a full example, I&#8217;ll provide an example task implementation. This one does nothing but print a number:</p>
<pre>
<pre class="brush: java; title: ; notranslate">
/**
 *
 */
package nl.bentels.test;

/**
 * This class is an example task.
 *
 * @author ben.tels
 */
public class ExampleTask implements Task
{
        /** Number of the task. */
        private final int       taskNumber;

        /**
         * @param taskNumber
         */
        public ExampleTask(final int taskNumber)
        {
                this.taskNumber = taskNumber;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void executeTask()
        {
                System.out.println(taskNumber);
        }

}
</pre>
</pre>
<p>Finally, the Spring configuration:</p>
<pre class="brush: xml; title: ; notranslate">
&lt; ?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
        xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
        xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd&quot;&gt;
&lt;bean id=&quot;lifeCycleManager&quot;
                class=&quot;nl.bentels.test.LifeCycleManager&quot;&gt;
&lt;property name=&quot;preStage0&quot;&gt;
&lt;list&gt;
&lt;ref local=&quot;taskZero&quot; /&gt;
&lt;ref local=&quot;taskOne&quot; /&gt;
&lt;ref local=&quot;taskTwo&quot; /&gt;
&lt;/list&gt;
&lt;/property&gt;
&lt;property name=&quot;stage0&quot;&gt;
&lt;list&gt;
&lt;ref local=&quot;taskZero&quot; /&gt;
&lt;ref local=&quot;taskOne&quot; /&gt;
&lt;ref local=&quot;taskOne&quot; /&gt;
&lt;ref local=&quot;taskOne&quot; /&gt;
&lt;ref local=&quot;taskTwo&quot; /&gt;
&lt;ref local=&quot;taskOne&quot; /&gt;
&lt;ref local=&quot;taskTwo&quot; /&gt;
&lt;ref local=&quot;taskZero&quot; /&gt;
&lt;ref local=&quot;taskOne&quot; /&gt;
&lt;/list&gt;
&lt;/property&gt;
&lt;property name=&quot;postStage0&quot;&gt;
&lt;list&gt;
&lt;ref local=&quot;taskZero&quot; /&gt;
&lt;ref local=&quot;taskZero&quot; /&gt;
&lt;ref local=&quot;taskTwo&quot; /&gt;
&lt;/list&gt;
&lt;/property&gt;
&lt;/bean&gt;
&lt;bean id=&quot;taskZero&quot; class=&quot;nl.bentels.test.ExampleTask&quot;&gt;
&lt;constructor -arg value=&quot;0&quot; /&gt;
&lt;/bean&gt;
&lt;bean id=&quot;taskOne&quot; class=&quot;nl.bentels.test.ExampleTask&quot;&gt;
&lt;constructor -arg value=&quot;1&quot; /&gt;
&lt;/bean&gt;
&lt;bean id=&quot;taskTwo&quot; class=&quot;nl.bentels.test.ExampleTask&quot;&gt;
&lt;constructor -arg value=&quot;2&quot; /&gt;
&lt;/bean&gt;
&lt;/beans&gt;
</pre>
<h3>Moving on&#8230;.</h3>
<p>Like I said, this mechanism is not in place yet; the project is only about to start working on it. This means that there are still considerations open, such as how to arrange communication (or state sharing) between the tasks of the process. Of course I will report on the outcome (once it is known) in a sequel to this article&#8230;..</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2008%2F08%2F09%2Fthe-life-cycle-pattern%2F&amp;title=The%20Life%20Cycle%20Pattern&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2008/08/09/the-life-cycle-pattern/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

