Factory Pattern vs FactoryMethod Pattern - java

Could anybody please let me know why the FactoryMethod design pattern is introduced ? As my question is the same can be achivied using a Factory Pattern itself ?
For example if i see the difference between Factory Pattern and FactoryMethod Pattern the the Factory Pattern returns the Concrete IMplementation where as the FactoryMethod Pattern returns the Factory Object as its return type ??
Please tell me why FactoryMethod is introduced ??

In a nutshell:
Factory Method is a design pattern that "hides" the instantiation of concrete types from the rest of your code thereby providing loose coupling.
Abstract Factory is a design pattern that is introduced to provide different kind of factories that are responsible to create a specific group of concrete types. So you can switch between abstract factories and as a result get eventually different concrete instances of objects in your code.
So Abstract Factory is a step up i.e. a generization of Factory Method. In simple projects the latter is adequate. In projects with complicated hierarchies the Abstract Factory is needed.

As you can read on the wiki 'Abstract factory pattern, a pattern often implemented using factory methods'.
See this picture http://upload.wikimedia.org/wikipedia/commons/a/a7/Abstract_factory.svg
Design patterns are often/ always connected with each other and this way they show us the patterns concepts.
Regards Lukasz.

AbstractFactory pattern is another level of abstractization. The user is not aware of the type of object that he will get and it's not interested in that matter. The AbstractFactory decides which method it's used to create the concrete object that the user will recieve.
In method factory, the user decides which method to use for the object creation and knows what he gets. But this doesn't always concern him.
If I request a button in Method Factory, I need to know if I want a LinuxButton or a WindowsButton or a OSXButton. In AbstractFactory, I request a button, I recieve a button... and the AbstractFactory will decide how the button is created, knowing our OS.

As per understanding about Abstract factory is it Abstract Factory pattern is used when you have factories that can create a family of objects. while there is abstraction of Factory class.
while in case of factory method have abstraction over factory class and it produces single set of product objects.

Related

Factory Method pattern vs ordinary abstract class implementation

I'm trying to understand the Factory Method pattern. I've managed to distinguish it from the Simple Factory, but now I don't get why it's actually called a "pattern". Please, look at my example below:
Class Diagram link
Sample java code for Messenger:
public String exchangeMessages(String messageToSend) {
Socket socket = getSocket();
socket.open();
socket.send(messageToSend);
String receivedMessage = socket.receive();
socket.close();
return receivedMessage;
}
And for Client:
public static void main(String[] args) {
Messenger messenger = new TCPMessenger("127.0.0.1", 4321);
String result = messenger.exchangeMessages("Hello!");
System.out.println(result);
}
If I understand correctly, everything makes sense because exchangeMessages method exists. We use the abstract factory method getSocket inside it and thanks to it we:
let subclasses decide which class to instantiate
But isn't it just an ordinary abstract class implementation? We take advantage of the code shared by both TCPMessenger and UDPMessenger - for me, this is not a pattern but a core feature of Object-Oriented Programming that everybody knows from the beggining of OOP language learning!
Moreover, I think that naming this creational is very confusing. We actually care about exchangeMessages method, so Client (part of the code that uses our "pattern") is not even aware of the Socket class which creation we're all about. It's more like a way to implement Messenger functionallity (which can be easily extended etc...) than a way to really create something.
Am I missing the point or is my example invalid? Please guys, let me know what do you thing about it.
Thanks in advance!
for me, this is not a pattern but a core feature of Object-Oriented
Programming
Most of patterns rely on core OOP features : programming by interface, overriding, polymorphism, and so for...
Moreover, I think that naming this creational is very confusing.
We actually care about exchangeMessages method, so Client (part of the
code that uses our "pattern") is not even aware of the Socket class
which creation we're all about. It's more like a way to implement
Messenger functionality (which can be easily extended etc...) than a
way to really create something.
It depends on the point of view you are taking.
For subclasses of the Messenger abstract class such as TcpManager, their parent class defines all but this factory method that they have to implement to specify what Socket getSocket(); should return.
So for subclasses point of view, talking about a creational pattern for Socket getSocket() makes sense.
For client classes of Messenger, things are indeed different.
Clients may even not need to use directly this method.
For these classes, the important thing is indeed having a way to manipulate indifferently any subclass of Messenger.
The Factory Method pattern is a simple pattern, but still a pattern nonetheless.
Your Client and its relationship to the Factory Method
The Gang of Four (GoF) definition of the Factory Method Pattern does not specifically mention a Client as a participant of the pattern itself. In reality the Client is most likely to use the Factory Method indirectly through some other operation.
In your case as the Client does not care about the Socket being used, but just the Messenger itself. However, the Messenger is dependent upon a Socket as it has some behavior that uses a Socket Object.
So whilst the Client itself does not care about the Socket, it does care about the Messenger which has a use dependency with Socket.
As the Socket itself is abstract it gives us a problem, as we don't want to replicate the same logic in exchangeMessages(String) multiple times for the different implementations of Socket (TCPSocket and UDPSocket), especially when we may want to add more Socket classes at a later date.
This is where the Factory Method pattern comes into play, as we can define all the generalized behavior for exchanging messages at an abstract level, but leave the creation of the actual Socket implementation (TCPSocket and UDPSocket) to subclasses of Messenger (TCPMessenger and UDPMessenger).
Discussion of alternatives to the Factory Method Pattern
You could just set the Socket as a field of Messenger, and inject it using a Strategy pattern approach or have a constructor that takes a Socket as a parameter. A drawback of this approach is that we'll have to maintain a reference to this Socket Object as a class field in anticipation of it's use.
However, with the Factory Method Pattern, the Socket will only be created in the method exchangeMessages() when needed and then discarded when the method terminates, which may be of some benefit. This comes at the cost of having to create one of the Socket Objects each time exchangeMessages() is called, which may not be ideal.
You could also pass the required Socket to the exchangeMessages() method to be used, but this may not as convenient for the user of the method in the long term.
If your Messenger subclasses also have some specific behaviors (new methods / overridden implementations) not applicable to all types of Messenger, then Factory Method is certainly the way to go, as we need to subclass Messenger anyway and it allows us to strictly enforce the type of Socket created by the Factory Method getSocket().
Perhaps others could contribute to the pros/cons of the Factory Method (specifically in Java as this the language tag for the question) and I can update this answer in due course.
Validity of your example
About whether your example is invalid or not. I think it helps to first fully understand the pattern and the important classes, operations and relationships in order to conform to the Factory Method pattern (as specified by the GoF).
The Factory Method Pattern allows you to define an Operation (or possibly several operations) in an abstract Creator class (in your case Messenger) which will use some Object (a Product [Socket]) without knowing the specific Product in advance and deferring its creation (hence the term creational pattern) to the Factory Method.
The Factory Method itself (getSocket()) is abstract in the Creator class and will be implemented by Concrete Creators (TCPMessenger, UDPMessenger) so polymorphism is used to achieve Object creation.
The Factory Method will return a Concrete Product (TCPSocket, UDPSocket) and have a return type applicable to all Concrete Product classes (Socket) used by the Operation in the abstract Creator class.
The Operation(s) (exchangeMessages(String)) that use the Factory Method will use the Concrete Product returned by the Factory Method by the interface Product which is applicable to all Concrete Product classes (Socket).
The result is that this pattern allows new Concrete Product classes to be added by implementing / subclassing the Product interface / class (or its subclasses...) and introducing a new Concrete Creator which returns the newly added Concrete Product from its Factory Method, preventing the need to re-write your Operation(s) that use this Product.
This means that we do not need to modify existing code when introducing new Concrete Products (Open/Closed Principle).
Generalized UML for the Factory Method Pattern
Some notes on the UML:
The factoryMethod() can be given a default implementation in Creator (i.e. a default Product to return), in turn allowing Creator to be non-abstract
The factoryMethod() could be public if desired, but this is superficial to the intention of the pattern since the factoryMethod() is primarily intended to be used by operation()
Product does not have to be abstract class, it could be an interface or it could be a concrete class
Validity of your example (continued)
In reference to the UML (and your example), the important parts of the pattern in less wordy terms are as follows:
There must exist
A Product interface (not neccesarily an interface in Java terms, could be a class or abstract class in reality) (in your case Socket)
ConcreteProduct classes that implement the Product interface (TCPSocket, UDPSocket)
An abstract Creator class (Messenger)
A Product factoryMethod() method that is defined in the Creator class (getSocket())
Note: The Creator and factoryMethod() are usually abstract, but the Creator can define a default Product removing this requirement.
operation() methods in the Creator class that use the ConcreteProduct returned by the factoryMethod() (exchangeMessages(String))
At least one ConcreteCreator class (TCPMessenger and UDPMessenger))
Such that
The ConcreteCreator classes implement the Product factoryMethod() to create and return a ConcreteProduct
The abstract Creator class uses the ConcreteProduct (returned by Product factoryMethod()) through the interface for all Product implementations
The last two points reflect that Creator has a use dependency with the Product interface, and the ConcreteCreator classes have a create dependency with its corresponding ConcreteProduct class.
Again, note that the Client class is not part of the pattern itself (as defined by the GoF).
So in conclusion, your example would appear check out as the Factory Method in regards to the requirements listed above if the TCPMessenger and UDPMessenger class implement the getSocket() method correctly (which I assume they actually do).

What exactly can we describe Factory Method of design pattern?

I am confused with the concept ? Is it just as simple as incorporating a static method to return the object instead of a constructor ? So that client doesn't need to change the code while we update the library or there is something more to it ?
The book Head First Design Patterns will be your definitive guide for Java. That is a great book. If you check out my answer to this Stack Overflow Question, you will be able to see my implementation for an ArbitraryPointFactory class in the Point Example code that uses the Factory Method pattern as well as how it differs from Abstract Factory pattern seen in the Point Factory class. Although this answer is presented with C# code samples, the design pattern language I am using to describe their usage, should warrant you an answer.
What you are thinking of in your question is not a design pattern at all. This static method that returns an object to encapsulate the instantiation, is known as the Simple Factory as seen in the Wiki page. The Factory Method pattern more or less abstracts the type being returned via an interface. This is typically done where the sole job of the factory method class is to control creation of the objects for one concrete class that implements the interface being returned. The Abstract Factory provides encapsulation for a group of related products. In my example I was showing for different types of points, however they could implement different interfaces and all use the same Abstract Factory.
The idea is that you are programming to interfaces, not implementations. True factories pull creation logic to a single location in your application and encapsulate the instantiation via interfaces.

"Factory Method Design Pattern" in context of Java interfaces?

I am a beginner in Java and the book that I use to learn it seems to have cryptic examples and sentences that completely confuse me.
I understand what interfaces are and how/where to apply the concept in real world. But what are Factory Methods? The term "factory method" is ambiguous (JavaScript has a different meaning for that) so I am providing the snippet that the book has, in order to make my question clear. Here is the code:
interface Service {
void method1();
void method2();
}
interface ServiceFactory {
Service getService();
}
The Service interface is just a normal interface. ServiceFactory interface looks like a normal interface but it is a "Factory Method". What's that? What does it solve and why I should use them?
A factory method is simply a method that encaspulate the creation of an object. Instead of using the new operator as you normally would for creating an instead of a Service, in your example, you're using the factory method on some object.
ServiceFactory sf = new ServiceFactoryImpl();
// factory method
Service s = sf.getService();
To better illustrate the role of the method, it could be called createService instead. Now the method encapsulates the details of the creation of a Service, you can provide many flavors of the methods (by overloading), you can have it return different subclasses depending on the context, or parameters passed to the factory method.
A "factory method" is a method that constructs an object.
More specifically, the term usually refers to a static method that returns an instance of its declaring class (either a direct instance, or an instance of a subclass). In my experience, there are a few cases where that's particularly commonly done:
If you need to have multiple different constructors, using factory methods lets you give them appropriate names (whereas calls to different constructors can only be distinguished by the argument-types, which aren't always obvious at a glance).
If you need to have a few different implementations of a single abstract class that serves as the entry-point, the factory method can instantiate the appropriate subtype.
If you need any sort of caching logic or shared instances, the factory method can handle that, returning an already-existing instance if appropriate.
If you need to do some work with side effects, a factory method can be named in such a way that it's more clear what those side effects are.
So, your example doesn't really involve a "factory method" IMHO, but you can cheat a bit and describe getService() as one. (Rather, I would just describe ServiceFactory as a "factory" at leave it at that.) The benefits of ServiceFactory.getService() are the same as those of a factory method, plus the usual benefits of having an instance instead of a static method.

If I use abstract class instead of interface while implementing factory pattern. Would it still be a factory pattern?

For example : http://www.tutorialspoint.com/design_pattern/factory_pattern.htm
If I change interface shape on abstract class Shape, make concrete classes to extend Shape and Make the Shape factory return Shape abstract class typed objects. Is it still going to be a factory pattern ?
I would go with yes.
Lets look at definition of Factory method pattern:
the factory method pattern is a creational pattern which uses factory methods to deal with the problem of creating objects without specifying the exact class of object that will be created
The motivation behind this pattern is to separate object creation from the client using the object. Client should provide specification to factory but details how the object is built are abstracted away by the factory.
If this is an interface or abstract class is an implementation detail specific to situation, as long as your implementation of the factory lets you achieve the motivation behind pattern.
Consider using abstract classes if any of these statements apply to your situation:
You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
Consider using interfaces if any of these statements apply to your situation:
You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
You want to take advantage of multiple inheritance of type.
In some implementations it might even make more sense to use abstract class rather then interface for the Products created by the factory. If there is shared set of features/behavior between all products then it does make sense to put these into base abstract class. This could apply even if products are built from different factories.
It boils down to: do you wish to and does it make sense to introduce coupling
between products or not?
In the end, client will get same result - Product built based upon specification, with details of construction abstracted away.
When it comes to these kind of differences, the answer can always be both yes and no. Design patterns are not any kind of precise specification, they are more like a set of best and recommended practices and their implementation varies from case to case.
In my opinion the answer is no, technically this would not be a factory pattern. And it does not have to be, as long as it solves your use case and makes the code readable and maintainable (trying to literally adhere to design patterns often leads to misusing them and to over-architecturing).
If we look at the Abstract Factory Pattern (right below the Factory Pattern in the linked page), we'll see that it is a factory for creating factories. Now suppose that we have two Shape factories that can be created by the AbstractFactory: ShapeFactory2D and ShapeFactory3D, both producing Shape objects.
If Shape were abstract class, then you would force both 2D and 3D objects to inherit the same implementation, although it might make no sense (they could be implemented in totally different ways).
So, technically, in order for this to really be a factory pattern, there must exist no assumptions about the implementation details, meaning abstract classes containing partial implementation should not be used at the factory interface level.
Of course you can have Abstract2DShape and Abstract3DShape abstract classes implementing Shape; the point is that you are able to create and use Shape without being aware whether it is a 2D or a 3D shape.

What is the difference between Factory and Strategy patterns?

Can any one explain the difference between factory and strategy patterns?
For me both are looking same other than an extra factory class (which create an object of product in factory patterns)
A factory pattern is a creational pattern. A strategy pattern is an operational pattern. Put another way, a factory pattern is used to create objects of a specific type. A strategy pattern is use to perform an operation (or set of operations) in a particular manner. In the classic example, a factory might create different types of Animals: Dog, Cat, Tiger, while a strategy pattern would perform particular actions, for example, Move; using Run, Walk, or Lope strategies.
In fact the two can be used together. For example, you may have a factory that creates your business objects. It may use different strategies based on the persistence medium. If your data is stored locally in XML it would use one strategy. If the data were remote in a different database, it would use another.
The strategy pattern allows you to polymorphically change behavior of a class.
The factory pattern allows you to encapsulate object creation.
Gary makes a great point. If you are using the principle of coding to abstractions rather than "concretions" then a lot of the patterns start looking like variations on a theme.
Just to add to what tvanfosson said, a lot of the patterns look the same as far as implementation. That is, a lot have you create an interface where perhaps there wasn't one before in your code, and then create a bunch of implementations of that interface. The difference is in their purpose and how they are used.
First of all a difference between simple factory and abstract factory must be made. The first one is a simple factory where you only have one class which acts as a factory for object creation, while in the latter you connect to an factory interface (which defines the method names) and then call the different factories that implement this interface which are supposed to have different implementations of the same method based on some criteria. For example, we have a ButtonCreationFactory interface, which is implemented by two factories, the first WindowsButtonCreationFactory (creates buttons with Windows look and feel) and the second LinuxButtonCreationFactory (creates buttons with Linux look and feel). So both these factories do have the same creation method with different implementations (algorithms). You can reference this in runtime based on the method that you type of button that you want.
For example if you want buttons with Linux look and feel:
ButtonCreationFactory myFactory = new LinuxButtonCreationFactory();
Button button1 = myFactory.createButton(...);
or if you want Windows buttons
ButtonCreationFactory myFactory = new WindowsButtonCreationFactory();
Button button1 = myFactory.createButton(...);
Exactly in this case, it results in a kind of strategy pattern, since it differentiates algorithms for doing some creation. However, it differs from it semantically because it is used for OBJECT CREATION rather than operational algorithms. So, basically with abstract factory you have object creation using different strategies, which makes it very similar to the strategy pattern. However the AbstractFactory is creational, while the Strategy pattern is operational. Implementation wise, they result to be the same.
The Factory ( method ) Pattern.
Create concrete instances only. Different arguments may result in different objects. It depends on the logic etc.
The Strategy Pattern.
Encapsulate the algorithm ( steps ) to perform an action. So you can change the strategy and use another algorithm.
While both look like very similar, the purpose is rather different, one purpose is to create the other is to perform an action.
So. If your Factory method is fixed, you may have it like this:
public Command getCommand( int operatingSystem ) {
switch( operatingSystem ) {
case UNIX :
case LINUX : return new UnixCommand();
case WINDOWS : return new WindowsCommand();
case OSX : return new OSXCommand();
}
}
But suppose your factory needs more advanced or dynamic creation. You may add to the factory method an strategy and change it without having to recompile, the strategy may change at runtime.
Factory (and FactoryMethod returned by Factory):
Creational pattern
Based on inheritance
Factory returns a Factory Method (interface) which in turn returns Concrete Object
You can substitute new Concrete Objects for interface and client (caller) should not be aware of all concrete implementations
Client always access interface only and you can hide object creation details in Factory method
Have a look at this wikipedia article and javarevisited article
Strategy pattern:
It's a behavioural pattern
It's based on delegation
It changes guts of the object by modifying method behaviour
It's used to switch between family of algorithms
It changes the behaviour of the object at run time
Example:
You can configure Discount strategy for a particular item ( AirFare ticket or ShoppingCart item). In this example, you will offer 25% discount to an item during July - December and No discount on the item during Jaunary - June.
Related posts:
Real World Example of the Strategy Pattern
Design Patterns: Factory vs Factory method vs Abstract Factory
To extend on what Oscar said and in reference to his code:
The getCommand is the Factory and the UnixCommand, WindowsCommand and OSXCommand classes are Strategies
Strategy pattern in simple terms is more of runtime creation of behaviour where you are not concerned with the implementing class. On the other had factory is runtime creation of concrete class instance and it is up to you to use any behaviour(method) exposed by the implemented interface.
Factory pattern is a creational pattern, which is created with specified properties(behaviour). while at run time after creation u cn't change it's properties(behaviour). so if u need different properties(behaviour) u have to delete the object and create new object with needed properties(behaviour). which is not gud.
while in case of strategy pattern u can change the properties(behaviour) at run time.
You cannot understand the difference simply by looking at the code or categorization. To grasp the GoF patterns correctly, look for their intents:
Strategy: "Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it."
Factory Method: "Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses."
And here's an elaborate explanation about the intents and the differences between these two patterns: Difference between Factory Method and Strategy design patterns
The key difference between Factory Pattern and Strategy Pattern is where the operation is done. Factory Pattern does the operation on the created objects (the factory class done the job after creation), whereas Strategy Pattern does the operation on the context class itself.
To change a Factory Pattern to a Strategy Pattern, instead of returning the created object from the factory class, holding the object inside a context class, and creating a wrapper method inside the context class to do the operation instead of doing the operation directly from the created object.
While somebody may ask if we can do the operation on the created object, why do we still need to create a wrapper to do at context class? OK, the key thing is the operation. Strategy Pattern can alter the operation based on the strategy, and you don't need to alter the object, you can rely on the context object to do different operations instead of changing the object itself.
I may digress with Oscar in that his example of a Factory implementation is rather tightly coupled and very closed, no wonder your pick is Strategy pattern. A Factory implementation should not depend on any fixed number of specific classes being instantiated, For example:
public Command getCommand( int operatingSystem ) {
return commandTable.get(operatingSystem);
}
...
public class WindowsCommand implements Command {
...
static {
CommandTable.getInstance().registerCommand(WIN_COMMAND_ID, new WindowsCommand());
}
}
I guess the most appropriate criteria to choose one or another is mostly the terms you employ to name your classes and methods, taking into account we all should tend to program to interfaces and not to classes and also focus on the goal: we aim to determine which code will execute on runtime. That said, we can achieve the goal by using any of both patterns.
Strategy and Factory are different purposes. In strategy you have the approach defined, using this pattern you can interchange the behavior (algorithms). Coming to Factory there are lot of variations around. But the original pattern from GO4 states factory leaves creation of object to child class. Here with the factory you are replacing complete instance not the behavior you are interested in. By this you will be replacing complete system not the algorithm.
In brief:
Factory is for create multi object that has same behaviour but Strategy is for One Object that has different way to work.
Factory Pattern is about deciding which Object to create, but Strategy Pattern is about using the created object. For example, which strategy is to use can be decided by Factory Pattern

Categories

Resources