Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use activator and when to use factory method?

Tags:

c#

I have learnt the factory method design pattern, and at the same time, I have come across the Activator object and how to use it, from reading a tutorial (I have come across this object in intellisense a lot thougha).

Activator allows late binding, which can be extremely useful. But this is because we don't know what class we want to instantiate. Likewise, the factory method deals with the same problem in software engineering.

At a simple level, a bunch of ifs or a case statement and then instantiating an object based on the if condition is an implementation of the factory method, right?

On on a related topic, I have read that polymorphism can reduce coupling between objects by eliminating case statements. Is there an example of this?

Thanks

like image 318
GurdeepS Avatar asked Jan 24 '23 00:01

GurdeepS


1 Answers

If you know at compile time all of the potential classes you would want to instantiate, use the Factory pattern, it will be faster and lets the compiler check your type safety.

On the other hand, if you don't know all of the classes that might need to be instantiated (for example, if you are trying to provide a plugin architecture), your only option is to use Activator.

The simple rule of thumb here is this: Choose a factory over using Activator (or any other type of runtime binding) as long as the scenario allows it.

like image 198
Jon Norton Avatar answered Feb 16 '23 11:02

Jon Norton