A singleton class creation with factory method - java

My singleton class implements a interface and in future I can expect many concrete implementation to come out .
I am thinking of creating an instance of this class through factory method. factory method may be overloaded .
My question is how good or bad this idea is ?

Based on your updated comment, sure you can do that. A factory method dishes out singleton implementations of your persistence classes based on the overloaded parameters or an enum / integer value in the parameter. There are many frameworks out there that use this pattern, say to give you instances of a client that communicate with a server based on different protocols.
MyFactory.pbClient("host", port);
MyFactory.httpClient("host", port);

It is irrelevant if the instance returned from your factory method is a singleton. That is an implementation choice - do what is correct for your need.
Also, if your method signature is returning an interface, then technically it's an abstract factory method, not a factory method.

Related

Java's DAO definition of Factory Method [closed]

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?

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).

"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.

Java - Create new Instance using Reflection without knowing constructor params

I need to create new instances of many classes. I'm using reflection but when I make c.newInstance(), the classes without 'empty parameter constructor' throws an java.lang.InstantiationException.
Now, how can i do to create instances of every classes ?
I know that i can use c.getConstructor(Class).newinstance(params) to create instances of classes that doesn't have 'empty parameter constructor', but i do not know the params of each classes.
One more thing, all those classes extend from another class called ParentClass, so one workaround that i could use is to include some code in the ParentClass that force the child classes to implement an 'empty parameter constructor', but don't know how to do this.
Thanks in advance !
You can call Class.getConstructors() to get all the constructors for a given class.
On each Constructor, you can call Constructor.getGenericParameterTypes() to learn which parameters it expects.
JavaDoc for Class
JavaDoc for Constructor
You can't. There's no way to "require" a parameterless constructor and have it enforced by the compiler, and by definition to create an instance of a class you must provide it with the necessary parameters, or otherwise you'll wind up with an object that violates the class contract (because it is not initialized properly).
The proper way to enforce this at a code level is with an object factory and interfaces. I'm presuming that you're having to use reflection because you don't know about the types at compile time; In this case, there should also be a "Factory" which knows how to produce instances of each type. This factory should be built/compiled with the type in question, so that it is aware of and can invoke the proper constructor. The Factory then implements an interface which your code is aware of, such as "ObjectFactory", that allows you to delegate to the factory for instantiating objects. You would then have some method which an object factory can use to register as being responsible for whatever types it can instantiate.
In the code that ships with the classes you're trying to create:
static {
FactoryRegistry.register(TypeA.class, new TypeAFactory());
}
And in your code:
Class<?> unknownClass = ...;
Object obj = FactoryRegistry.getFactory(unknownClass).newInstance();
(where you have a Factory interface that TypeAFactory implements and specifies the newInstance method)
You don't know what unknownClass is or how to instantiate it, but if the code that came with that class registered a factory, you can query for that factory and ask it to create the object for you. If unknownClass is really TypeA.class, then the registry will return the TypeAFactory that was registered to create objects.
Alternatively, you can just require that the authors of any code your framework is loading dynamically include an argument-less constructor. It's not rigidly enforced, but can be easier for authors to implement.
There are two reflective methods for creating instances of classes: java.lang.reflect.Constructor.newInstance() and Class.newInstance()
Class.newInstance() can only invoke the zero-argument constructor, while
Constructor.newInstance() may invoke any constructor, regardless of the number of parameters.

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