http://www.developer.com/

Back to article

Build and Command Objects-Using Design Patterns


June 15, 2006

"A software design pattern, the Builder pattern is used to enable the creation of a variety of complex objects from one source object. The source object may consist of a variety of parts that contribute individually to the creation of each complex object through a set of common interface calls of the Abstract Builder class."

"In computer programming, Command Pattern is a Design Pattern: a standard solution to a common problem in software design. The Command Pattern encapsulates invocation and allows code that causes actions to be initiated to be separated from code that performs those actions."

Wikipedia online

In the software development world, many projects involve complex architectures, multi-tier frameworks. and extensive planning. Yet, simple design patterns are some how overlooked. The design patterns that simplify overall flow of the information in the project or emphasize logic reuse will achieve wonders if implemented correctly. Many projects are designed to include enterprise scale patterns such as Model View Controller (MVC) or Data Access Object (DAO), but simple patterns such as Singleton or Visitor may never even be considered.

It is as if project architects think that some "buzzword" patterns are enterprise material and others are not worth considering. The benefit of the less known, but equally useful, patterns is sometimes greater than from the more popular ones.

I am not saying that all design patterns should be used in a project, or even considered. All patterns have a specific problem space that they address. However, I do believe that careful planning of the design phase of an enterprise-scale application should include several fine-grained patterns that deal with logic, data, or its flow.

This article will deal with two often overlooked or underused design patterns: one creational Builder pattern and one a behavioral Command pattern. I will explore their application in the software architecture process, describe the purpose of these patterns, and show how they can be used in real-world Java projects.

Builder Pattern

Builder is one of the "easier-to-understand-and-difficult-to-find-use-for" patterns. But, with some practice, even novice architects can begin to reuse this pattern. It is a creational pattern; that places it in the same category as a "factory" or "singleton," but its intent as stated in the original "gang of four" book is to "separate the construction of a complex object from its representation so that the same construction process can create different representations."

What this really means is that this pattern is very useful at daisy-chaining some actions to take one object and transform it into another, to change its properties or appearance. Applications for this little concept are infinite, from parsers of data to modification of Swing GUI objects models.

Imagine a situation, in an enterprise application, where data is coming in real time and needs to be processed, formatted, and displayed. A stream of market data, for example, would have ticket symbols, "bid" and "ask" prices, and volume information. Every part of the incoming data represents a different number or character value and needs to be parsed or formatted accordingly. Monetary data needs a "$" in front and ticker symbol needs to be uppercased, for instance.

Builder pattern takes initial data (or object) and transforms it by a set of methods defined in a public interface. The concrete classes that implement "builder" interface are required to accept the same type of object and perform the same API call.

The specific business rules that those concrete builders follow must be implemented in the public methods exposed by the interface.

Here is a sample interface that has one method "build" and takes an Object type and returns an Object type. In this example, I'm using a very generic Object and assuming that a Sting type will be passed in, but any types could be used.

public interface Builder {
   Object build(Object o);
}

A concrete class would have its logic implemented in the "build" method it overwrites:

public class SimpleBuilder implements Builder {
   public Object build(Object o) {
      if (o instanceof String){
         o = ((String)o).toUpperCase();
      }
      return o;
   }
}

Therefore, any feasible operation can be done on the object of the correct type. As I mentioned, the powerful feature of this pattern is that several concrete builders can be daisy chained together. A complex concrete builder can take several concrete builder objects, put them in a list, and traverse through them. Each Builder in the list will execute a "build" action on the passed-in object.

public class ComplexBuilder implements Builder {
   private ArrayList builders = new ArrayList();
   public void add(Builder b) {
         this.builders.add(b);
      }
      public Object build(Object o) {
         Object tempObj = null;
      for (int i = 0; i < this.builders.size(); i++) {
         Builder builder = (Builder) builders.get(i);
         o = builder.build(o);
      }
      return o;
   }
}

Please see the source code for the executable example.

Here is a UML representation of this pattern.

Even though the concept is simple, the places to apply this pattern could be difficult to find when designing an enterprise application. To see where to use this pattern, architects need to look for instances in the design where data or objects are created or modified. Builder can be applied where something is morphed from smaller parts into a final product. Most text formatting for onscreen presentation that involves several steps, such as concatenations, lower or upper case conversion, numeric formatting, and so forth, can benefit from this pattern. See the included source for an example.

Other uses can be more complex changes to an object's properties. Imagine you have a Value Object that is populated with database values and is passed back to the client level (JSP or any other technology) via an HTTP response. Based on some values, an appropriate action will be taken before the client sees the server response. For example, if some data is not correct, the client may see an error page and not the page with the values. Value Object is a holder of data and its concepts can be considered another design pattern, but this topic is not in the scope of this article.

Builder can be used to check data in the Value Object and modify it, before it reaches the client tier. It can set flags, add or format fields in the Value Object, and then pass it onward.

Another application of this pattern could be even more complex, where actual new objects are created based in the interface. For instance, the above "build" method returns a generic "Object," but it could return a specific interface and any class that implements it. Therefore, based on the business rules, which a concrete builder implements, it can take one object and return a completely different one.

The build possibilities are endless for "Builder" pattern.

Command Pattern

Command is a behavioral pattern; that puts it in the category of Observer design pattern. Observer pattern is beyond the scope of this article, but anyone who used modern listeners should be familiar with its concept. Command deals with behavior and does not create new types of objects like the Builder does. For example, this pattern is often used in GUIs where a menu item object can be connected with different Commands in such a way that the menu item object does not need to know any details of how action is performed.

Its intent is to "encapsulate a request as an object, thereby letting [developers] parameterize clients with different requests, and supports undoable operations."

Here is an UML diagram of this pattern:

Look at some code to make this pattern clear:

The Receiver object is the one that performs action on the behalf of the command and it can be any action dictated by the business logic even a Builder action, via a public interface.

class Receiver
{
   public void action()
   {
      System.out.println("Performing action or build operation");
   }
}

Instead of an interface, an abstract class can be used to define the command.

public abstract class Command
{
   protected Receiver receiver;
   public Command( Receiver receiver )
   {
      this.receiver = receiver;
   }
   public abstract void execute();
}

The concrete Command class, therefore, need not to have Receiver field defined.

public class ConcreteCommand extends Command {
   ConcreteCommand(Receiver receiver) {
      super(receiver);
   }
   public void execute() {
      receiver.action();
   }
}

Please see the included source for a complete implementation.

In an enterprise application, "receivers" can be supplied on the fly to the "command" objects, and "commands" can be attached to visual components that don't need to know how the action is done. For example, in the Swing GUI, a different instance of the same concrete command object can be attached to different buttons or drop-down menu Items and perform different actions based on the command Receiver's implementations.

As I mentioned, Receiver can be combined with the Builder pattern. In other words, an action method could also be a build method. This way, when there is a request for a command to be done, the same request also can perform a build action.

By placing "Builder" object as a Receiver of the "Command," truly powerful results can be achieved. Programmers can build and command objects, at the same time enforcing code reuse, strict interface following and logic flow, in your design.

Conclusion

In this article, I have covered the basis of creational "Builder" and behavioral "Command" patterns, and have shown how to use them in an overall architecture design. I also have shown how to look for places to apply them. I firmly believe that architects need not only know these patterns, but also have a strong understanding on where these patterns fit on the overall design; that sometimes can be harder than just knowing them.

Download the Code

You can download the source code used in this article here.

References

Books

Design Patterns by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides
Publisher: Addison-Wesley Professional; 1st edition (January 15, 1995)
ISBN: 0201633612

Head First Design Patterns
by Elisabeth Freeman, Eric Freeman, Bert Bates, and Kathy Sierra
Publisher: O'Reilly; 1st edition (October 26, 2004)
ISBN: 0596007124

Online

http://www.dofactory.com/Patterns

Wikipedia online: http://en.wikipedia.org/wiki/

About the Author

Vlad Kofman is a Senior System Architect working on projects under government defense contracts. He has also been involved with enterprise-level projects for major Wall Street firms and the U.S. government. His main interests are object-oriented programming methodologies and design patterns.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date