What is the difference between Factory and Strategy patterns? - java

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

Related

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.

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.

Java Design Patterns - Builder and Singleton

I am fairly new to Design Patterns in programming, and I am trying to learn them by creating recipes and a meal. There can be many recipes but only one meal.
Using Builder:
Create a Recipe, which will contain a name, ingredients, etc.
Using Singleton:
Instantiate my CurrentMeal, which should contain an ArrayList<Recipe>. I also should be able to access a Recipe inside my CurrentMeal.
While I believe I understand Builder, I am not sure I understand Singleton all that well. Am I approaching this problem in an appropriate manner? If not, any suggestions as to an approach to take would be greatly appreciated. Thanks in advance.
builder pattern:
Intent:
Separate the construction of a complex object from its representation so that the same construction process can create different representations.
Key points:
Builder pattern builds a complex object using simple objects and using a step by step approach
A Builder class builds the final object step by step. This builder is independent of other objects
Replacement to Factory method/Abstract Factory in this scenario : Too Many arguments to pass from client program to the Factory class that can be error prone
Some of the parameters might be optional unlike in Factory which forces to send all parameters
UML diagram:
Builder:
Abstract interface for creating objects (product).
ConcreteBuilder:
Provides implementation for Builder. It is an object able to construct other objects. Constructs and assembles parts to build the objects
Guidelines for Builder design pattern in Java
Make a static nested class called Builder inside the class whose object will be build by Builder
Builder class will have exactly same set of fields as original class
Builder class will expose method for adding ingredients. Each method will return same Builder object. Builder will be enriched with each method call.
Builder.build() method will copy all builder field values into actual class and return object of Item class
Item class (class for which we are creating Builder) should have private constructor to create its object from build() method and prevent outsider to access its constructor.
Refer to this journaldev article for more details.
Singleton pattern:
Intent:
Ensure a class has only one instance, and provide a global point of access to it.
Encapsulated "just-in-time initialization" or "initialization on first use"
singleton should be considered in below scenarios:
Ownership of the single instance cannot be reasonably assigned
Lazy initialization is desirable
Global access is not otherwise provided for
UML diagram:
Have a look at below SE question for more details:
What is an efficient way to implement a singleton pattern in Java?
The Singleton pattern allows you to share a single instance of an object. If you would like to share your CurrentMeal property, then you can of course encapsulate it in a Singleton, although I don't really see the point. It's not really what the pattern is designed for. You might use Singleton to implement a logging mechanism, for example.
The Builder pattern is well-suited to your application, as it allows different Recipe implementations to be constructed based on similar properties.

Factory Pattern vs FactoryMethod Pattern

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.

Factory & Strategy patterns

I need to create a class which will be responsible for result set processing but it might happen that different algorithms should be used to process that result set.
I am aware of the following options:
1) Use Strategy patern, below is pseudo code:
interface Strategy {
processResultSet(ResultSet rs);
}
class StrategyA implements Strategy {
processResultSet(ResultSet rs);
}
class StrategyB implements Strategy {
processResultSet(ResultSet rs);
}
Context class will contain reference to Strategy and Client should pass the implementation of Strategy creating Context object, i.e.
class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public doSomething(rs) {
strategy.processResultSet(rs);
}
The problem is that I don't want to pass strategy object to Context but I would like to create something like StrategyFactory which will be responsible for creation of concrete Strategy implementation. It would separate Client from Strategy - is it a good design?
Is it a mix of Strategy and Factory or in fact only Factory pattern?
It's definitely a combination of Strategy and Factory - but I don't think that's bad. The patterns are intended to be combined and used with each other.
It is hard to tell with out seeing this design plan in context whether this is a good design or a bad one. With just the information you've given here it could go either way.
Seems like your head is in the right place, but let me just give you a word of warning: don't stretch too hard to separate your client from your strategy. I have done this in the past and it lead to a convoluted mess which would have been far simpler had I just allowed a little connection between the two portions of my code. Separation is good, but struggling to maintain perfect separation can lead to bad code and all kinds of problems.
We have used this is many different parsing scenarios and it certainly works. I have blogged about this with a code example: http://www.herrodius.com/blog/136
The trick we use is to give the strategy interface an extra "canProcess" method which simply returns a boolean if the strategy is able to deal with the data. The factory then simply loops through all its strategies and asks each one if it can work with the data. If one can, we return that strategy or execute the strategy.
In the scenario you depict, there wouldn't really be a need for a Context, which would instead be replaced by the Factory you desire. The strategy pattern in this case is just overhead and an unneeded layer of complexity. All you need is an interface or abstract class, implementations, and a Factory or Proxy to retrieve the implementations.
Anny comments related to my thoughts:
1) There is a Service - Singleton. 2) It contains a reference to DAO class - it is also a singleton. 3) In DAO there is a method which retrieves ResultSet: ResultSet rs = ps.executeQuery(); I would like to create an appropriate strategy inside DAO to process this result set. I can't pass this strategy in DAO constructor because it is specific for the incomming request. Passing it in the constructor would make it the same for all incomming request.
So I decided to create a Factory inside DAO (DAO object instance) and inside a method I'm going to create an appropriate strategy (based on the request - local object) from the factory and use it to process the resultset.
Is this solution good in your opinion?
I think strategy pattern should go with a factory pattern. And in a way you used it is absolutely correct. Secondly, it would be better if you kept context class as an abstract class so that you can extend different contexts as per your requirement. Rest of the things seems good but according to the example you mentioned I think it wasn't necessary but you have used it in right way.

Categories

Resources