"Kerievsky states that the Replace Constructors with Creation Methods refactoring does not generate an implementation that is fully compliant with the Gang of Four's concept of a Factory Method."
I'm trying to wrap my head around this. As far as I know Factory methods are always Creation methods but Creation Methods are not always Factory methods? Could someone explain this to me?
Well, you can replace the contructors with facotry methods. But to be fully compliant you need to have a class heriacy where
The factory method pattern relies on inheritance, as object creation
is delegated to subclasses that implement the factory method to create
objects.
http://en.wikipedia.org/wiki/Factory_method_pattern
If I understand correctly, what Kerievsky meant is:
If we only consider a method which simply creates an object, then Factory and creation method are same.
The main difference is the coupling. The main motivation behind creating factory method is to facilitate the loose coupling and differing object creation. Whereas the creation methods are tightly coupled to the class where is defined.
The idea is also explained in the book as follows:
To form a Creation Method, a class must implement a static or nonstatic method that
instantiates and returns an object. On the other hand, if you wish to
form a Factory Method [DP], you need the following:
• A type (defined by an interface, abstract class, or class) to
identify the set of classes that Factory Method implementors may
instantiate and return
• The set of classes that implement that type
• Several classes that implement the Factory Method, making local
decisions about which of the set of classes to instantiate,
initialize, and return
Related
GOF talks about frameworks for "Factory method" pattern. Frameworks need objects but implementation of objects depends upon application hence an abstract method to create the object is created. Also as return type is needed so interface for the object needed is defined, it defines the apis needed for the object. Actual objects are created by subclasses (concrete Application) . This is a creational pattern.
For Template pattern the only change is that the encapsulating class does not know the implementation of certain behavior hence it abstracts it in a method , uses it but leaves the implementation to the subclasses. This is behavioral pattern.
Is the only differences between the two are
1. Factory method is creational and Template is behavioural.
2. Factory method abstracts a method to create an object where as template pattern abstracts a method for some policy or algorithm.
example code
/**factory-method example**/
public abstract class Application{
public void create(){
View contentView = createContentView();
Menu menu = contentView.obtainMenu();
generateMenuItems(menu);
}
public abstract View createContentView(); //factory-method
public void generateMenuItems(Menu menu){
// some code
}
}
/** Product Specification**/
public interface View{
public abstract Menu obtainMenu();
// other abstract method of product
}
Now User code using above will subclass Application and provide implementation for createContentView().
Template method basic characterstic : Parent class concrete method invoking its abstract method.
Factory method : lets the product creation be implemented by its sub classes.
Above example fits for both. In fact any example for Factory methods fits for Template method as well.
So it is good to say
Factory method pattern is specialized template method pattern for obtaining the object whose implementation is dependent upon user code which can provide implementation of object creation in the subclass
Template pattern if used for object creation is Factory method pattern.
My second doubt : Is it mandatory for Factory method (which is as per GOF based on inberitence) to invoke its abstract product producing method from its other concrete method ?
If answer to above is 'No' then this means there will be some consumer code which will have an instance of type Factory (composition),will invoke the factory method to obtain the object of a product and will get concrete factory class injected. But now this becomes abstract factory.
I don't want to oversimplify these patterns, but, yes, both abstractions defer implementation details completely. Decoupling clients from implementation details is more flexible and allows each to evolve independently; this is the essence of the Dependency Inversion Principle.
Factory Method defers creation completely
Strategy defers behavior completely
To address the comment above:
Template Method defers behavior partially (not quite the same)
These patterns are not used exclusively, e.g., Strategy can use Template Method, Factory Method, or other patterns.
I hope this helps!
Both Factory method pattern and Template method pattern have similar design but they vary for their purpose.
Factory method is a creational pattern where object creation is the responsibility of the child class.
A pattern where a class defines an abstract method for an object creation and another method using the created object and thereby allowing the subclasses to provide the implementation of the creational method is factory method.
Template method is a behavioral pattern where behaviour is the responsibility of the sub class.
A pattern where a class defines an abstract method for a behaviour and another method invokes the abstract method to have the behaviour executed, the behaviour is implemented by the subclass. Hence its the parent class invoking the implementation of the child class without having any explicit compile time dependency on its subclass. This is true for the factory method pattern as well. But both differs in their intent.
In other words we can say Factory method pattern creates object in a similar way as Template method pattern executes the behaviour.
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.
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();
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?
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...