mxmissile
mxmissile

Reputation: 11672

Should Factories Persist Entities?

Should factories persist entities they build? Or is that the job of the caller? Pseudo Example Incoming:

    public class OrderFactory
    {
      public Order Build()
      {
        var order = new Order();
        ....
        return order;
      }
    }

public class OrderController : Controller
{
    public OrderController(IRepository repository)
    {
       this.repository = repository;
    }

    public ActionResult MyAction()
    {
       var order = factory.Build();
       repository.Insert(order);
       ...
    }
}

or

public class OrderFactory
{
  public OrderFactory(IRepository repository)
  {
     this.repository = repository;
  }

  public Order Build()
  {
    var order = new Order();
    ...
    repository.Insert(order);
    return order;
   }
}

public class OrderController : Controller
{
  public ActionResult MyAction()
  {
     var order = factory.Build();
     ...
  }

}

Is there a recommended practice here?

Upvotes: 0

Views: 488

Answers (3)

code4life
code4life

Reputation: 15794

If you decide to use a factory for singleton objects, you will need to manage the persistence of the singleton object. Other than that, I can't see why you'd want to have factories manage persistence.

Actually, having factories manage persistence - with the exception of when singletons are involved - would lead to the very opposite of proper separation of concerns, which is the raison d'etre for using factories in the first place.

Upvotes: 1

zincorp
zincorp

Reputation: 3282

The Factory's main purpose is the creation of objects. Once that object has been created it's up to you to decide what you want to do with it.

The only case where this would be different is if there's also a requirement that only once instance of the created object should exist, in which case you'll have some kind of pseudo-factory-singleton hybrid pattern going on.

Upvotes: 1

Tom Cabanski
Tom Cabanski

Reputation: 8018

As a general rule the factory has only one responsibility: create an instance and return it. I would not mix in persistence. I would view it as the responsibility of another class. In this case, it would be the controller.

Upvotes: 7

Related Questions