Design Patterns in C++ - Creational Patterns - Scuola Superiore
Creational Patterns
description
Transcript of Creational Patterns
DESIGN PATTERNS
1
Definitions A pattern is a recurring solution to a standard problem, in a
context. Jim Coplein, a software engineer:
“I like to relate this definition to dress patterns…” What are dress patterns? “... I could tell you how to make a dress by specifying the
route of a scissors through a piece of cloth in terms of angles and lengths of cut. Or, I could give you a pattern. Reading the specification, you would have no idea what was being built or if you had built the right thing when you were finished.
The pattern foreshadows the product: it is the rule for making the thing, but it is also, in many respects, the thing itself.”
2
Types of PatternThere are 3 types of pattern …
Creational: address problems of creating an object in a flexible way. Separate creation, from operation/use.
Structural: address problems of using O-O constructs like inheritance to organize classes and objects
Behavioral: address problems of assigning responsibilities to classes. Suggest both static relationships and patterns of communication(use cases)
3
GoF Design Pattern Categories4 Purpose
Creational Structural BehavioralScope Class Factory Method Adapter Interpreter
Template MethodObject Abstract Factory
Builder Prototype Singleton
Adapter Bridge Composite
DecoratorFacade ProxyFlyweight
Chain of ResponsibilityCommand Iterator MediatorMemento Observer State Strategy Visitor
GoF Design pattern relationships 5
Elements of Design Patterns Design patterns have 4 essential
elements: Pattern name: increases vocabulary of
designers Problem: intent, context, when to apply Solution: UML-like structure, abstract code Consequences: results and tradeoffs
6
Abstract FactoryFactory Method
Creational Patterns7
Creational patterns Creational design patterns abstract the instantiation process. Design patterns that deal with object creation mechanisms,
trying to create objects in a manner suitable to the situation Make a system independent of the way in which objects are
created, composed and represented There are two recurring themes in these patterns.
First, they all encapsulate knowledge about which concrete classes the system uses.
Second, they hide how instances of these classes are created and put together.
8
Creational Patterns Abstract Factory:
Factory for building related objects Builder:
Factory for building complex objects incrementally Factory Method:
Method in a derived class creates associates Prototype:
Factory for cloning new instances from a prototype Singleton:
Factory for a singular (sole) instance
9
Benefits of creational patterns Generic instantiation – Objects are instantiated
without having to identify a specific class type in client code (Abstract Factory, Factory)
Simplicity – Make instantiation easier: callers do not have to write long complex code to instantiate and set up an object (Builder, Prototype pattern)
Creation constraints – Creational patterns can put bounds on who can create objects, how they are created, and when they are created
10
Abstract Factory11
Abstract Factory patterns work around a super-factory which creates other
factories. This factory is also called as factory of factories. In Abstract Factory pattern an interface is
responsible for creating a factory of related objects without explicitly specifying their classes.
Each generated factory can give the objects as per the Factory pattern.
12
Abstract Factory Central interface for creating objects
Uses ONLY a high level reference.
Declares an interface for each kind of widget
Concrete subclasses have implementation details
Compile Time vs. Dynamic Creation
13
Intent
Abstract Factory offers the interface for creating a family of related objects, without explicitly specifying their classes.
14
Structure and Participants AbstractFactory
Declares an interface for operations that create abstract products
ConcreteFactory Implements the operations to create concrete product objects: usuallyinstantiated as a Singleton
AbstractProductDeclares an interface for a type of product object; Concrete Factories produce the concrete products
ConcreteProduct Defines a product object to be created by the corresponding concrete factory
15
Abstract Factory: Applicability Use Abstract Factory when:
A system should be independent of how its products are created, composed, and represented
A system should be configured with one of multiple families of products
You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations
16
Implementation
We are going to create a Shape and Color interfaces and concrete classes implementing these interfaces.
We create an abstract factory class AbstractFactory as next step.
Factory classes ShapeFactory and ColorFactory are defined where each factory extends AbstractFactory.
A factory creator/generator class FactoryProducer is created.
17
Implementation AbstractFactoryPatternDemo, our demo class
uses FactoryProducer to get a AbstractFactory object.
It will pass information (CIRCLE / RECTANGLE / SQUARE for Shape) to AbstractFactory to get the type of object it needs.
It also passes information (RED / GREEN / BLUE for Color) to AbstractFactory to get the type of object it needs.
18
19
Sample Code
Abstract Factory: Consequences Good:
Isolates concrete classes All manipulation on client-side done through abstract
interfaces Makes exchanging product families easy
Just change the ConcreteFactory Enforces consistency among products
Bad Supporting new kinds of products is difficult Have to reprogram Abstract Factory and all subclasses But it’s not so bad in dynamically typed languages
20
Factory Method21
Factory Method Intent:
Define an interface for creating an object, but let subclasses decide which class to instantiate.
Factory Method lets a class defer instantiation to subclasses.
22
Factory Method Motivation:
Framework use abstract classes to define and maintain relationships between objects
Framework has to create objects as well - must instantiate classes but only knows about abstract classes - which it cannot instantiate
Factory method encapsulates knowledge of which subclass to create - moves this knowledge out of the framework
23
Applicability Use the Factory Method pattern when
a class can´t anticipate the class of objects it must create.
a class wants its subclasses to specify the objects it creates.
classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
24
FACTORY METHOD - Structure
25
Participants Product
defines the interface for objects the factory method creates.
ConcreteProduct implements the Product interface.
Creator (also refered as Factory because it creates the Product
objects) declares the method FactoryMethod, which returns a Product object. May call the generating method for creating Product objects
ConcreteCreator overrides the generating method for creating
ConcreteProduct objects
26
Advantages: The main reason for which the factory pattern is used is that
it introduces a separation between the application and a family of classes (it introduces weak coupling instead of tight coupling hiding concrete classes from the application).
It provides a simple way of extending the family of products with minor changes in application code.
It provides customization hooks. When the objects are created directly inside the class it's
hard to replace them by objects which extend their functionality.
If a factory is used instead to create a family of objects the customized objects can easily replace the original objects, configuring the factory to create them.
-
27
Drawbacks The factory has to be used for a
family of objects. If the classes doesn't extend
common base class or interface they can not be used in a factory design template.
28
Example We're going to create a Shape interface and
concrete classes implementing the Shape interface.
A factory class ShapeFactory is defined as a next step.
FactoryPatternDemo, our demo class will use ShapeFactory to get a Shape object.
It will pass information (CIRCLE / RECTANGLE / SQUARE) to ShapeFactory to get the type of object it needs.
29
Example30
Sample Code