Lec_8 Java Design Patterns P2 (1)
Lec_8 Java Design Patterns P2 (1)
Presented By
Assis. Prof. Abdalla Moustafa
DATE : 07/05/2024 1
The Factory Pattern
2
The Factory Pattern
3
When to Use a Factory Pattern
• You should consider using a Factory pattern when:
• A class can’t anticipate which kind of class of objects it must
create.
• A class uses its subclasses to specify which objects it creates.
• You want to localize the knowledge of which class gets created.
5
Abstract Factory pattern
• The Abstract Factory pattern is one level of abstraction higher
than the factory pattern.
• This pattern returns one of several related classes, each of which
can return several different objects on request.
• In other words, the Abstract Factory is a factory object that
returns one of several factories.
• One classic application of the abstract factory is the case where
your system needs to support multiple “look-and-feel” user
interfaces, such as Windows, or Macintosh:
• You tell the factory that you want your program to look like
Windows and it returns a GUI factory which returns
Windows-like objects.
• When you request specific objects such as buttons, check
boxes and windows, the GUI factory returns Windows
instances of these visual interface components.
6
A Garden Maker Factory
- Suppose you are writing a program to plan the layout of gardens.
- These could be annual gardens, vegetable gardens or perennial gardens.
- However, no matter which kind of garden you are planning, you want to ask
the same questions:
▪What are good border plants?
▪What are good center plants?
▪What plants do well in partial shade?
8
A Garden Class
A Garden class simply returns one kind of each plant. So,
for example, for the vegetable garden we simply write:
class GardenMaker {
//Abstract Factory which returns one of three gardens
private Garden gd;
public Garden getGarden(String gtype) {
gd = new VegieGarden(); //default
if(gtype.equals("Perennial"))
gd = new PerennialGarden();
if(gtype.equals("Annual"))
gd = new AnnualGarden();
return gd;
}
}
10
Consequences of Abstract Factory
- One of the main purposes of the Abstract Factory is that
it isolates the concrete classes that are generated.
- The actual class names of these classes are hidden in the
factory and need not be known at the client level at all.
- Because of the isolation of classes, you can change or
interchange these product class families freely.
- Since you generate only one kind of concrete class, this
system keeps you for inadvertently using classes from
different families of products.
- While all of the classes that the Abstract Factory
generates have the same base class, there is nothing to
prevent some derived classes from having additional
methods that differ from the methods of other classes.
11
12