I have a simple design problem - I am looking for the best pattern to implement a simple functionality. Let's say, I am going to create an xml message in java. This message consists of many fields in different logic groups.
So, the first idea - create a class to set all fields. I can do it one method (which will be really long...) or split the method into multiple smaller (for each of the logical groups). However, I don't think it is a good approach, because the class will be really long and difficult to mantain.
The second idea is to create a functional interface and some implementations for different groups, for instance GroupXxxSetter, GroupYyySetter, etc. I can create and keep all instances in a list or a set and call the method defined inside the interface for each object stored inside the collection. It seems to be very similar to the 'Chain of responsibility' pattern. However, the idea of this pattern is different, so I am not sure if it is a good idea to use this pattern in my case.
Should I use the 'chain of responsibility' pattern here? Or, maybe there is something better?
Thanks in advance.
Should I use the 'chain of responsibility' pattern here?
Clearly, no. You don't have the notion of candidate responsible to respond to a request. All elements will do a processing.
Or, maybe there is something better?
You have multiple possibilities.
Your context is not totally set. So it is hard to propose one rather than another.
I may propose you a implementation with the Builder pattern (Java Effective reference and not GOF).
For each logic group, you could have a specific class.
You would also have a composite class that is composed of logic group instances.
Instead of providing a public constructor or setters that prevent immutability and that can make rules validation cumbersome, you could use the Builder pattern for each one logic group class and in the composite class, you could use the same kind of Builder pattern where you will build the final message from the previously created logic group instances.
You could so create the instances in this way :
OneLogicGroup oneLogicGroup = OneLogicGroup.builder().fieldXXX(...).fieldYYY(...).build();
AnotherLogicGroup anotherLogicGroup = AnotherLogicGroup .builder().fieldXXX(...).fieldYYY(...).build();
MyMessage myMessage = MyMessage.builder().oneLogicGroup(oneLogicGroup).anotherLogicGroup(anotherLogicGroup).build().
I can create and keep all instances in a list or a set and call the
method defined inside the interface for each object stored inside the
collection.
It seems referring to a structural concern.
It is not directly related to the creation of the object. It is much related to how to share the created objects.
The flyweight pattern addresses this need and may be used conjointly with the presented builder Pattern.
Related
I have troubles understanding these two design patterns.
Can you please give me contextual information or an example so I can get a clear idea and be able to map the difference between the two of them.
Thanks.
The visitor pattern allows you to add functionality to classes without altering them. You keep in a single place/class the same kind of behaviour for different type of objects while (potentially) having different implementation for each type. You can extend or change the behaviour for multiple types of objects while working on a single class (the visitor). Also useful when you want to extend behaviour of classes that are not under your control, without wrapping or extending them.
In visitor the driver of the behaviour is based on behalf of which type of object the operation is performed.
The interpreter pattern can be used on domain problems which can be expressed in simple language/sentences. Then the problems can be solved by interpreting these sentences. So we get an input, we can understand (interpret) it and then implement certain behaviour based on the interpretation/categorization of the input.
In interpreter the driver of the behaviour is based on what the input is, the interpretation/categorization of the input.
In the factory design pattern, we write logic for deciding which class to be loaded in the factory class. Suppose I have a choice of 100 classes, so for all 100 do I need to write conditions in factory class? Or there is some other way?
In this case I'd create an annotation which describes the condition each class must meet to be created. Then I'd use reflection to discover all possible products and store a specific subfactory in a HashMap with the condition used as key.
Its not very helpful, but I would say it totally depends on your use-case. There could be some generic logic on which a particular class could be picked up.
On a side note: I would advice you to rethink on the design if such situation occurs and not fix a problem which could be avoided to begin with. Use of reflection could help if your logic is around class name but again it could be an overkill for the problem.
I need to create an email-notification service (as a part of a bigger project).
It will be used to send several types of notification messages which are based on html-templates.
I can design it in two ways:
The first way is based on the builder pattern. It's universal (as I think) and can handle all necessary cases. But it's not very convenient for those who will use it. The typical usage would look like this:
messageBuilder
.put("name", "John Doe")
.put("company", companyObj)
.processPattern(pattern)
.send(addresses, subject);
The second way is to implement all cases explicitly. It means that usage code (shown below) will be as simple as possible but we'll have to modify API (add new methods) every time when we need to handle any new case.
messageSender.sendPersonExpenceNotification(addresses, "John Doe", company);
Which one is better? Why? (the language is Java if it matters)
Thanks!
I think the answer is to use both. I would suggest using the more generic approach (the message builder) in the API and then providing client-side convenience functions/classes that are simple to use for specific tasks. This way the API doesn't have to update when you add new cases but the client can still use the most direct call for what they're trying to do.
Effective Java 2nd Edition, Item 2: Consider a builder when faced with many constructor parameters.
The builder pattern is more readable, especially as you have potentially many more parameters. That said, it's usually more common to have specific setName, setCompany, etc methods for a builder. That way you can also enforce type-safety, e.g. setSomeBoolean(boolean), setSomeInt(int), etc.
A builder pattern also allows you to set default values to some parameters, and user can conveniently override the default on some parameters. Providing methods to simulate this involves writing many overloads, which exacerbate the problem further.
Related questions
When would you use the Builder Pattern?
Nowadays, the most favored design pattern relies upon "fluent" builder. This way, you gain the genericity of the builder, with an understandable interface.
Implementing it is rather mundane, considering it's only a matter of well choosing your method names.
Good real world examples are all the FEST* libraries.
I have several different classes coming from external sources (unmodifiable) that represent the same concept. For example Address. I have com.namespace1.Address (with fields houseNum, street, city), com.namespace2.Address (with fields h, s, c), namespace3.com.CoolAddress (with fields house_num, street, city).
The problem is that certain web services I use require certain Address object types so I am required to create a com.namespace1.Address given a namespace3.com.CoolAddress. The fields are easy enough to map but I'm looking for a pattern on how to do it.
From my point of view, an instance object AddressConverter doesn't make sense as there is no state (only behaviour) and when classes only have behaviour it boils down to static methods in a utility class. In the long term, anytime I need to map new objects to one another, I have one place to add/modify/remove methods. How it's done might change, but I know where the code sits (in once place) and can change the mapping when I need to.
Thoughts?
I think what you're looking for is a factory class. The factory pattern is used when you need to be able to instantiate one of several related classes, to be determined by the factory, not the developer.
See http://en.wikipedia.org/wiki/Factory_method_pattern
You're right to try to keep all this business logic in one place instead of doing ClassOne.toClassTwo(), ClassOne.toClassThree(),...
The most flexible way I can think of implementing this (but not the easiest by far) would be to have the factory start with a simple class with only basic common methods in it, and add handlers to a Hashtable or other container. That way you don't need concrete implementations of every possible combinations of features.
Of course it would be quicker to have a concrete implementation for each possible address variant, but there would be a fair amount of duplicated code, and it would be a little harder to add new address class types.
Since you can't modify the classes themselves, I'd suggest an implementation of the Adapter pattern for each direction. As you said, the adapter methods themselves can be static, but you can group both directions inside a single class so that the logic is all in one place.
At the end of the day you're going to be performing the same task no matter what you call it, or where you put the code. I'd suggest that both directions live in the same file, as they'll often both need updating when either direction changes.
If you are always converting to the same Class I would keep it simple and put all you conversion code in that Class and not worry about factories and the like, especially if you are only dealing with a couple of different classes. Why does there always have to be a complicated pattern for these things?!
public class A {
...
public static A convertB(B b) {
...
}
}
Are the classes you need to output final? If not, you could subclass them to create proper Adapters. Otherwise I'd go with dj_segfault's suggestion of a Factory with a table of handlers.
Or, wait -- is it just a web service you need to talk to? If so, there should be no reason your implementations of its datatypes can't be Adapters wrapping the input datatypes, or some intermediate object of your own.
I just found myself creating a class called "InstructionBuilderFactoryMapFactory". That's 4 "pattern suffixes" on one class. It immediately reminded me of this:
http://www.jroller.com/landers/entry/the_design_pattern_facade_pattern
Is this a design smell? Should I impose a limit on this number?
I know some programmers have similar rules for other things (e.g. no more than N levels of pointer indirection in C.)
All the classes seem necessary to me. I have a (fixed) map from strings to factories - something I do all the time. The list is getting long and I want to move it out of the constructor of the class that uses the builders (that are created by the factories that are obtained from the map...) And as usual I'm avoiding Singletons.
A good tip is: Your class public API (and that includes it's name) should reveal intention, not implementation. I (as a client) don't care whether you implemented the builder pattern or the factory pattern.
Not only the class name looks bad, it also tells nothing about what it does. It's name is based on its implementation and internal structure.
I rarely use a pattern name in a class, with the exception of (sometimes) Factories.
Edit:
Found an interesting article about naming on Coding Horror, please check it out!
I see it as a design smell - it will make me think if all those levels of abstraction are pulling enough weight.
I can't see why you wanted to name a class 'InstructionBuilderFactoryMapFactory'? Are there other kinds of factories - something that doesn't create an InstructionBuilderFactoryMap? Or are there any other kinds of InstructionBuildersFactories that it needs to be mapped?
These are the questions that you should be thinking about when you start creating classes like these. It is possible to just aggregate all those different factory factories to just a single one and then provide separate methods for creating factories. It is also possible to just put those factory-factory in a different package and give them a more succinct name. Think of alternative ways of doing this.
Lots of patterns in a class name is most definitely a smell, but a smell isn't a definite indicator. It's a signal to "stop for a minute and rethink the design". A lot of times when you sit back and think a clearer solution becomes apparent. Sometimes due to the constraints at hand (technical/time/man power/etc) means that the smell should be ignored for now.
As for the specific example, I don't think suggestions from the peanut gallery are a good idea without more context.
I've been thinking the same thing. In my case, the abundance of factories is caused by "build for testability". For example, I have a constructor like this:
ParserBuilderFactoryImpl(ParserFactory psF) {
...
}
Here I have a parser - the ultimate class that I need.
The parser is built by calling methods on a builder.
The builders (new one for each parser that needs to be built) are obtained from builder factory.
Now, what the h..l is ParserFactory? Ah, I am glad you asked! In order to test the parser builder implementation, I need to call its method and then see what sort of parser got created. The only way to do it w/o breaking the incapsulation of the particular parser class that the builder is creating is to put an interception point right before the parser is created, to see what goes into its constructor. Hence ParserFactory. It's just a way for me to observe in a unit test what gets passed to the constructor of a parser.
I am not quite sure how to solve this, but I have a feeling that we'd be better off passing around classes rather than factories, and Java would do better if it could have proper class methods rather than static members.