Last post May 29, 2010 01:27 PM by DigiMortal
May 17, 2010 05:37 PM|Ed_Chiu|LINK
I am having troubles understanding the purposes of using Factory pattern, I understand Factory pattern uses Factory class that has methods to return concrete objects. But why don't I simply use new opertor to create concrete objects? Some articles suggest
Factory methods could return objects of different concreate classes, I can do the same thing by using switch statement.
Also are there classes in .Net framework already implementing Factory pattern? I think that will give me a better ideas why it is useful.
May 17, 2010 06:28 PM|ignatandrei|LINK
May 18, 2010 03:48 AM|toas1|LINK
I understand your troubles and not all patterns are that easy to understand how to implement. Let me start by explaining from a real life problem. Imagine a company that deals with funds and as you might already know there are differnt kinds off funds, you
have hedge funds, equity funds etc. But since they are all funds they share the same base class. This company work from a domain model and in the repository they have a factory class that, based on the funds ID provided to the factory, it returns the correct
type of fund. This is a really good example how you can hide the complexity from the consumer, all you know is that you have an ID and that you need to fetch the fund with that ID from the repository.
And yes TIA, I agree with you aswell. "Whey use a pattern when I can do like this instead?" Thats a really good question that I think more develovers should ask themself before implementing a pattern. I see a lot a solutions where developers tried to sqeeze
in as many patterns as the could just to use patterns. not a good idea at all!
My suggestion is to "travel the fastest way" and later on, if you have a general understanding for the most commonly used patterns, you will look at your code and say to youerself "hey, this piece a code looks like it could be replaced by the xxx pattern".
And in my opinion, thats when you start using patterns in a correct way!
May 28, 2010 03:52 PM|voodoo9055|LINK
May 28, 2010 03:53 PM|voodoo9055|LINK
May 29, 2010 01:27 PM|DigiMortal|LINK
You need Factory pattern to hide details of object instantiation. Not all objects are easy to create with just using new MyClass(). There are also objects that need complex initialization and you really don't want this instantiation to happen in every place
in your code where new instance of specific class is needed.
The other context where you need Factory pattern is using object-relational mappers (O/R-mappers). To keep your code free from persistence logic you need proxy classes that are able to load child objects when they are asked. You may also write this kind
of code manually. Real-world example is Entity Framework with lazy loading. I wrote blog posting
Entity Framework 4.0: Creating objects of correct type when using lazy loading about how to use factory methods to get new instances of correct type.