Question

I've seen that few occasion, the .NET Framework provides the Factory version of method, e.g.:

vs.

How do we make choice on which one to use and which one is better than other?

Was it helpful?

Solution

On this occasion, as Scott Chamberlain says in the comment, DataCacheFactory is provided as a means of creating or getting a default DataCache object. There is no other way for this class, due to the lack of DataCache public constructors.

However, in some cases, you do have a choice. Take System.Threading.Task for example. You can create using the constructor, or using a TaskFactory.

The reason why both are provided in some cases is that factories can simply be more useful. A factory can provide you with a pre-created object with certain useful properties set. This can save you from having to specify them every time you want a new object.

As an example: with the Task class, you could do:

var task = new Task(yourAction);

Or, you can create a TaskFactory as follows:

var taskFactory = new TaskFactory(yourCancellationToken);

And when you call:

var task = taskFactory.StartNew(yourAction);

your created Task is:

  1. associated with the desired cancellation token
  2. started with the specified Action

Using the TaskFactory, you don't need to create the Task, then populate all these properties, then start the Task yourself. The factory does it for you.

OTHER TIPS

You use DataCacheFactory to create DataCache objects. There is no dilemma - use them both.

These two things are not mutually exclusive -- you need to use them both. You are seeing the Factory Pattern.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top