Why factory pattern




















Factory methods should be considered as an alternative to constructors - mostly when constructors aren't expressive enough, ie. Factory classes are useful when you need a complicated process for constructing the object, when the construction need a dependency that you do not want for the actual class, when you need to construct different objects etc. One situation where I personally find separate Factory classes to make sense is when the final object you are trying to create relies on several other objects.

The simplest method to achieve this is having each object create their children on their construct method, but if the properties are relatively nested, when your House fails creating you will probably spend some time trying to isolate exactly what is failing. Here if the process of creating a House fails there is only one place to look, but having to use this chunk every time one wants a new House is far from convenient.

Enter the Factories:. Thanks to the factory here the process of creating a House is abstracted in that you don't need to create and set up every single dependency when you just want to create a House and at the same time centralized which makes it easier to maintain.

There are other reasons why using separate Factories can be beneficial e. It is important to clearly differentiate the idea behind using factory or factory method. Both are meant to address mutually exclusive different kind of object creation problems.

First thing is that, when you are developing library or APIs which in turn will be used for further application development, then factory method is one of the best selections for creation pattern. Reason behind; We know that when to create an object of required functionality s but type of object will remain undecided or it will be decided ob dynamic parameters being passed.

Now the point is, approximately same can be achieved by using factory pattern itself but one huge drawback will introduce into the system if factory pattern will be used for above highlighted problem, it is that your logic of crating different objects sub classes objects will be specific to some business condition so in future when you need to extend your library's functionality for other platforms In more technically, you need to add more sub classes of basic interface or abstract class so factory will return those objects also in addition to existing one based on some dynamic parameters then every time you need to change extend the logic of factory class which will be costly operation and not good from design perspective.

On the other side, if "factory method" pattern will be used to perform the same thing then you just need to create additional functionality sub classes and get it registered dynamically by injection which doesn't require changes in your base code. They're also useful when you need several "constructors" with the same parameter type but with different behavior. Problem statement: Create a Factory of Games by using Factory Methods, which defines the game interface.

Game is the interface for all type of games. It defines complex method: createGame. Chess, Ludo, Checkers are different variants of games, which provide implementation to createGame.

GameFactory pre-creates different type of games in constructor. It implements IGameFactory factory method. Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses. When to use: Client doesn't know what concrete classes it will be required to create at runtime, but just wants to get a class that will do the job.

It's really a matter of taste. Factory classes are useful for when the object type that they return has a private constructor, when different factory classes set different properties on the returning object, or when a specific factory type is coupled with its returning concrete type. If you only have one class that's consuming the factory, then you can just use a factory method within that class. Consider a scenario when you have to design an Order and Customer class.

For simplicity and initial requirements you do not feel need of factory for Order class and fill your application with many 'new Order ' statements. Things are working well. Now a new requirement comes into picture that Order object cannot be instantiated without Customer association new dependency. Now You have following considerations. Not acceptable. Not a good practice and real pain. Instead If you have created a factory for Order Class you only have to change one line of code and you are good to go.

I suggest Factory class for almost every aggregate association. Hope that helps. Any class deferring the object creation to its sub class for the object it needs to work with can be seen as an example of Factory pattern. In other words, it's easier to change things if you use factory method than if you use a simple factory known as factory class.

Now, imagine that you want to bring a new Animal. In Factory class you need to change the Factory but in the factory method, no, you only need to add a new subclass.

Factory classes are more heavyweight, but give you certain advantages. In cases when you need to build your objects from multiple, raw data sources they allow you to encapsulate only the building logic and maybe the aggregation of the data in one place. There it can be tested in abstract without being concerned with the object interface. I have found this a useful pattern, particularly where I am unable to replace and inadequate ORM and want to efficiently instantiate many objects from DB table joins or stored procedures.

I liken factories to the concept of libraries. For example you can have a library for working with numbers and another for working with shapes. You can store the functions of these libraries in logically named directories as Numbers or Shapes. These are generic types that could include integers, floats, dobules, longs or rectangles, circles, triangles, pentagons in the case of shapes. The stated purpose of the Factory Patterns is: Define an interface for creating an object, but let subclasses decide which class to instantiate.

Factory Method lets a class defer instantiation to subclasses. So let's say that you are building an Operating System or Framework and you are building all the discrete components. I am not an expert. Imagine you have a different customers with different preferences.

Someone need Volkswagen another one Audi and so on. One thing is common - it's a car. To make our customer happy we need a factory. The factory only should know which car the customer want and will deliver such car to customer. If later we have some another car we can easily extend our car park and our factory. If I want to instantiate in many places, I don't have to repeat my condition, so when I come to add a new class, I don't run the risk of missing one.

I can write 3 tests for the factory, to make sure it returns the correct types on the correct conditions, then my calling class only needs to be tested to see if it calls the factory and then the required methods on the returned class.

It needs to know nothing about the implementation of the factory itself or the concrete classes. When someone decides we need to add a new class D to this factory, none of the calling code, neither unit tests or implementation, ever needs to be told. We simply create a new class D and extend our factory method. This is the very definition of Open-Closed Principle. You can even create a new factory class and make them hot-swappable, if the situation requires it -- for example, if you want to be able to switch class D on and off, while testing.

I have run into this situation only once, but it was extremely useful. As has been said, the Factory Pattern isn't always the way to go. But, wherever you see conditional instantiation, you should give it a moment's thought. A factory pattern is usually more complex than that. Instead, when you don't use the factory, you would have that code repeatedly used in several locations in your code. As an example consider the following: you need to load data from a DB, but you have one central DB for integration with lots of data, and one smaller one in memory on each dev-PC.

In your code you ask a factory to get a DB-handle and the factory returns one of those depending on e. The places that need an implementation of the product do not need to know how to construct one. The factory holds that information. Do you want to know what arguments to pass to the particular constructor?

Or what dependencies you have to inject? Or how to register the implementation class with the database after it is fully configured? Let the factory look after all that stuff. The places that need an implementation of the product do not need to know at the time of module description i. This is much more flexible. The downside is that where you know what to make and how to do it, you get more complexity when you use a factory.

The fix to that is simple though: don't use a factory when it doesn't make sense! I have come across numerous cases where a Factory class is coded when a simple constructor would be adequate. I would like to think about design patterns in terms of classes being as 'people,' and patterns are ways that people talk to each other.

So, to me the factory pattern is like a hiring agency. You've got someone that will need a variable number of workers. This person may know some info they need in the people they hire, but that's it. So, when they need a new employee, they call the hiring agency and tell them what they need. Now, to actually hire someone, you need to know a lot of stuff - benefits, eligibility verification, etc.

But the person hiring doesn't need to know any of this - the hiring agency handles all of that. In the same way, using a Factory allows the consumer to create new objects without having to know the details of how they're created, or what their dependencies are - they only have to give the information they actually want.

Use Factory Method when instantiating a subclass and the client code isn't supposed to be responsible for deciding which particular subclass is instantiated. It is useful because it prevents you from having to change client code when you need to change what class gets instantiated. Changing existing code is bad practice because it is typically error prone. An example would be having subclasses, where each one sorts data in ascending order, but in a different way.

Each way is optimal for a particular kind of data. Each product can be made up of any number of components in their inventory. The Factory Method pattern is a design pattern used to define a runtime interface for creating an object. Assume you have a ProductFactory class which creates a new type of product:.

By defining build as a factory method, you now have an interface through which you can create different products on the fly.



0コメント

  • 1000 / 1000