I have an array of obje开发者_JAVA技巧cts. I want to pass it through a few steps that will modify each object in the array. These steps are independent of each other, and may not all be used in every case. Looking for a design pattern that might describe this behavior.
Thanks
You may be looking for the Visitor pattern.
I would use the Composite
and Command
patterns. Each one of your discrete operations would be a Command
instance, implemented in the execute
method that the pattern specifies. I would use Composite
because you want to do more than 1 command. In effect you would have a "composite command" that you apply to each element of the array.
It seems to me you are describing a pipeline.
One writeup on this pattern is http://stevenatkinson.wordpress.com/2009/03/02/pipeline-design-pattern/.
Performing an operation on each object of collection -> Iterator or Visitor
Encapsulating a series of operations -> Command
Visitor is a good choice for performing the operation.
Perhaps you should take a look at the "chain of responsibility" pattern. The goal of this pattern is very close (if not equals to) what you express. A chain of responisibility is composed by several commonds which can handle a request. In your case, the request is your array; each command can modify the array; after handling the array, each command calls the next command in the chain of responsiblity.
This pattern is very clearly explained in the "design pattern" by the GoF.
I see the visitor pattern more suited for this purpose even thought I personally don't like to use as it sometimes violates object encapsulation as it can access all the visited class implementation details.
All day, this is a Chain of Responsibility
精彩评论