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...
Related
I was reading effective java and one advantage of static factory methods written is that they can return an object of any sub-type of return type.
I understood the way we can implement this as mentioned in following link with example.
https://www.slideshare.net/mysky14/java-static-factory-methods
But in the book an example of Collections API is given that has static factory methods in java.util.Collections utility class and it is written that "Collections API is much smaller than it would have been had it exported 32 separate public classes".
It is also mentioned that in this manner, API can return objects without their classes to be public and this results in very compact API.
I want to know how the API size is reduced by implementing this method and not having separate public classes.
I want to know how the API size is reduced by implementing this method and not having separate public classes.
Let's use the same concrete example used in the book: java.util.EnumSet has static factories that return one of two implementations: RegularEnumSet or JumboEnumSet. These implementations have their own complexities, but are effectively hidden to the clients of Collections. In theory, the factories could use other implementations in the future, and the clients of them would not be affected.
If you visualized this in a class diagram, the factory methods (e.g., of(), as opposed to a constructor) return an abstract type EnumSet, which hides the details of the implementations. Abstract (or Interface) types effectively abstract (simplify) the API.
What's more, the implementations are actually package private, meaning they're declared without a public keyword. This means that only classes in the same package can see them, so it prevents having Client depend on them. This is a great example of information hiding, which allows API developers to simplify their API and also to change the hidden parts later without breaking the code.
Another example that comes to mind where factory methods can simplify an API are the concrete iterators in Collections. In this case, it's a factory method that is not static, e.g., ArrayList.iterator(), that returns a concrete iterator for ArrayLists. The name of this class is even less "known" than the EnumSet implementations.
In general having static factory method would take out your object instantiation logic out of your class. Suppose based on certain logic, you need to return different subclass objects. This would result in if-else logic in your class method whichever is responsible for appropriate object instantiation. Moving this out to static factory method would result in cleaner class design which would be easier to test and closer to "Closed to modification" principle
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.
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.
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();
Back couple of months ago I attended a presentation hosted by two representative of an independent software development company. It was mainly about good software design and practices.
The two guys were talking mainly about Java and I remember them saying, that in some circumstances it is very good practice to use getInstanceOf() instead of the constructor. It had something to do with making always calling getInstanceOf() from different classes rather than constructor and how it was it is much better approach on larger scale projects.
As you can see I cannot remember much from it now :/ but I remember that the arguments that they used were really convincing. I wonder if any of you ever came across such a design and when, would you say, is it useful? Or do you think it isn't at all?
Consider static factory methods instead of constructors—Joshua Bloch
They were probably talking about the static factory method pattern (and not the reflection API method for dynamically creating objects).
There at several advantages of a method such as getInstanceOf() over a constructor and using new. The static factory method can...
Choose to create a different sub-class of the main class if that is desirable in certain cases (based on environmental conditions, such as properties and other objects/singletons, or method parameters).
Choose to return an existing object instead of creating one. For an example of this, see Boolean.valueOf(boolean) in the Java API.
Do the same thing as the constructor - just return a new instance of the class itself.
Provide many different kinds of ways to construct a new object and name those methods so they are less confusing (e.g. try this with constructors and you soon have many different overloads). Sometimes this is not even possible with constructors if you need to be able to create an instance two different ways but only need the same type of parameters. Example:
// This class will not compile!
public class MyClass {
public MyClass(String name, int max) {
//init here
}
public MyClass(String name, int age) {
// init here
}
}
// This class will compile.
public class MyClass2 {
private MyClass2() {
}
public static MyClass2 getInstanceOfMax(String name, int max) {
MyClass2 m2 = new MyClass2();
// init here
return m2;
}
public static MyClass2 getInstanceOfAge(String name, int age) {
MyClass2 m2 = new MyClass2();
// init here
return m2;
}
}
Do any combination of the above.
And, on top of all that it hides the detail of instantiating an instance from other classes and so can be varied in the future (construction encapsulation).
A constructor can only ever create a new instance of an object of the exact type requested. It cannot be varied later.
Some disadvantages of this pattern are:
The factory methods are static so cannot be inherited in sub-classes; a parent constructor is easily accessible to sub-classes.
The factory method names can vary widely and this could be confusing for some (new) developers.
You also asked for personal experience. Yes, I frequently use both patterns. For most classes constructor but when there are much more advanced needs then I use the static factory. I also work on projects in other languages (proprietary, but similar to Java) where this form of construction is mandated.
I suspect you mean the newInstance method on the Class class. You would invoke it like this: MyClass foo = MyClass.newInstance();
This form of object instantiation is popular in creational patterns; it's useful when you want to specify the concrete, runtime type of an object externally, such as in a properties or XML file.
If Drew is right, newInstance() is part of the Java Reflection API. So it is not as natural as using a constructor.
Why it would be recommended to use it on a large project may come with the fact that it leads to Java Bean programming style and clearly makes the creation of the object something particular. On large project, creating object shouldn't be a cross-cutting concern but rather a clearly identified responsibility, often from one source / factory. But IMHO, you get all of those advantages and many more with IoC pattern.