Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract Factory design pattern to create objects? Why can’t we just use the new operator?

why do we need a Abstract Factory design pattern to create objects? Why can’t we just use the new operator? answer is, to avoid tight coupleing of the objects. But I didn't understand how ? can anyone explain with code (will be very useful).

what makes abstract factory design pattern useful and when.

Thanks in advance. Harsha T

like image 536
Harsha Avatar asked Jun 03 '10 14:06

Harsha


People also ask

Why should we use Abstract Factory design pattern?

Abstract factory pattern implementation provides us with a framework that allows us to create objects that follow a general pattern. So at runtime, the abstract factory is coupled with any desired concrete factory which can create objects of the desired type.

Which design pattern would you use when you want a client to create a new object without explicitly specifying the class of the new object?

In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly specifying their classes.

Is a factory or a template to create new objects of same type?

Factory Method is to creating objects as Template Method is to implementing an algorithm. A superclass specifies all standard and generic behavior (using pure virtual "placeholders" for creation steps), and then delegates the creation details to subclasses that are supplied by the client.

What are the consequences of applying the Abstract Factory pattern?

Abstract-Factory Pattern { consequence: The Abstract Factory pattern has the following beneets and liabilities: 1. It isolates concrete classes. 2. It makes exchanging product families easy.


2 Answers

If you use the new operator, you have to specify which exact type you want. Sometimes you want to be more generic, for example because you want to be able to change that instantiated type in all the codebase quickly.

like image 90
Bastien Léonard Avatar answered Sep 26 '22 00:09

Bastien Léonard


An abstract factory design pattern is designed to create an object with a specific setup at initialization time. For example if you have a lot of similarly connected classes, rather than repeating the same 4+ lines [and using copying and pasting], the abstract factory would allow for you to keep the 4+ lines in a single location and reduce the amount of changes needed.

Reference For Abstract Factory

like image 21
monksy Avatar answered Sep 25 '22 00:09

monksy