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

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();

Related

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

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.

Is this code implements 'Factory Pattern', factory methods, both or none?

Although this subject has been discussed many times, I still find myself get too confused with it.
I have this simple code sample:
public class FruitFactory {
public static Apple getApple() {
return new Apple();
}
public static Banana getBanana() {
return new Banana();
}
public static Orange getOrange() {
return new Orange();
}
}
Which Factory type this code is? and is it a proper writing of factory methods?
The factory pattern definition is: create an object without exposing the creation logic to the client
If I expose my client to some of the creation complexity like as the example below, is it a bad factory implementation?
public static Orange getOrange(String weight, String size,) {
return new Orange(weight, size);
}
The first code is a Factory pattern because you have just one class without subclassing, overriding, etc.
When you want to use a factory method than write (Banana inherits from Fruit):
public abstract FruitFactory {
public abstract Fruit createFruit();
}
public BananaFactory extends FruitFactory {
#Override
public Fruit createFruit() {
return new Banana();
}
}
The implementation:
public static Orange getOrange(String weight, String size) {
return new Orange(weight, size);
}
is also a correct implementation in my opinion because you encapsulate the creational logic like explained from #amn.
The good thing in using the static method is that you can make the constructor private so it is only possible to instantiate objects by using the method.
For better understanding see the following link: patterns
The factory pattern's purpose is to put an abstraction layer on top of object creation.
If the object has enough information to create itself without too many arguments or settings, then you don't need to use a factory pattern, as the object's constructor is a factory in itself.
This is the problem with your current code, it doesn't add a layer of abstraction to anything. You simply encapsulate the constructor.
The problem with the second code sample is the same, if it were a factory, then it would choose the weight or size of the fruits randomly or by an algorithm, like a real tree does.
Edit: The original Gang of four description is
"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."
This means, that your code isn't a factory, because you need to define what you need.
As it is said, a factory is merely an abstraction where object creation implementation is intentionally encapsulated behind the factory's public interface. A factory does not have to be a class, it does not have to be a package -- different languages achieve encapsulation of state and behavioral details differently (consider closures, for instance).
A function in a language that allows "top-level" functions, can be a factory as well:
public Orange growNewOrange(String weight, String size) {
/// ...traditionally not callers concern.
}
If the factory hides creation code behind a way for you to use it without concerning yourself with said creation code for each created object, you already have a useful isolation (between getting new objects and that which manages them) that solves the problem the factory pattern was designed to solve.
There are factories that are designed to create and manage one kind of objects and then there are those that create and manage multiple kinds of objects. A fruit factory where you can specify the concrete class of fruit you want, still matches a valid factory pattern.
Categorizing factory implementations into "types" is done by various OOP authors, and may be useful for various good reasons, but this is not essential to be able to utilize the general idea to your advantage.
The immediately useful advice would be encapsulate creation code in a Java package or class, where specifying parameters of a created object is done on a per-object basis, while factory state controlling creation logic -- for instance size of reused object pool etc -- is set up during factory creation itself. Object pools are one of the examples of factory pattern at work.

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!

Why should the getInstance() method in Factory pattern be static?

In most of the factory pattern implementations, the getInstance method is usually declared as static. The main advantage of factory pattern is to hide the implementation details, but why does getInstance() method needs to be static? Is instantiating a new Factory Object a bad practice?
XYZFactory factory = new XYZFactory();
XYZObj obj = factory.getInstance(TYPE);
Vs
XYZObj obj = XYZFactory.getInstance(TYPE);
A lot of factory methods are used to offer an instance of the class itself, without the class exporting any constructors (see e.g. Josh Bloch item 1). If the factory method were an instance method, you wouldn't have an object of the class to start with.
Furthermore, getInstance() is usually independent of any existing instance, so it should be declared static. If it depends on one, a prototype (i.e. clone()) is often preferred.
Finally, you should distinguish between factory method public static getInstance() and an abstract factory, which is a class that hides implementation details often for several interfaces. You must, of course, be able to instantiate subclasses of the abstract factory. You can find a great introduction to creational patterns (Abstract Factory, Factory Method, Prototype, amongst others) in the classic Design Patterns book from the Gang of Four. It also gives an example of a non-static factory method intermixed with a prototype. So you see, many variants are possible...
Daves answer is absolutely correct if the factory method is in the class itself. For a factory method in some other class, I think it is a matter of style. I would go back to the basic question of when is something static: does this method provide behavior to the class as a whole, or to specific instances of the class? I argue factory methods typically offer class-level behavior.
Factory should give you instances of products, not instances of itself. It's rather like Singleton.
Because you use a factory to create objects. What you need is object instances not factory instances. So you usually look for the simplest, cleanest way of doing it.
It isn't useful to have more instances of the factory laying around. The factory instances will be useless after creating the object(s), so why create useless factory objects when just one long lived instance will do?

abstract factory implementation

I've implemented an abstract factory like this
public abstract class AbstractFactory {
private static final Map FACTORIES = new HashMap();
AbstractFactory(FactoryType type) {
FACTORIES.put(type, this);
}
public abstract A getA();
public abstract B getB();
public static AbstractCatalogFactory getFactory(FactoryType type) {
return (AbstractCatalogFactory) FACTORIES.get(type);
}
}
A concrete factory must call this abstract factories constructor, causing each concrete implementation to be registered in the FACTORIES map. I'm a bit concerned about referring to this within a constructor, because it seems like the value of this should be undefined until execution of the constructor has returned.
Thanks,
Don
About leaking this from the constructor
I'm a bit concerned about referring to this within a constructor, because it seems like the value of this should be undefined until execution of the constructor has returned.
More precisely, the this reference should not leak out of the constructor to external parties before the constructor finishes. Otherwise the external party might end up calling a method on the yet unfinished new object.
Your implementation has a chance of this happening, since this is added to the map, which is accessible by external parties via the static method getInstance. A remedy could be synchronizing access to the map. Another option (as discussed by Josh Bloch in Effective Java) would be to make the constructors in any concrete subclass private, and have a static factory method instead in each subclass, to construct the object, then add it to the map. This would result in some code duplication though.
About your design
Apparently you are implementing a "catalog of factories" rather than a "factory of products", so this is fairly different from the classic Abstract Factory. Without more details it's hard to tell whether or not this is justified.
The main issue is that here you unify the factory interface and the factory "storage", which is IMO not a good idea. Clients of the factory should only see the factory interface with its getX methods, and should not be aware of what concrete factory they are actually using (much less selecting it themselves).
Moreover, typically there is only one concrete family of products in use at any given time, so only one concrete kind of factory is needed. This eliminates the possibility of mixing up incompatible products from different concrete product families. Your current design seems to allow this, which is not a good sign to me - but maybe you have a good reason for this...

Categories