Java's DAO definition of Factory Method [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I was reading today, again after many years, the article Core J2EE Patterns - Data Access Object and came across these two definitions of DAO implementations, the first one using Factory Method and the second one using Abstract Factory. Although the article claims the first example to be using factory method, I've started to think that it could just as well be defined as an abstract factory with a single concrete factory implementation.
Example Factory method:
Example Abstract Factory:
Going back to GoF, we can find arguments as to why it is an abstract factory:
Abstract factory creates a factory of related products, which would be the single concrete implementation of the first example.
Abstract factory is used, among other things, to create gui toolkit factories for different look and feels that would return different components to be worked on by other classes. These components are closely related. These would be the concrete dao factory implementation itself, which has methods for creating the individual products/daos.
I have also seen many discussions explaining the difference between inheritance (factory method) and composition (abstract factory) but I think that distinction is very ambiguous. In GoF we read that one of the two ways to use factory methods is to Connects parallel class hierarchies which means allowing classes other than the creator (class that implements the factory method) to call these factory methods.
If some class is calling a factory method from another class, using the interface exported by a creator, that is the same thing as calling a method from an abstract factory. Both examples use inheritance to benefit from the polymorfism and both are creating concrete produtcts, based on some abstract product interface. In essence, that means the same UML diagram could describe both patterns.
So in the end, I think it all comes down to whether I'm defining/describing DAOFactory as a creator with multiple factory operations, in the case of factory method or an abstract factory in the case of an abstract factory, which have the following definitions in GoF:
creator (Factory Method)
declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the
factory method that returns a default ConcreteProduct object.
may call the factory method to create a Product object.
abstract factory (Abstract Factory)
declares an interface for operations that create abstract product
objects
Reading further it even seems as if the author thinks Abstract Factory is an abstract method with a switch case selecting a factory method to be returned, as in a "factory of factories". This becomes clear with the following excerpts:
This strategy uses the Factory Method implementation in the factories
produced by the Abstract Factory. ... The Factory for Data Access
Objects Strategy uses the Factory Method pattern to implement the
concrete factories and its products (DAOs). For added flexibility, the
Abstract Factory pattern may be employed as discussed in the
strategies.
Abstract factories don't "produce" factories. Abstract factories are just interfaces describing operations that create products. The article goes on to show a sample code with an abstract method creating factory methods inside a switch case. Saying Abstract Factories produce something just sounds wrong to me.
So to decide whether the pattern is a factory method or an abstract factory, I need more than just the UML, but the requirement of the application to define what pattern best fits the description of the requirement. And so when I did that, it sounded like abstract factory fit better both examples from Oracle.
First because all DAOs are tightly coupled. I could share the same connection between them right from inside DaoFactory or even share a transaction. Second because there are multiple methods and I access them from a centralized object. Factory method in and of itself sounds more like a lone wolf in a creator class. When you have many of them you start stepping more into an abstract factory definition, sorta. Even though GoF has the example of the MazeGame defining many factory methods, MazeGame is never considered a factory. It either creates a maze using many factory methods or using an abstract factory.
I don't think calling the first example factory method just because there was only one implementation is justification enough nor is it calling the second example abstract factory just because it produces a factory method.
Have I missed something? Is my view of both patterns up to date or has it changed since GoF?

Related

Factory Method pattern vs ordinary abstract class implementation

I'm trying to understand the Factory Method pattern. I've managed to distinguish it from the Simple Factory, but now I don't get why it's actually called a "pattern". Please, look at my example below:
Class Diagram link
Sample java code for Messenger:
public String exchangeMessages(String messageToSend) {
Socket socket = getSocket();
socket.open();
socket.send(messageToSend);
String receivedMessage = socket.receive();
socket.close();
return receivedMessage;
}
And for Client:
public static void main(String[] args) {
Messenger messenger = new TCPMessenger("127.0.0.1", 4321);
String result = messenger.exchangeMessages("Hello!");
System.out.println(result);
}
If I understand correctly, everything makes sense because exchangeMessages method exists. We use the abstract factory method getSocket inside it and thanks to it we:
let subclasses decide which class to instantiate
But isn't it just an ordinary abstract class implementation? We take advantage of the code shared by both TCPMessenger and UDPMessenger - for me, this is not a pattern but a core feature of Object-Oriented Programming that everybody knows from the beggining of OOP language learning!
Moreover, I think that naming this creational is very confusing. We actually care about exchangeMessages method, so Client (part of the code that uses our "pattern") is not even aware of the Socket class which creation we're all about. It's more like a way to implement Messenger functionallity (which can be easily extended etc...) than a way to really create something.
Am I missing the point or is my example invalid? Please guys, let me know what do you thing about it.
Thanks in advance!
for me, this is not a pattern but a core feature of Object-Oriented
Programming
Most of patterns rely on core OOP features : programming by interface, overriding, polymorphism, and so for...
Moreover, I think that naming this creational is very confusing.
We actually care about exchangeMessages method, so Client (part of the
code that uses our "pattern") is not even aware of the Socket class
which creation we're all about. It's more like a way to implement
Messenger functionality (which can be easily extended etc...) than a
way to really create something.
It depends on the point of view you are taking.
For subclasses of the Messenger abstract class such as TcpManager, their parent class defines all but this factory method that they have to implement to specify what Socket getSocket(); should return.
So for subclasses point of view, talking about a creational pattern for Socket getSocket() makes sense.
For client classes of Messenger, things are indeed different.
Clients may even not need to use directly this method.
For these classes, the important thing is indeed having a way to manipulate indifferently any subclass of Messenger.
The Factory Method pattern is a simple pattern, but still a pattern nonetheless.
Your Client and its relationship to the Factory Method
The Gang of Four (GoF) definition of the Factory Method Pattern does not specifically mention a Client as a participant of the pattern itself. In reality the Client is most likely to use the Factory Method indirectly through some other operation.
In your case as the Client does not care about the Socket being used, but just the Messenger itself. However, the Messenger is dependent upon a Socket as it has some behavior that uses a Socket Object.
So whilst the Client itself does not care about the Socket, it does care about the Messenger which has a use dependency with Socket.
As the Socket itself is abstract it gives us a problem, as we don't want to replicate the same logic in exchangeMessages(String) multiple times for the different implementations of Socket (TCPSocket and UDPSocket), especially when we may want to add more Socket classes at a later date.
This is where the Factory Method pattern comes into play, as we can define all the generalized behavior for exchanging messages at an abstract level, but leave the creation of the actual Socket implementation (TCPSocket and UDPSocket) to subclasses of Messenger (TCPMessenger and UDPMessenger).
Discussion of alternatives to the Factory Method Pattern
You could just set the Socket as a field of Messenger, and inject it using a Strategy pattern approach or have a constructor that takes a Socket as a parameter. A drawback of this approach is that we'll have to maintain a reference to this Socket Object as a class field in anticipation of it's use.
However, with the Factory Method Pattern, the Socket will only be created in the method exchangeMessages() when needed and then discarded when the method terminates, which may be of some benefit. This comes at the cost of having to create one of the Socket Objects each time exchangeMessages() is called, which may not be ideal.
You could also pass the required Socket to the exchangeMessages() method to be used, but this may not as convenient for the user of the method in the long term.
If your Messenger subclasses also have some specific behaviors (new methods / overridden implementations) not applicable to all types of Messenger, then Factory Method is certainly the way to go, as we need to subclass Messenger anyway and it allows us to strictly enforce the type of Socket created by the Factory Method getSocket().
Perhaps others could contribute to the pros/cons of the Factory Method (specifically in Java as this the language tag for the question) and I can update this answer in due course.
Validity of your example
About whether your example is invalid or not. I think it helps to first fully understand the pattern and the important classes, operations and relationships in order to conform to the Factory Method pattern (as specified by the GoF).
The Factory Method Pattern allows you to define an Operation (or possibly several operations) in an abstract Creator class (in your case Messenger) which will use some Object (a Product [Socket]) without knowing the specific Product in advance and deferring its creation (hence the term creational pattern) to the Factory Method.
The Factory Method itself (getSocket()) is abstract in the Creator class and will be implemented by Concrete Creators (TCPMessenger, UDPMessenger) so polymorphism is used to achieve Object creation.
The Factory Method will return a Concrete Product (TCPSocket, UDPSocket) and have a return type applicable to all Concrete Product classes (Socket) used by the Operation in the abstract Creator class.
The Operation(s) (exchangeMessages(String)) that use the Factory Method will use the Concrete Product returned by the Factory Method by the interface Product which is applicable to all Concrete Product classes (Socket).
The result is that this pattern allows new Concrete Product classes to be added by implementing / subclassing the Product interface / class (or its subclasses...) and introducing a new Concrete Creator which returns the newly added Concrete Product from its Factory Method, preventing the need to re-write your Operation(s) that use this Product.
This means that we do not need to modify existing code when introducing new Concrete Products (Open/Closed Principle).
Generalized UML for the Factory Method Pattern
Some notes on the UML:
The factoryMethod() can be given a default implementation in Creator (i.e. a default Product to return), in turn allowing Creator to be non-abstract
The factoryMethod() could be public if desired, but this is superficial to the intention of the pattern since the factoryMethod() is primarily intended to be used by operation()
Product does not have to be abstract class, it could be an interface or it could be a concrete class
Validity of your example (continued)
In reference to the UML (and your example), the important parts of the pattern in less wordy terms are as follows:
There must exist
A Product interface (not neccesarily an interface in Java terms, could be a class or abstract class in reality) (in your case Socket)
ConcreteProduct classes that implement the Product interface (TCPSocket, UDPSocket)
An abstract Creator class (Messenger)
A Product factoryMethod() method that is defined in the Creator class (getSocket())
Note: The Creator and factoryMethod() are usually abstract, but the Creator can define a default Product removing this requirement.
operation() methods in the Creator class that use the ConcreteProduct returned by the factoryMethod() (exchangeMessages(String))
At least one ConcreteCreator class (TCPMessenger and UDPMessenger))
Such that
The ConcreteCreator classes implement the Product factoryMethod() to create and return a ConcreteProduct
The abstract Creator class uses the ConcreteProduct (returned by Product factoryMethod()) through the interface for all Product implementations
The last two points reflect that Creator has a use dependency with the Product interface, and the ConcreteCreator classes have a create dependency with its corresponding ConcreteProduct class.
Again, note that the Client class is not part of the pattern itself (as defined by the GoF).
So in conclusion, your example would appear check out as the Factory Method in regards to the requirements listed above if the TCPMessenger and UDPMessenger class implement the getSocket() method correctly (which I assume they actually do).

What exactly can we describe Factory Method of design pattern?

I am confused with the concept ? Is it just as simple as incorporating a static method to return the object instead of a constructor ? So that client doesn't need to change the code while we update the library or there is something more to it ?
The book Head First Design Patterns will be your definitive guide for Java. That is a great book. If you check out my answer to this Stack Overflow Question, you will be able to see my implementation for an ArbitraryPointFactory class in the Point Example code that uses the Factory Method pattern as well as how it differs from Abstract Factory pattern seen in the Point Factory class. Although this answer is presented with C# code samples, the design pattern language I am using to describe their usage, should warrant you an answer.
What you are thinking of in your question is not a design pattern at all. This static method that returns an object to encapsulate the instantiation, is known as the Simple Factory as seen in the Wiki page. The Factory Method pattern more or less abstracts the type being returned via an interface. This is typically done where the sole job of the factory method class is to control creation of the objects for one concrete class that implements the interface being returned. The Abstract Factory provides encapsulation for a group of related products. In my example I was showing for different types of points, however they could implement different interfaces and all use the same Abstract Factory.
The idea is that you are programming to interfaces, not implementations. True factories pull creation logic to a single location in your application and encapsulate the instantiation via interfaces.

"Factory Method Design Pattern" in context of Java interfaces?

I am a beginner in Java and the book that I use to learn it seems to have cryptic examples and sentences that completely confuse me.
I understand what interfaces are and how/where to apply the concept in real world. But what are Factory Methods? The term "factory method" is ambiguous (JavaScript has a different meaning for that) so I am providing the snippet that the book has, in order to make my question clear. Here is the code:
interface Service {
void method1();
void method2();
}
interface ServiceFactory {
Service getService();
}
The Service interface is just a normal interface. ServiceFactory interface looks like a normal interface but it is a "Factory Method". What's that? What does it solve and why I should use them?
A factory method is simply a method that encaspulate the creation of an object. Instead of using the new operator as you normally would for creating an instead of a Service, in your example, you're using the factory method on some object.
ServiceFactory sf = new ServiceFactoryImpl();
// factory method
Service s = sf.getService();
To better illustrate the role of the method, it could be called createService instead. Now the method encapsulates the details of the creation of a Service, you can provide many flavors of the methods (by overloading), you can have it return different subclasses depending on the context, or parameters passed to the factory method.
A "factory method" is a method that constructs an object.
More specifically, the term usually refers to a static method that returns an instance of its declaring class (either a direct instance, or an instance of a subclass). In my experience, there are a few cases where that's particularly commonly done:
If you need to have multiple different constructors, using factory methods lets you give them appropriate names (whereas calls to different constructors can only be distinguished by the argument-types, which aren't always obvious at a glance).
If you need to have a few different implementations of a single abstract class that serves as the entry-point, the factory method can instantiate the appropriate subtype.
If you need any sort of caching logic or shared instances, the factory method can handle that, returning an already-existing instance if appropriate.
If you need to do some work with side effects, a factory method can be named in such a way that it's more clear what those side effects are.
So, your example doesn't really involve a "factory method" IMHO, but you can cheat a bit and describe getService() as one. (Rather, I would just describe ServiceFactory as a "factory" at leave it at that.) The benefits of ServiceFactory.getService() are the same as those of a factory method, plus the usual benefits of having an instance instead of a static method.

If I use abstract class instead of interface while implementing factory pattern. Would it still be a factory pattern?

For example : http://www.tutorialspoint.com/design_pattern/factory_pattern.htm
If I change interface shape on abstract class Shape, make concrete classes to extend Shape and Make the Shape factory return Shape abstract class typed objects. Is it still going to be a factory pattern ?
I would go with yes.
Lets look at definition of Factory method pattern:
the factory method pattern is a creational pattern which uses factory methods to deal with the problem of creating objects without specifying the exact class of object that will be created
The motivation behind this pattern is to separate object creation from the client using the object. Client should provide specification to factory but details how the object is built are abstracted away by the factory.
If this is an interface or abstract class is an implementation detail specific to situation, as long as your implementation of the factory lets you achieve the motivation behind pattern.
Consider using abstract classes if any of these statements apply to your situation:
You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
Consider using interfaces if any of these statements apply to your situation:
You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
You want to take advantage of multiple inheritance of type.
In some implementations it might even make more sense to use abstract class rather then interface for the Products created by the factory. If there is shared set of features/behavior between all products then it does make sense to put these into base abstract class. This could apply even if products are built from different factories.
It boils down to: do you wish to and does it make sense to introduce coupling
between products or not?
In the end, client will get same result - Product built based upon specification, with details of construction abstracted away.
When it comes to these kind of differences, the answer can always be both yes and no. Design patterns are not any kind of precise specification, they are more like a set of best and recommended practices and their implementation varies from case to case.
In my opinion the answer is no, technically this would not be a factory pattern. And it does not have to be, as long as it solves your use case and makes the code readable and maintainable (trying to literally adhere to design patterns often leads to misusing them and to over-architecturing).
If we look at the Abstract Factory Pattern (right below the Factory Pattern in the linked page), we'll see that it is a factory for creating factories. Now suppose that we have two Shape factories that can be created by the AbstractFactory: ShapeFactory2D and ShapeFactory3D, both producing Shape objects.
If Shape were abstract class, then you would force both 2D and 3D objects to inherit the same implementation, although it might make no sense (they could be implemented in totally different ways).
So, technically, in order for this to really be a factory pattern, there must exist no assumptions about the implementation details, meaning abstract classes containing partial implementation should not be used at the factory interface level.
Of course you can have Abstract2DShape and Abstract3DShape abstract classes implementing Shape; the point is that you are able to create and use Shape without being aware whether it is a 2D or a 3D shape.

Factory Pattern vs FactoryMethod Pattern

Could anybody please let me know why the FactoryMethod design pattern is introduced ? As my question is the same can be achivied using a Factory Pattern itself ?
For example if i see the difference between Factory Pattern and FactoryMethod Pattern the the Factory Pattern returns the Concrete IMplementation where as the FactoryMethod Pattern returns the Factory Object as its return type ??
Please tell me why FactoryMethod is introduced ??
In a nutshell:
Factory Method is a design pattern that "hides" the instantiation of concrete types from the rest of your code thereby providing loose coupling.
Abstract Factory is a design pattern that is introduced to provide different kind of factories that are responsible to create a specific group of concrete types. So you can switch between abstract factories and as a result get eventually different concrete instances of objects in your code.
So Abstract Factory is a step up i.e. a generization of Factory Method. In simple projects the latter is adequate. In projects with complicated hierarchies the Abstract Factory is needed.
As you can read on the wiki 'Abstract factory pattern, a pattern often implemented using factory methods'.
See this picture http://upload.wikimedia.org/wikipedia/commons/a/a7/Abstract_factory.svg
Design patterns are often/ always connected with each other and this way they show us the patterns concepts.
Regards Lukasz.
AbstractFactory pattern is another level of abstractization. The user is not aware of the type of object that he will get and it's not interested in that matter. The AbstractFactory decides which method it's used to create the concrete object that the user will recieve.
In method factory, the user decides which method to use for the object creation and knows what he gets. But this doesn't always concern him.
If I request a button in Method Factory, I need to know if I want a LinuxButton or a WindowsButton or a OSXButton. In AbstractFactory, I request a button, I recieve a button... and the AbstractFactory will decide how the button is created, knowing our OS.
As per understanding about Abstract factory is it Abstract Factory pattern is used when you have factories that can create a family of objects. while there is abstraction of Factory class.
while in case of factory method have abstraction over factory class and it produces single set of product objects.

Categories

Resources