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.
for a project in the semantic-web context, I am looking for a elegant way to implement generic beans. The beans should represent the individuals stored in the underlying ontology (rdf/owl), whose structure is modifiable. So, the structure of the beans are known only at runtime. There is no underlying static database structure on which the beans can base upon.
I've tried java reflection, but it is not possible to add methods to a java bean this way. The alternative could be to implement an appropriate databinding mechanism.
Any clues? Thanks in advance.
You could try Empire -- it's an implementation of a fair portion of JPA for RDF & SPARQL. It's not quite what you want, doing something that dynamic is likely to have to be custom; as another person said, you're better off w/ something like groovy. But if you do know a schema ahead of time, it could make your life easier.
It does come w/ some utilities for generating beans, though incomplete, from a SPARQL endpoint. You could probably use that + reflection, and maybe get the kind of system you're talking about.
Well, you may not add a Java field or method to a class or object at run-time. But you may store a java.util.Map instead of a bean.
http://download.oracle.com/javase/6/docs/api/java/util/Map.html
What does the term Plain Old Java Object (POJO) mean? I couldn't find anything explanatory enough.
POJO's Wikipedia page says that POJO is an ordinary Java Object and not a special object. Now, what makes or what doesn't make and object special in Java?
The above page also says that a POJO should not have to extend prespecified classes, implement prespecified Interfaces or contain prespecified Annotations. Does that also mean that POJOs are not allowed to implement interfaces like Serializable, Comparable or classes like Applets or any other user-written Class/Interfaces?
Also, does the above policy (no extending, no implementing) means that we are not allowed to use any external libraries?
Where exactly are POJOs used?
EDIT: To be more specific, am I allowed to extend/implement classes/interfaces that are part of the Java or any external libraries?
Plain Old Java Object The name is used to emphasize that a given object is an ordinary Java Object, not a special object such as those defined by the EJB 2 framework.
class A {}
class B extends/implements C {}
Note: B is non POJO when C is kind of distributed framework class or ifc.
e.g. javax.servlet.http.HttpServlet, javax.ejb.EntityBean or J2EE extn
and not serializable/comparable. Since serializable/comparable are valid for POJO.
Here A is simple object which is independent.
B is a Special obj since B is extending/implementing C. So B object gets some more meaning from C and B is restrictive to follow the rules from C. and B is tightly coupled with distributed framework. Hence B object is not POJO from its definition.
Code using class A object reference does not have to know anything about the type of it, and It can be used with many frameworks.
So a POJO should not have to 1) extend prespecified classes and 2) Implement prespecified interfaces.
JavaBean is a example of POJO that is serializable, has a no-argument constructor, and allows access to properties using getter and setter methods that follow a simple naming convention.
POJO purely focuses on business logic and has no dependencies on (enterprise) frameworks.
It means it has the code for business logic but how this instance is created, Which service(EJB..) this object belongs to and what are its special characteristics( Stateful/Stateless) it has will be decided by the frameworks by using external xml file.
Example 1: JAXB is the service to represent java object as XML; These java objects are simple and come up with default constructor getters and setters.
Example 2: Hibernate where simple java class will be used to represent a Table. columns will be its instances.
Example 3: REST services. In REST services we will have Service Layer and Dao Layer to perform some operations over DB. So Dao will have vendor specific queries and operations. Service Layer will be responsible to call Which DAO layer to perform DB operations. Create or Update API(methods) of DAO will be take POJOs as arguments, and update that POJOs and insert/update in to DB. These POJOs (Java class) will have only states(instance variables) of each column and its getters and setters.
In practice, some people find annotations elegant, while they see XML as verbose, ugly and hard to maintain, yet others find annotations pollute the POJO model.
Thus, as an alternative to XML, many frameworks (e.g. Spring, EJB and JPA) allow annotations to be used instead or in addition to XML:
Advantages:
Decoupling the application code from the infrastructure frameworks is one of the many benefits of using POJOs. Using POJOs future proofs your application's business logic by decoupling it from volatile, constantly evolving infrastructure frameworks. Upgrading to a new version or switching to a different framework becomes easier and less risky. POJOs also make testing easier, which simplifies and accelerates development. Your business logic will be clearer and simpler because it won't be tangled with the infrastructure code
References : wiki source2
According to Martin Fowler, he and some others came up with it as a way to describe something which was a standard class as opposed to an EJB etc.
Usage of the term implies what it's supposed to tell you. If, for example, a dependency injection framework tells you that you can inject a POJO into any other POJO they want to say that you do not have to do anything special: there is no need to obey any contracts with your object, implement any interfaces or extend special classes. You can just use whatever you've already got.
UPDATE To give another example: while Hibernate can map any POJO (any object you created) to SQL tables, in Core Data (Objective C on the iPhone) your objects have to extend NSManagedObject in order for the system to be able to persist them to a database. In that sense, Core Data cannot work with any POJO (or rather POOCO=PlainOldObjectiveCObject) while Hibernate can. (I might not by 100% correct re Core Data since I just started picking it up. Any hints / corrections are welcome :-) ).
Plain Old Java Object :)
Well, you make it sound like those are all terrible restrictions.
In the usual context where POJO is/are used, it's more like a benefit:
It means that whatever library/API you're working with is perfectly willing to work with Java objects that haven't been doctored or manhandled in any way, i.e. you don't have to do anything special to get them to work.
For example, the XStream XML processor will (I think) happily serialize Java classes that don't implement the Serializable interface. That's a plus! Many products that work with data objects used to force you to implement SomeProprietaryDataObject or even extend an AbstractProprietaryDataObject class. Many libraries will expect bean behavior, i.e. getters and setters.
Usually, whatever works with POJOs will also work with not-so-PO-JO's. So XStream will of course also serialize Serializable classes.
POJO is a Plain Old Java Object - as compared to something needing Enterprise Edition's (J2EE) stuff (beans etc...).
POJO is not really a hard-and-fast definition, and more of a hand-wavy way of describing "normal" non-enterprise Java Objects. Whether using an external library or framework makes an object POJO or not is kind of in the eye of the beholder, largely depending on WHAT library/framework, although I'd venture to guess that a framework would make something less of a POJO
The whole point of a POJO is simplicity and you appear to be assuming its something more complicated than it appears.
If a library supports a POJO, it implies an object of any class is acceptible. It doesn't mean the POJO cannot have annotations/interface or that they won't be used if they are there, but it is not a requirement.
IMHO The wiki-page is fairly clear. It doesn't say a POJO cannot have annotations/interfaces.
What does the term Plain Old Java Object (POJO) mean?
POJO was coined by Martin Fowler, Rebecca Parsons and Josh Mackenzie when they were preparing for a talk at a conference in September 2000. Martin Fowler in Patterns of Enterprise Application Architecture explains how to implement a Domain Model pattern in Java. After enumerating some of disadvantages of using EJB Entity Beans:
There's always a lot of heat generated when people talk about
developing a Domain Model in J2EE. Many of the teaching materials and
introductory J2EE books suggest that you use entity beans to develop a
domain model, but there are some serious problems with this approach,
at least with the current (2.0) specification.
Entity beans are most useful when you use Container Managed
Persistence (CMP)...
Entity beans can't be re-entrant. That is, if you call out from one
entity bean into another object, that other object (or any object it
calls) can't call back into the first entity bean...
...If you have remote objects with fine-grained interfaces you get
terrible performance...
To run with entity beans you need a container and a database
connected. This will increase build times and also increase the time
to do test runs since the tests have to execute against a database.
Entity beans are also tricky to debug.
As an alternative, he proposed to use Regular Java Objects for Domain Model implementation:
The alternative is to use normal Java objects, although this often
causes a surprised reaction—it's amazing how many people think that
you can't run regular Java objects in an EJB container. I've come to
the conclusion that people forget about regular Java objects because
they haven't got a fancy name. That's why, while preparing for a talk
in 2000, Rebecca Parsons, Josh Mackenzie, and I gave them one: POJOs
(plain old Java objects). A POJO domain model is easy to put together,
is quick to build, can run and test outside an EJB container, and is
independent of EJB (maybe that's why EJB vendors don't encourage you
to use them).
There is an abundance of posts that are half correct and half incorrect. The best example of the correct interpretation is given by Rex M in their answer here.
[POJO are classes] that doesn't require any significant "guts" to make
it work. The idea is in contrast with very dependent objects that have
a hard time being (or can't be) instantiated and manipulated on their
own - they require other services, drivers, provider instances, etc.
to also be present.
Unfortunately, these very same answers often come along with the misunderstanding that they are somehow simple or often have a simple structure. This is not necessarily true and the confusion seems to stem from the fact that in the Java (POJO) and C# world (POCO) business logic is relatively easily modeled especially in the web application world.
POJO's can have multiple levels of inheritance, generic types, abstractions, etc. It just so happens that this isn't required in the majority of web applications as business logic doesn't necessitate it - alot of the effort goes into databases, queries, data transfer objects and repositories.
As soon as you step out of line with simple web apps, your POJO's start looking a lot more complex. E.g. Make a web app that assigns taxi's to user schedules. To do this, you need a graph coloring algorithm. To color the graphs, you need a graph object. Each node in the graph is a schedule object. Now what if we want to make it generic so that coloring the graph can be done not only with schedules but other things as well. We can make it generic, abstract and add levels of inheritance - almost to the point of making it a mini library.
At this point though, no matter its complexity, its still a POJO because it doesn't rely on the guts of other frameworks.
A Plain Old Java Object (POJO) that contains all of the business logic for your extension.
Exp. Pojo which contains a single method
public class Extension {
public static void logInfo(String message) {
System.out.println(message);
}
}
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 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.