0

Possible Duplicate:
Constructor vs. Factory in .NET Framework

I understand factory patten and have implemented it but couldn't get what benefit it will bring. For example instead of:

MyType1 obj=new Mytype1();
MyType2 obj=new Mytype2();

writing:

IMyType obj1 = Factory.Create(1);
IMyType obj2 = Factory.Create(2);

Is it something I have missed or not conceive. Can you please put your own experience example.

Community
  • 1
  • 1
haansi
  • 5,470
  • 21
  • 63
  • 91
  • 2
    If you don't find a need for it, then don't use it. – John Saunders Aug 09 '12 at 00:38
  • Also, what does "client side" have to do with it? – John Saunders Aug 09 '12 at 00:41
  • John Saundes it is Win Forms. – haansi Aug 09 '12 at 00:42
  • @John Saundes, I am feeling I dont need it but I want to realize where it will be needed. Please guide. – haansi Aug 09 '12 at 00:44
  • Did you read the other questions about the factory pattern? http://stackoverflow.com/questions/4067271/when-to-use-factory-patterns – bmm6o Aug 09 '12 at 00:48
  • 2
    Guidance: don't use it. When you can't do your job by following this suggestion, you can ask yourself whether it's not possible that you need it. Until a pattern actually solves a problem for you, don't use it. – John Saunders Aug 09 '12 at 00:53
  • Clearly, you don't understand the factory pattern. It appears you even thing that "client side" might be relevant to when to use the pattern (hint: no, it doesn't). I strongly recommend you learn patterns in terms of what problems they solve. Until you need to solve one of those problems, you do not need the pattern. – John Saunders Aug 09 '12 at 00:55
  • Your problem here is you are creating very simple objects. If you do not have any complex initialization logic which you don't want to put everywhere and pollute your code, you can live without the factory. But when you evolve your code, it may come in handy one day. – Ε Г И І И О Dec 20 '12 at 04:49

4 Answers4

3

Some benefits of the factory pattern:

  1. You can keep track of the objects you create. If you want to re-use objects or enforce a limit on the number of objects created, the factory can enforce that.
  2. You can control how objects are created. If there are some parameters used to create the objects, you can return an existing object when clients pass in the same parameters for an object that has already been created.
  3. You can have the factory return an interface but internally create different types of objects that support the interface.
Kent
  • 1,691
  • 4
  • 19
  • 27
1

Factory patterns are good for many reasons

A couple of them are:

  • you can initialise the item in the factory (default values etc) and make the item creation procedural (look at other classes/procedures, get defaults, inspect configuration values).

A constructor is one way to create an item but you can't inspect other classes or run other processes that are outside of the newly created instance without tightly coupling the class to these dependencies

  • it provides a central repository for item creation which enforces patterns/practices amongst developers in your team

Those are some of the reasons I can think of :)

e.g.

This class is dependent on the ConfigManager for instantiation

class SomeClass 
{
    public int SomeValue;

    public SomeClass() 
    {
        // Check the config for some value
        SomeValue = ConfigManager.GetDefaultInt("SomeValue");
    }
}

This class is not because it uses a factory

class SomeClass 
{
    public int SomeValue;

    public SomeClass() 
    {
    }
}

class SomeClassFactory 
{
    public SomeClass CreateSomeClass() 
    {
        SomeClass obj = new SomeClass();
        obj.SomeValue = ConfigManager.GetDefaultInt("SomeValue");
    }
}
Charleh
  • 13,749
  • 3
  • 37
  • 57
1

The benefit of the Factory pattern is that it encapsulates the details of construction and specific type from how it is used. This allows you to evolve to more interesting designs later with fewer places to make a change.

Consider this example:

public interface IStorage
{
    void Save(SomeObject toSave);
    SomeObject Get(SomeId id);
}

public class DatabaseStorage : IStorage
{
    public void Save(SomeObject toSave)
    {
       //persist to DB somehow
    }

    public SomeObject Get(SomeId id)
    {
       //get from db somehow and return
    }
}

public class StorageFactory
{
    public IStorage GetStorage()
    {
         return new DatabaseStorage();
    }
}

public class DatabaseStorage : IStorage
{
    public void Save(SomeObject toSave)
    {
       //persist to DB somehow
    }

    public SomeObject Get(SomeId id)
    {
       //get from db somehow and return
    }
}

Now imagine you later get the requirement to cache some results, or to log all results. You could create a proxy, like this:

public class LoggingStorage : IStorage
{
    private readonly IStorage _proxied;

    public LoggingStorage(IStorage proxied)
    {
        _proxied = proxied;
    }

    public void Save(SomeObject toSave)
    {
       //log this call
       _proxied.Save(toSave);
    }

    public SomeObject Get(SomeId id)
    {
       //log this call
       return _proxied.Get(id);
    }
}

Now, if you used a constructor, you have to replace every use of it to wrap it with this. If you used the factory, you only change it:

public class StorageFactory
{
    public IStorage GetStorage()
    {
         return new LoggingStorage(new DatabaseStorage());
    }
}

Of course, speculative factories can seem a little heavy handed for this, which is why I prefer to encapsulate the constructor.

tallseth
  • 3,635
  • 1
  • 23
  • 24
1

jQuery is a factory function that takes advantage of the way JavaScript works to create objects with a very low memory footprint.

Let's investigate with a horribly mutilated, drastically simplified version of jQuery to help see the potential benefits:

var $ = jQuery = (function(){ //this anon function fires once, and returns a function

//defines all kinds of internal functions jquery uses here

function jQuery(selector,context){ // we're going to return this inner JQ later
    //defines only the logic needed to decide what to do with the arguments here
    //and then builds the jQuery object with 'return new jQuery.prototype.init();'
}

//defines jQuery.prototype properties here:
jQuery.prototype = {
    //...
    init:function(selector,context){ //gets used to build the JQ objects
        this.constructor.prototype = jQuery.prototype; //hands off the function prototype
    }
    //...
}

return jQuery; //this gets assigned to the outer jQuery and $ vars

})()

So... now we have a factory function that is also something like a namespace whose prototype we can extend, and expect those methods to be available on the object it spits out. Furthermore, the objects themselves have very little weight in memory aside from the DOM objects they typically wrap because all functions are references pulled in from closure or the outer prototype object that gets handed off as a reference. Aside from a bit of logic and some state vars, everything the object needs is built when jQuery first gets parsed or handed down from the prototype object as you add new methods to factory function's prototype property.

Now, try to do that with new jQuery()

If anything, applying the factory pattern in JavaScript can be immensely and uniquely powerful.

Erik Reppen
  • 4,605
  • 1
  • 22
  • 26