Factory & Strategy patterns - java

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.

Related

Strategy Pattern using java 8 and service injection

I'm trying to implement the Strategy Pattern for some custom validation that doesn't involve only validation input with basic operations but I do need to call some other services to validate the data.
At the beginning I used the example mentioned here which uses enums to have different strategies but of course it was not possible to inject my services in the enum so now I'm looking at this that leverages to java 8 for more clarity.
My idea is to have an interface with has one method validate() and have generic input for different objects I could send it and then a class implementing that interface that would have different validations based on object type and dispatches requests to different services, but on the other hand I'm kinda loosing the enum advantage on having different strategies which I could select for instance based on specific user settings.
Any idea how to have both of these advantages?
I would say that enums and the strategy pattern don't really mix.
The ideal use case for an enum is something that represents an exhaustive set of choices. DayOfWeek representing Monday to Sunday, for example. The problem with using this, in addition to not being able to autowire any other beans, is that your enum will continue to grow as the number of validations increase.
The strategy pattern allows you to use a potentially infinite number of possible strategies, provided it obeys the contract. Take Collections.sort(List<T> list, Comparator<? super T> c), for example. There could be no exhaustive list of possible comparators, because it could never fulfill everyone's use-cases.
It makes more sense to define each of your possible strategies as a component
#Component
class NonNullValidationStrategy implements ValidationStrategy {
private final MyService service;
//constructor
#Override
public boolean isValid(MyClass foo) {
return foo != null;
}
}
How you would obtain an instance of the right strategy when you need it will depend on details you haven't provided. Maybe autowiring with a qualifier is a possibility.
Spring already has it's own way of defining validations, via interfaces and annotations. I suggest you pursue that before rolling your own solution.
It'd like to suggest using javax.validation groups, see more about it here especially #Validated(OnCreate.class)
If you want to apply strategy pattern at the controller level and deeper than see this article and especially my comment, because there is described not a pretty clean solution.

Abstract Factory Design: Replacing if else with enum

When we use Abstract Factory Pattern, we generally have FactoryMaker class which has a getFactory function in which we pass argument and we have switch or if-else logic in the function on the passed parameter to decide which factory to return. Is creating passed parameter an enum or an object and then having the logic of which factory to return inside those object will be better. For example :
Let us say this us our factory maker which are passed enum CountryCode to decide factory.
public class FacoryMaker {
public final static FacoryMaker fctry= new FacoryMaker();
public static RetailFactory getFactory(CountryCode code){
RetailFactory rt = null;
if(code == CountryCode.UK){
rt = new UKFactory();
}
if(code == CountryCode.US){
rt = new USFactory();
}
return rt;
}
}
Instead of this we will have :
public class FacoryMaker {
public final static FacoryMaker fctry= new FacoryMaker();
public static RetailFactory getFactory(CountryCode code){
return code.getFactory();
}
}
and enum will be modified like this:
public enum CountryCode {
US(){
#Override
public RetailFactory getFactory() {
return new USFactory();
}
},
UK(){
#Override
public RetailFactory getFactory() {
return new UKFactory();
}
};
public abstract RetailFactory getFactory();
}
But I don't see this being followed generally. Why is it so? Why can't we make the passing parameter always an object and have the logic inside the object of which factory to get? Can it fail under any abstract factory design. It looks very generic to me. Also by this it is possible to even remove the factory maker and use the object directly to get the Factory instance.
When designing software, one aspect to consider is Separation of Concerns it doesn't sound very reasonable to me to let a CountryCode create a RetailFactory. Both concepts have a pretty low cohesion towards each other, which should be avoided.
Further, if you already have a country code, why would you need a factory at all, what's preventing you to call the getFactory method directly? It simply makes no sense.
The CountryCode is merely a hint for the FactoryMaker's getFactory method, how to create the factory. It may even completely ignore the country code. What if there is a country without a RetailFactory? Do you return null? a DefaultFactory or the Factory of another country?
Of course it is possible to do it that way, but if you look at your code a half year from now, you may think "Wtf? Why the heck did I create the Factory in the Country Code?!"
Besides, the first example you provided seem to be more of a Factory Method than a Factory because the FactoryMaker is not used at all.
I think that Abstract Factory is a general pattern for all OOP languages. When people describe it, they should show a general implementation which is possible to be applied in all of those languages. Then people follow the pattern, they follow genernal implementation.
And your implementation is using Enum which is specifically supported in Java but not other OOP languages.
Very often in practice, factory methods don't know in advance the implementations. The implementing classes may not exist at the time the factory is created. This is the case for example in service provider frameworks such as the Java Database Connectivity API (JDBC). JDBC defines the interfaces that service providers must implement, but the concrete implementations are not known in advance.
This framework allows adding implementations later, for example for database drivers of new cutting edge databases.
The service provider framework includes a provider registration API to register implementations (ex: DriverManager.registerDriver), and a service access API for clients to obtain an instance of the service (ex: DriverManager.getConnection).
It is common to instantiate the service implementation using reflection (ex: Class.forName("org.blah.Driver")).
Your example is different. You know all the implementation classes you intended.
And you are not considering (yet) the pluggability of other implementations.
Whether you create the instances using a switch or an enum,
it makes little difference.
Both alternatives are fine, equivalent.
Another related alternative is that the various methods in Collections do, for example Collections.emptyList(), Collections.singletonList(...), and so on.
The implementations are not decided by a switch,
but have explicit names by way of using specialized methods.
When you want to make it possible to use implementations of your interfaces not known in advance, and not hard-coded in your factory, look into service provider frameworks such as JDBC.
But I don't see this being followed generally. Why is it so?
Your technique only works because you know all the implementations of RetailFactory in advance.
In frameworks like JDBC, all the implementations of Driver, Connection, and so on, are not known in advance, for all the databases out there, so using such technique with a single enum referencing all implementations is not possible, and not scaleable. So they use a different mechanism, to register and load implementations dynamically at runtime.
Why can't we make the passing parameter always an object and have the logic inside the object of which factory to get?
You can. If you don't need dynamic loading of implementations like JDBC (and most probably don't), your way of using enums has some advantages.
For example, your original implementation does rt = ..., which is not as good as doing return .... Such "mistake" is not possible using your enum solution. On the other hand, if you want dynamic loading, then using an enum will not make much sense.
The bottomline is, there is no big difference between the two alternatives you presented. Both are fine.

Need a way to define input arguments for constructor in interface

First of all, I know it isn't possible to define constructors in interfaces in Java. But somehow, I've run into a problem where I need something very similar. Maybe there is an easy solution for my case...
I have an interface:
public interface SomeObject {
/**
* Generate a xml representation of the object.
*/
public String generateXMLRepresentation();
}
This xml-representation of the object will be stored somewhere and later on it should be possible to construct a copy of the object using this xml-representation. My intial thought was to define a constructor which takes a String as input and let every implementation of SomeObject know how to handle it and how to construct the corresponding object.
How can I achieve this?
Edit: Either I wasn't clear enough about that or I think about it the wrong way but I think that Factory or Builder patterns won't work. I need something stronger where everyone can write a new implementation of SomeObject and is forced to implement an constructor which takes an xml string. To put it another way, I do not how many or which implementations of SomeObject exist and still, I'm relying on that every implementation knows how to construct itself from an xml-representation.
I believe for this you should use the Factory pattern, since we are talking about building up an object based on a string.
So you should have different static methods constructing different implementations for a given String.
public class ObjV1 implements SomeObject(){ // objects would simply extend interface
...
}
public class SomeObjectFactory{// factory would provide construction methods for different implementations of the interface
//Hide factory constructor, so we use it only as a singleton
private SomeObjectFactory(){
}
public static ObjV1 buildV1(String str){
ObjV1 obj = new ObjV1(); // note that we're using the noarg constructor
...
return obj;
}
}
If you want to have more control over the building process, you should give the Builder pattern a try
Some Design Patterns can help you to define a solution that can handle your current context. Both the Abstract Factory and the Builder pattern can help you.
I'd rather go with the Builder design pattern. You'll end up being able to construct from simple to complex objects based solely on that XML representation you have by implementing the proper logic.
I think you should consider separating the concern of xml serialisation from whatever concern your object is dealing with. Is knowledge of to and from xml really intrinsic to the domain of your class, or is it an orthogonal concern?
Have a look at http://x-stream.github.io/
If you do not want to use xstream itself, because you can't depend on the jar, or your xml form is particular to your project, at least look at what xstream does. You should be able to define a single strategy to (reflectively?) recurse an object structure and write out xml in the form you require, and a companion class to do the opposite.

Is this right usage of factory pattern?

Got design problem, maybe you can help to decide.
My client object can ask for set of objects of class Report. There is defined set of available reports and according to client's permissions different reports can included in returned set. Reports are created per request (every client gets brand new report instances on each request).
Should I use kind of "factory" that will encapsulate reports creation like below:
public class ReportsFactory {
private UserPermissionsChecker permissionsChecker;
public Set<Report> createReports() {
Set<Report> reports = new HashSet<Report>();
if(permissionsChecker.hasAccessTo('report A')) {
reports.add(createReportA());
}
if(permissionsChecker.hasAccessTo('report B')) {
reports.add(createReportB());
}
if(permissionsChecker.hasAccessTo('report C')) {
reports.add(createReportC());
}
return reports;
}
private Report createReportA() {...}
private Report createReportB() {...}
private Report createReportC() {...}
}
Is this right usage of so called simple Factory pattern? Or do you have other suggestions?
** EDIT **
Some comments below say it's not exactly Factory pattern. If not, how could I call that?
I think the design is correct, but this is a wrong usage of the "Factory" word. In the Factory pattern, XxxxFactory creates instances of Xxxx, initializes them if required, but applies no other kind of logic.
This design here seems correct to me, but your class would rather be called ReportsService
And maybe UserPermissionsChecker would be AuthorizationService
Edit: To take into account criticism against the word "Service".
There is currently a quite widespread (I did not say universal) convention in the java world, which consists in having:
A purely descriptive business-model implemented by classes emptied of all logic called (maybe mistakenly) POJOs
All business logic mainly related to an object Xxx implemented in a procedural style in the methods of a class called XxxService.
I personally don't agree with this coding style and I prefer object oriented programming, but whether we like it or not, this convention exists in the Java EE world and has it's coherence.
Judging bye the coding style of the class submitted by the OP, I inferred that he followed this procedural approach. In that situation, it's better to follow the existing convention and call the class that serves as a container for the procedural code which handles Reports a ReportService.
To me this looks a bit of a builder pattern, in a sense you have an object, that you build its data to.
This is in contrast to a factory, where usually returns different concrete types of created objects,
And usually the construction of the data of these objects is done in the CTORs of the concrete classes that objects of them are returned from the factory.

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