When should we use the factory method pattern? (instead of composition) - java

As per GOF book, Factory method pattern
Define an interface for creating an object, but let the subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclass.
Structure of the pattern
public abstract class Factory {
public abstract IProduct createProduct();
private void performCriticalJob(){
IProduct product = createProduct();
product.serve();
}
public void executeJob(){
//some code
performCriticalJob();
//some more code
}
}
public interface IProduct {
public void serve();
}
Factory needs an object (whose concrete class is not known or whose concrete class may change as per the different application type ) to perform a task.
As it does not know which class to instantiate, one standard contract is set for the type of object needed, this contract is put in an Interface.
Base factory class declares an abstract method to return an object of type as above defined interface.
It lets subclasses decide and provide the implementation of object creation.
For completion of the task it needs an object which it simply fetches by calling the abstract method.
Question Favour Composition over inheritance.
Factory method above uses inheritance to get the concrete products. Also subclasses need to be implement the createProduct which will create and return the ConcreteProduct. Instead of Subclassing the Factory class, if abstract method is removed from it (which makes the Factory class as non abstract class). Now Factory class can be composed by the new classes and concrete product objects can be injected in it as below example.
To achieve the intent in the scenarios as defined by Factory method pattern why just normal polymorphism is not being used as below ? I know factory method pattern has something more which I am missing but going by the favouting composition over inheritance, i find the below way ,to solve the same problem in same scenario , a better way over the way as in Factory method. What is the advantage of Factory method over the method below ?
public abstract class PolymorphismWay {
private void performCriticalJob(IProduct product){
product.serve();
//some code
}
public void executeJob(IProduct product){
//some code
performCriticalJob(product);
//some more code
}
}
Now instead of asking users to create child factory classes and returning the concrete object of product by implementing the createProduct method, users can directly provide the object of concrete classes implementing IProduct to executeJob.
[EDIT] Thanks for the answers and comments but same thought as expressed in comments and answers I also had which also brought some confusion. I studied the GOF factory method pattern. It has used an example of a Framework for applications creating documents of various types. My questions are doubts those arouse after this study.
The sites and blogs are based nothing but the reflection of the understanding which the authour has for the pattern, he / she may or maynot have read, understood the actual intent of the pattern. Understanding the classes is not the main objective. Design pattern should be studied considering what scenario and what problem comes for which the best solution following the good OOP principles ( or violating them the least and voilating them along with having a very good reason to do so). That best solution is the solution as explained by any design pattern. GOF is a standard book which explains it quite well. But still there are few gaps or doubts which is the main reason for this question.

I know factory method pattern has something more which I am missing but going by the favouting composition over inheritance, i find the below way ,to solve the same problem in same scenario
There are several advantages that you get when using the Factory Method pattern instead of plain old composition as shown in your question :
1. Separation of concerns and open-closed principle : You create one factory subclass for each related group of objects. This factory subclass is responsible for creating only those products that belong to a particular group. ABCProductFactory will only be concerned with creating ABCProduct1, ABCProduct2, etc. CDEProductFactory will only be concerned with creating CDEProduct1, CDEProduct2 and so on. For every new product group, you create a new subclass rather than modifying an existing class. If you went with the composition approach, some other class would be responsible for creating the product and passing it into your Factory. As your product variety increases to say ZZZProduct1 and ZZZProduct2 and so on, this class would soon explode to a huge size with too many if-else conditions to check which product subclass to create. You would eventually realize this and define one class for creating each related group of products.
2. Product creation and product processing has a contract : The factory method pattern is very similar to the template-method pattern in this case as it specifies a template for the operations that need to be performed on an object after it has been created. This allows you to ensure that once a product is created, it will always go through the same steps as any other product created by the factory. Compare this to the Composition example in your question where there is no fixed contract for what steps an IProduct should go through once it has been created. I could create a class called Factory2 with a single public method called performCriticalJob. Nothing forces me to have an executeJob method in Factory2. Even if I add an executeJob method to Factory2, nothing forces me to call performCriticalJob inside executeJob. You could fix this issue by using the template pattern.
It should be clear by now that the Factory Method pattern basically binds the object creation and object processing together in one class. With your composition example, you would have a lot of moving pieces and no one governing how they should work together.
Bottom line : In your case, use the Factory Method pattern when you want object creation and object processing to have a fixed contract such that all objects go through the same processing once created. Use your composition example where there is no contract needed for the steps to be followed after the object has been created.

Your problem is, you are insisting that your Factory class has only ONE kind of clients who always use the class by either extending it (the code #1) or passing a newly-created IProduct to its methods (the code #2). The whole purpose of this kind of clients is to make the Factory the ability of receiving a newly-created IProduct.
How about normal clients who don't care about all of the things above! These even don't care whether the class is Factory or not. Thus, they don't want a method requiring an IProduct as in your code #2.
Indeed, you should rename your Factory class to something else (e.g., XXX), the class is not "factory"! But some of its methods are "factory". You see, the pattern name is "Factory Method", not "Factory" or "Factory Object". In contrast, in Abstract Factory pattern, an abstract factory is really a factory object.
P/S: a proper composition approach is passing an abstract factory into the constructor of XXX.

Since we know the Factory Method Pattern relies on inheritance, this problem is much easier to reason about if we begin without the Factory Method piece and simply ask, when should we favor inheritance over composition?
We already know the answer to that question is, "not often" because the GoF has told us to favor composition in general. Yet there are real-world scenarios where inheritance exists. The animal kingdom may be the quintessential example. When inheritance actually occurs within a domain, it makes sense to model it the same way in our code. And that's when we should consider the Factory Method Pattern as well. Consider it only when you've already decided that inheritance is appropriate to the context. First choose inheritance, then choose the creational pattern. Don't introduce Factory Method and then be forced into an inheritance relationship that otherwise wouldn't apply.
A more opinionated answer is: never use the Factory Method Pattern in modern code. Stick with composition relationships, all wired together within a dependency-injection container. The GoF patterns are not advice. They are a collection of designs from the 1980s. Similar to the way Singleton is now considered to be more anti-pattern than pattern due to its negative side effects, Factory Method has very little applicability in modern code. In those rare cases where it may be appropriate, you'll know it because you'll already be using inheritance.

Read again the definition you've provided:
Define an interface for creating an object, but let the subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclass.
Which a bit contradicts your first statement:
Factory needs an object (whose concrete class is not known or whose concrete class may change as per the different application type ) to perform a task
The factory purpose is creating objects, not performing tasks.
In fact, event if it will perform a task it's only to be able to create the object for you.
After you get the object from the factory, you can perform your critical job.
And about Favour Composition over inheritance, the factory method can compose the object for you as well and deliver back an object composition.
There are many good examples of factory pattern - for example in Wikipedia and blackwasp
Edit - Concerning the GoF Application example
The GoF example of the Application uses a Template Method for the Factory Method.
the Application defines the factory method and some operations around it, but the sub-classes of the Application decide which Document to create.
You have suggested, not to use factory method. Instead, to create the Document somewhere else and "injected" to the Application (a.k.a dependency injection).
You have not described where will the Document be created (it could still be a factory).
Now the Application sub-classes doesn't have any control on the creation of the Document. This changes the behavior and design of the system completely.
It doesn't mean that its bad or good, it's just a different approach.
In real-life scenarios you have to carefully examine the problem at hand and decide which design would fit the most.

Related

Factory Method: "Patterns in Java" by Mark Grand vs GoF interpretation

I'm learning Java design patterns by "Patterns in Java", volume 1 by Mark Grand (Factory Method specifically). My point is to highlight difference between closest patterns for myself. There are good answers that clarify the difference between Factory Method and Abstract Factory (Design Patterns: Factory vs Factory method vs Abstract Factory, What is the basic difference between the Factory and Abstract Factory Design Patterns?). But I noticed that most of authors mean some other interpretation of Factory Method compared to one I have read in "Patterns in Java". The interpretation from the answers is closer to Factory Method from GoF book.
GoF interpretation:
Grand's interpretation:
To be specific I will describe what in my opinion is a key difference between Grand's and GoF interpretations. The source of polymorphism in GoF interpretation is inheritance: different implementations of Creator create different types of Products. The source of polymorphism in Mark Grand interpretations apparently is "data-driven class determination" (example from book):
Image createImage(String ext){
if (ext.equals("gif"))
return new GIFImage();
if (ext.equals("jpeg"))
return new JPEGImage();
...
}
CreationRequester delegates object creation to other object that encapsulates "data-driven class determination" logic to pick a right type of ProductIF by discriminator argument.
Can any one please explain me:
Is the Grand's Factory Method interpretation equivalent to Factory Method by GoF? Is it actually Factory Method at all? May be it is some kind of generalization or special case of GoF Factory Method? I can't see direct mapping between these interpretations taking into account UML class diagrams.
Let's consider GoF interpretation now. Can one define a factory method in a separate interface (not in abstract class), like Mark Grand describes? Will it still be Factory Method? Can one consider Factory Method in GoF interpretation as a special case of Template Method that returns some product?
If we consider Factory Method as Grand describes, then it becomes obvious that Factory Method is simply a special case of Abstract Factory that produces a single product. Am I right?
If one just encapsulates a "data-driven class determination" logic into a separate class, can this structure be called "Factory Method"?
The GoF Factory Method Pattern defines three varieties: What's the difference between Factory Method implementations? Grand's discriminator is indicative of what the GoF refer to as a parameterized factory method.
The GoF usage of the word interface is equivalent to abstraction. It predates Java's invention of the interface class and keyword. Interfaces and abstract classes are interchangeable.
Factory Method is a special case of Template Method: What are the differences between Abstract Factory and Factory design patterns?
No: Design Patterns: Abstract Factory vs Factory Method
No: without inheritance and without a template method, it would be what Head First Design Patterns calls a Simple Factory.
Question #1.
No.
No.
Sometimes UML obfuscates a thing more than it clarifies a thing.
Question #2.
I only see one factory interface in the Grand picture. I don't see a separate interface.
?
Yes. And no.
Question #3.
No.
Question #4.
No.
I'm not as up on my GoF patterns as I used to be, but I'll take a shot at this.
I think you are correct about the difference. The GoF pattern uses inheritance for polymorphism and Grand's example uses conditional logic for polymorphism.
The operational difference is that to add a new type in Grand's example, I would modify the method createImage:
if (ext.equals("png"))
return new PngImage()
In the GoF version no existing code is modified. I create a new subclass calledPngCreator that implements the Creator interface. This is a good example of the open/closed principle-- the GoF factory is closed to modification, but the pattern open to extension (by adding a new implementation of the factory interface).
Factory vs. Template
Factory Method is always implemented using the Template Method pattern (Design Patterns Smalltalk Companion by Alpert, Brown, and Woolf)
Yes, factory method pattern is a kind of template method pattern. However, a (GoF) pattern is more than its structure or diagram. Every pattern in the GoF book includes intent, motivation, applicability, participants, and so on. Intent and motivation are part of what makes Factory and Template different. For starters, one is a creation pattern and the other is a behavioral pattern.
The intent of the Factory Method pattern is to let subclasses of the Factory decide what class to instantiate. In Grand's version, I see only one concrete factory, and it uses conditional logic. IMHO, that is different than using multiple concrete subclasses. Then again, Grand's version does decouple creation requesters from class names. If you modify the factory to return an instance of Jpeg2000 instead of Jpeg, the compiler won't complain. CreationRequester depends only on the interface Image. This is important if I am using someone else's library and I can't modify it. If avoiding re-compilation of the creation requester is the motivation, then Grand's version works fine.
Is Grand's Factory Method pattern a special case of Abstract Factory pattern?
I don't think it is. I'll borrow the example from my (ancient) copy of Design Patterns Smalltalk Companion. Let's say my application uses vehicles. I might have a VehicleFactory interface with methods like 'createTruck', 'createPassengerCar', 'createMotorcyle`.
What the vehicle manufacturer was important to my applicaiton? Enter the Abstract Factory pattern! VehicleFactory defines the methods createTruck, createPassengerCar, createMotorcyle. I create classes named ToyotaFactory, FordFactory and HondaFactory that all implement the interface.
Here is what each concrete factory return:
ToyotaFactory.createPassengerCar -> Camry
HondaFactory.createPassengerCar -> Accord
FordFactory.createPassengerCar -> Taurus
ToyotaFactory.createMotorcycle -> FM6
HondaFactory.createMotorcycle -> GoldWing
FordFactory.createPassengerCar -> return null or throw exception, or ...
On the next day, I add a FiatFactory. Because the client classes depend on the VehicleFactory interface, I don't have to change any old code or recompile anything.

Only one class can instantiate all other clases

What is best practice to restrict instantiation of the classes to only one class? Something like this but in Java.
Let's say there is Main class, then there are User, Admin, View, Data, Client etc. classes. Only 'Main' class should be able to instantiate all other classes.
So if 'User' need to call 'getUser' method in 'Data' class, it can't instantiate 'Data' class and call method, but it has to call 'Main' class, and then 'Main' will instantiate 'Data' class and pass arguments to its 'getUser' method.
What I am thinking is using private constructor, Factory Pattern etc., but not sure if this will result in what I need. Due to the complexity I don't think inner classes would be good solution.
Any advice on this?
A distinct answer on the conceptual level (as there are already good answers on the technical "how to do it"):
Let's say there is Main class, then there are User, Admin, View, Data, Client etc. classes. Only 'Main' class should be able to instantiate all other classes.
I don't think this is a good starting point. Of course, when one follows Domain Driven Design, using factories is well established.
But there is one subtle point to add: you still want to cut your "boundaries" in reasonable ways. Meaning: don't force all objects into a single factory. Your objects should somehow resemble their domains, and be separated where needed.
Meaning: using factories is fine, but don't force yourself into the wrong corner by enforcing that there is exactly one factory that is supposed to handle all kinds of objects you deal with. Instead: try to reasonably partition your object model, and have as many factories as it makes conceptually sense to have.
Also note that you probably should distinguish between objects that mainly provide data/information, and "behavior" on the end. Thus it might be worth looking into the idea of having a service registry (for example what you do with the netflix Eureka framework, see here).
And finally, to quote an excellent comment given by tucuxi here: For small applications, factories are over-engineering. For larger applications, I find it questionable to have a single factory called "Main", instead of splitting responsibilities in a more orthodox way.
You can use a subclass with a private constructor:
With this, only InstantiatonClass can create InstantiatonClass.ArgClass and the constructor of ProtectedClass.
public class ProtectedClass{
//constructor that can only be invoked with an instance of ArgClass
public ProtectedClass(InstantiatonClass.ArgClass checkArg){}
}
public class InstantiatonClass{
public static class ArgClass{
//constructor that can only be invoked from InstantiatonClass
private ArgClass(){}
}
}
You should be able to get caller's class in a Class's constructor:
How to get the name of the calling class in Java?
Then in the classes where you only want to be instantiated by Main, simply check the caller class is Main in its constructor, if not throw a RuntimeException.

Factory Method Design Pattern `static` modifier must need or not

I'm studying about Design patterns. I have studied about Factory Design Pattern in java and i have Some things I didn't understand well and I'm writing them following.
Is there any different between Factory Design Pattern and Factory Method Design Pattern.
I saw in some examples, Factory class's get method is static and some examples its not static. What is the correct way.
Any help would appreciate.
I'm not too deep in design patterns in the sense that I did not ingest massive books discussing them in much abstraction, but I certainly have an idea of what they are and know how to apply them. Here is my understanding of these two patterns:
Factory is a pattern that delays the instantiation of an object by handing an object that knows how to construct others objects.This can have several advantages going. For example, let's say you are writing a theading pool library. A pool contains objects that can perform certain actions, and you want to be able to create pools of any size. Each object of the pool must be a distinct object. You could ask the user of your pool to give you as many objects as they want in the pool, but you can also ask them for a single factory that you will use to instantiate the objects yourself. This way, you can also dynamically change the size of the pool, destructing or regenerating objects, etc... It gives all the flexibility you need without knowing anything about the objects your pool is holding.
Factory method is different. Let's say you have a big constructor with a lot of parameters. Some of these parameters may have default values, or you may have various way to configure this class. You could certainly add a constructor for each typical configuration (set of parameters) but this wouldn't be user-friendly as all the constructors share the same name. To make it easier, you could have static methods that just call the constructor with the appropriate configuration. The advantage is that you can name these methods (defaultHttpClientForProd, defaultHttpClientForDev etc...). Another use-case is if you have a massive class hierarchy, say an abstract class Car extended by dozens of classes. You could use each individual constructor to build your dream car, but you would have to look at each and every page of the catalog to decide which one you want. You could alternatively have a single page that summarizes all the cars available, this would be a class containing a lot of factory methods, making them more discoverable.
For your second question about, I would say it depends. If you don't need to customize your factory too much or inject a lot of context, a static method with some parameters will do the trick. If you want your factory to be more configurable, a class with attributes and an instance method will be better.
To be specific to your questions:
Abstract Factory & Factory Method are two different design patterns. Refer to Gang of Four (Design patterns) for detailed explanation. The key difference is Abstract Factory or Factory is about creating families of related objects (note the word family meaning group of objects) whereas Factory Method is providing a creational method to create one particular type of object (not family), which can be implemented by multiple factory implementation class. Essentially, Factory Method is used in implementing Factory or Abstract Factory pattern but not the vice-versa.
As far as static method is concerned, it is not mandated by the pattern itself. It is specific to Java & hence static modifier is used to make sure Factory's getInstance() or any creational method is Singleton. You don't want multiple instances of Factory and hence in Java, you implement by having static instance of Factory and therefore, you will need static method to return the static instance.
Different tutorials seem to mean different things by the factory design pattern. I would say that the ones in your links are both simple factories. I think this post explains the difference simply: Simple Factory vs. Factory Method vs. Abstract Factory
Simple factories can be identified by the use of a static method to create different subclasses, usually with some kind of if/else or switch structure. The example in the second link doesn't actually use a static method, but it can easily be made static without changing much.
In the Gang of Four book, the Factory Method Pattern is defined as:
Define an interface for creating an object, but let subclasses decide
which class to instantiate. The Factory method lets a class defer
instantiation it uses to subclasses.
Because of the use of subclasses, static methods will not work here because they can't be overridden. The shape example done this way would be more like:
public interface ShapeFactory {
Shape getShape();
}
public class CircleFactory implements ShapeFactory {
public Shape getShape() {
return new Circle();
}
}
public class RectangleFactory implements ShapeFactory {
public Shape getShape() {
return new Rectangle();
}
}
ShapeFactory shapeFactory = new CircleFactory();
...
Shape shape = shapeFactory.getShape();
Here, we can separate the creation of the factory from its usage. The factory can be created in one class and then passed to another, so a class can create different types of objects by being configured by another.
Or in Java 8, we can just use:
Supplier<Shape> shapeFactory = Circle::new;
...
Shape shape = shapeFactory.get();

Calling the sub class method from super class isn't best practice?

I am working on a project where we have an abstract class(BaseConverter) with one abstract method(convert()) and few concrete methods. One important concrete method is invokeConverter() which will basically call the convert() method implemented in the subclass.
While our code is being reviewed by other guy, he told that, subclass methods shouldn't be called from superclass and he told it is not best practice. Below is our class structure. Can someone please tell whether this isn't a right way to do?
#Named
public abstract class BaseConverter{
#Inject
private ConversionDriver conversionDriver;//this class is responsible to return the correct subclass object based on the type
protected abstract String convert(Object toConvert);
public String invokeConverter(ConverterType type, Object toConvert){
conversionDriver.getConverter(type).convert(toConvert);//getConverter() return the subclass object based on the type
}
....
....
}
It is actually a design pattern called Template Method by GoF. However, you should not over apply it as it favors inheritance over composition.
Define the skeleton of an algorithm in an operation, deferring some
steps to subclasses. Template Method lets subclasses redefine certain
steps of an algorithm without changing the algorithm's structure.
You'll find this pattern implemented in many known frameworks and plugins. But, you should consider different patterns like the Strategy or the Decorator in some cases.
For instance, while Strategy pattern uses delegation to vary the whole algorithm, Template Method uses the defamed inheritance to vary a specific part of an algorithm. Strategy also modifies the logic of individual objects at run-time, while the Template Method modifies the logic of the entire class at compile-time by subclassing.
Regarding "best practice" - it is a controversial term. I believe that the Template Method should be replaced in favor of a better design pattern when the code base grows and refactoring for a better complexity is needed.
But sometimes it is the best solution for your needs. For example, you might have doExecute() method and would like other programmers to extend your class (whilst not modifying it), so you let them hook into the parts of your code providing a beforeExecute() method. Mature system would maybe include an event dispatcher capabilities if we talked about combination of various objects.

why use getInstance

A lot of the publicly available Java APIs seem to use getInstance in order to generate and return an object. I'm curious about why this is so -- why not just use default/parameterized constructors instead?
Is there an associated design pattern?
I suggest to read "Effective Java" by Joshua Bloch, Item 1 "Consider static factory methods instead of constructors". He led the design and implementation of numerous Java platform features, he knows why.
It is associated with Singleton Pattern.
Many times there are also Factory Methods which help you in creating objects.
For example: Boolean.parseBoolean("true");
Advantages of Factory Methods are they are more verbose and easy to grasp than a series of constructors.
Another example (apart from the singleton or multi-ton pattern) is if you need to do something in the constructor that is generally not recommended, such as registering a listener or starting a thread:
class Whatever {
private Whatever() {} //private constructor
public Whatever getInstance() {
Whatever w = new Whatever();
startSomeThread();
return w;
}
}
Yes....It is associated with both Factory and Singleton pattern. Factory pattern is used to decouple the object creation logic from the business logic and Singleton pattern is used to maintain only a single instance of an object through out the application.
"why not just use default/parameterized constructors instead" because at the point you invoke the constructor it is already too late to ensure the Singleton Pattern constraint to have only one instance. The whole point is to have controlled access to a single instance and avoid multiple instances. The only way to do that is to use access modifiers to prevent the constructor from being accessible.
To save you the trouble of looking up concrete reasons...
This is a case of the Factory Method pattern. The most common reasons to use it are:
If construction is too complex to handle in a constructor
If construction requires actions that are not permitted or desired in a
constructor
To decouple the type of the product ("interface") from the actual implementation ("class").
For performance or architechtural reasons, such as to perform partial specialization at construction time
For clarity/readability
There is some overlap between these reasons. In fact, often all four apply. Partial specialization (4) pretty much requires decoupling of type and implementation (3).
As it has been said, it's a matter of some pattern designs "requirements" to provide an easy/secure solution.
But you should avoid the using of "getInstance" (java.lang.Class.getInstance()' and 'java.lang.Class.NewInstance()') as far as possible in terms of Dynamic Instantiation, because Dynamic instantiation is slower than a regular Class invocation or Method call.
Use it only when it is necessary!

Categories