design pattern- creational pattern · design pattern- creational pattern 2015 4 | p a g e almas...

16
Design Pattern- Creational pattern 2015 1 | Page Almas Ansari Creational Patterns Abstracts instantiation process Makes system independent of how its objects are created composed represented Encapsulates knowledge about which concrete classes the system uses Hides how instances of these classes are created and put together Abstract the instantiation process Make a system independent of how objects are created, composed, and represented Important if systems evolve to depend more on object composition than on class inheritance Emphasis shifts from hardcoding fixed sets of behaviors towards a smaller set of composable fundamental behaviors Encapsulate knowledge about concrete classes a system uses Hide how instances of classes are created and put together What are creational patterns? 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 Recurring themes: Encapsulate knowledge about which concrete classes the system uses (so we can change them easily later) Hide how instances of these classes are created and put together (so we can change it easily later) Benefits of creational patterns Creational patterns let you program to an interface defined by an abstract class That lets you configure a system with ―product‖ objects that vary widely in structure and functionality Example: GUI systems InterViews GUI class library Multiple look-and-feels Abstract Factories for different screen components 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

Upload: others

Post on 28-Jul-2020

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Design Pattern- Creational pattern · Design Pattern- Creational pattern 2015 4 | P a g e Almas Ansari • The client may use the AbstractFactory interface to initiate creation, or

Design Pattern- Creational pattern 2015

1 | P a g e

Almas Ansari

Creational Patterns

• Abstracts instantiation process

• Makes system independent of how its objects are

– created

– composed

– represented

• Encapsulates knowledge about which concrete classes the system uses

• Hides how instances of these classes are created and put together

• Abstract the instantiation process

– Make a system independent of how objects are created, composed, and represented

• Important if systems evolve to depend more on object composition than on class inheritance

– Emphasis shifts from hardcoding fixed sets of behaviors towards a smaller set of composable

fundamental behaviors

• Encapsulate knowledge about concrete classes a system uses

• Hide how instances of classes are created and put together

What are creational patterns?

• 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

• Recurring themes:

– Encapsulate knowledge about which concrete classes the system uses (so we can change them

easily later)

– Hide how instances of these classes are created and put together (so we can change it easily

later)

Benefits of creational patterns

• Creational patterns let you program to an interface defined by an abstract class

• That lets you configure a system with ―product‖ objects that vary widely in structure and functionality

• Example: GUI systems

– InterViews GUI class library

– Multiple look-and-feels

– Abstract Factories for different screen components

• 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

Page 2: Design Pattern- Creational pattern · Design Pattern- Creational pattern 2015 4 | P a g e Almas Ansari • The client may use the AbstractFactory interface to initiate creation, or

Design Pattern- Creational pattern 2015

2 | P a g e

Almas Ansari

Abstract Factory Pattern

Provide an interface for creating families of related or dependent objects without specifying their concrete

classes

Intent: Provide an interface for creating families of related or dependent objects without specifying their

concrete classes

Also Known As: Kit.

Motivation:

– User interface toolkit supports multiple look-and-feel standards (Motif, Presentation Manager)

– Different appearances and behaviors for UI widgets

– Apps should not hard-code its widgets

Solution:

• Abstract Widget Factory class

• Interfaces for creating each basic kind of widget

• Abstract class for each kind of widgets,

• Concrete classes implement specific look-and-feel.

Page 3: Design Pattern- Creational pattern · Design Pattern- Creational pattern 2015 4 | P a g e Almas Ansari • The client may use the AbstractFactory interface to initiate creation, or

Design Pattern- Creational pattern 2015

3 | P a g e

Almas Ansari

Applicability

Use the Abstract Factory pattern 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 produces

– A family of related product objects is designed to be used together, and you need to enforce this

constraint

– You want to provide a class library of products, and you want to reveal just their interfaces, not their

implementations

Participants

AbtractFactory

Declares interface for operations that create abstract product objects

ConcreteFactory

Implements operations to create concrete product objects

AbstractProduct

Declares an interface for a type of product object

Concrete Product:

Defines a product object to be created by concrete factory

Implements the abstract product interface

Client:

Uses only interfaces declared by Abstract Factory and AbstractProduct classes

Collaborators

• Usually only one ConcreteFactory instance is used for an activation, matched to a specific application

context. It builds a specific product family for client use -- the client doesn’t care which family is

used -- it simply needs the services appropriate for the current context.

Page 4: Design Pattern- Creational pattern · Design Pattern- Creational pattern 2015 4 | P a g e Almas Ansari • The client may use the AbstractFactory interface to initiate creation, or

Design Pattern- Creational pattern 2015

4 | P a g e

Almas Ansari

• The client may use the AbstractFactory interface to initiate creation, or some other agent may use the

AbstractFactory on the client’s behalf.

Consequences:

The Abstract Factory Pattern has the following benefits:

– It isolates concrete classes from the client.

• You use the Abstract Factory to control the classes of objects the client creates.

• Product names are isolated in the implementation of the ConcreteFactory, clients use the instances

through their abstract interfaces.

– Exchanging product families is easy.

• None of the client code breaks because the abstract interfaces don’t change.

• Because the abstract factory creates a complete family of products, the whole product family changes

when the concrete factory is changed.

– It promotes consistency among products.

• It is the concrete factory’s job to make sure that the right products are used together.

• More benefits of the Abstract Factory Pattern

– It supports the imposition of constraints on product families, e.g., always use A1 and B1 together,

otherwise use A2 and B2 together.

The Abstract Factory pattern has the following liability:

– Adding new kinds of products to existing factory is difficult.

• Adding a new product requires extending the abstract interface which implies that all of its derived

concrete classes also must change.

• Essentially everything must change to support and use the new product family

• abstract factory interface is extended

• derived concrete factories must implement the extensions

• a new abstract product class is added

• a new product implementation is added

• client has to be extended to use the new product

Implementation

• Concrete factories are often implemented as singletons.

• Creating the products

– Concrete factory usually use the factory method.

• simple

• new concrete factory is required for each product family

– alternately concrete factory can be implemented using prototype.

Page 5: Design Pattern- Creational pattern · Design Pattern- Creational pattern 2015 4 | P a g e Almas Ansari • The client may use the AbstractFactory interface to initiate creation, or

Design Pattern- Creational pattern 2015

5 | P a g e

Almas Ansari

• only one is needed for all families of products

• product classes now have special requirements - they participate in the creation

• Defining extensible factories by using create function with an argument

– only one virtual create function is needed for the AbstractFactory interface

– all products created by a factory must have the same base class or be able to be safely coerced

to a given type

– it is difficult to implement subclass specific operations

Related Patterns

• Factory Method -- a ―virtual‖ constructor

• Prototype -- asks products to clone themselves

• Singleton -- allows creation of only a single instance

Example

The purpose of the Abstract Factory is to provide an interface for creating families of related objects, without specifying concrete classes. This pattern is found in the sheet metal stamping equipment used in the manufacture of Japanese automobiles. The stamping equipment is an Abstract Factory which creates auto body parts. The same machinery is used to stamp right hand doors, left hand doors, right front fenders, left front fenders, hoods, etc. for different models of cars. Through the use of rollers to change the

stamping dies, the concrete classes produced by the machinery can be changed within three minutes.

Page 6: Design Pattern- Creational pattern · Design Pattern- Creational pattern 2015 4 | P a g e Almas Ansari • The client may use the AbstractFactory interface to initiate creation, or

Design Pattern- Creational pattern 2015

6 | P a g e

Almas Ansari

BUILDER (Object Creational)

Intent: Separate the construction of a complex object from its representation so that the same construction

process can create different representations

Motivation:

• RTF reader should be able to convert RTF to many text format

• Adding new conversions without modifying the reader should be easy

Solution:

• Configure RTFReader class with a Text Converter object

• Subclasses of Text Converter specialize in different conversions and formats

• TextWidgetConverter will produce a complex UI object and lets the user see and edit the text

Applicability

Use the Builder pattern when

– The algorithm for creating a complex object should be independent of the parts that make up

the object and how they are assembled

– The construction process must allow different representations for the object that is

constructed

Structure

Page 7: Design Pattern- Creational pattern · Design Pattern- Creational pattern 2015 4 | P a g e Almas Ansari • The client may use the AbstractFactory interface to initiate creation, or

Design Pattern- Creational pattern 2015

7 | P a g e

Almas Ansari

Participants

Collaborations

• Client creates Director object and configures it with the desired Builder object

• Director notifies Builder whenever a part of the product should be built

• Builder handles requests from the Director and adds parts to the product

Client retrieves the product from the Builder

Consequences

1. It lets you vary a product's internal representation.

2. It isolates code for construction and representation.

3. It gives you finer control over the construction process.

Implementation

1. Assembly and construction interface.

2. Why no abstract class for products.

3. Empty methods as default in Builder.

Page 8: Design Pattern- Creational pattern · Design Pattern- Creational pattern 2015 4 | P a g e Almas Ansari • The client may use the AbstractFactory interface to initiate creation, or

Design Pattern- Creational pattern 2015

8 | P a g e

Almas Ansari

Related Patterns

Abstract Factory (99) is similar to Builder in that it too may construct complex objects.

A Composite (183) is what the builder often builds.

Example

The Builder pattern separates the construction of a complex object from its representation so that the same

construction process can create different representations. This pattern is used by fast food restaurants to

construct children's meals. Children's meals typically consist of a main item, a side item, a drink, and a toy

(e.g., a hamburger, fries, Coke, and toy dinosaur). Note that there can be variation in the content of the

children's meal, but the construction process is the same. Whether a customer orders a hamburger,

cheeseburger, or chicken, the process is the same. The employee at the counter directs the crew to assemble a

main item, side item, and toy. These items are then placed in a bag. The drink is placed in a cup and remains

outside of the bag. This same process is used at competing restaurants.

Page 9: Design Pattern- Creational pattern · Design Pattern- Creational pattern 2015 4 | P a g e Almas Ansari • The client may use the AbstractFactory interface to initiate creation, or

Design Pattern- Creational pattern 2015

9 | P a g e

Almas Ansari

FACTORY METHOD (Class Creational)

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.

Also Known As: Virtual Constructor

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

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.

Structure

Page 10: Design Pattern- Creational pattern · Design Pattern- Creational pattern 2015 4 | P a g e Almas Ansari • The client may use the AbstractFactory interface to initiate creation, or

Design Pattern- Creational pattern 2015

10 | P a g e

Almas Ansari

Participants

• Product: Defines the interface of objects the factory method creates

• ConcreteProduct : Implements the product interface

• Creator

– Declares the factory method which returns object of type product

– May contain a default implementation of the factory method

– Creator relies on its subclasses to define the factory method so that it returns an instance of

the appropriate Concrete Product.

• ConcreteCreator: Overrides factory method to return instance of ConcreteProduct

Collaborations

Creator relies on its subclasses to define the factory method so that it returns an instance of the appropriate

Concrete Product.

Consequences

Here are two additional consequences of the Factory Method pattern:

1. Provides hooks for subclasses. Creating objects inside a class with a factory method is always more flexible

than creating an object directly. Factory Method gives subclasses a hook for providing an extended version of

an object.

2. Connects parallel class hierarchies. In the examples we've considered so far, the factory method is only

called by Creators. But this doesn't have to be the case; clients can find factory methods useful, especially in

the case of parallel class hierarchies.

Implementation

Consider the following issues when applying the Factory Method pattern:

1. Two major varieties. The two main variations of the Factory Method pattern are (1) the case when the

Creator class is an abstract class and does not provide an implementation for the factory method it declares,

and (2) the case when the Creator is a concrete class and provides a default implementation for the factory

method. It's also possible to have an abstract class that defines a default implementation, but this is less

common.

2. Parameterized factory methods.

Another variation on the pattern lets the factory method create multiple kinds of products. The factory method

takes a parameter that identifies the kind of object to create. All objects the factory method creates will share

the Product interface. In the Document example, Application might support different kinds of Documents.

You pass Create Document an extra parameter to specify the kind of document to create.

3. Language-specific variants and issues. Different languages lend themselves to other interesting variations

and caveats.

4. Using templates to avoid subclassing. As we've mentioned, another potential problem with factory methods

is that they might force you to subclass just to create the appropriate Product objects.

5. Naming conventions. It's good practice to use naming conventions that make it clear you're using factory

methods

Page 11: Design Pattern- Creational pattern · Design Pattern- Creational pattern 2015 4 | P a g e Almas Ansari • The client may use the AbstractFactory interface to initiate creation, or

Design Pattern- Creational pattern 2015

11 | P a g e

Almas Ansari

Related Patterns

Abstract Factory (99) is often implemented with factory methods.

Factory methods are usually called within Template Methods (360).

Prototypes (133) don't require subclassing Creator.

Example

The Factory Method defines an interface for creating objects, but lets subclasses decide which classes to

instantiate. Injection molding presses demonstrate this pattern. Manufacturers of plastic toys process plastic

molding powder, and inject the plastic into molds of the desired shapes. The class of toy (car, action figure,

etc.) is determined by the mold.

Page 12: Design Pattern- Creational pattern · Design Pattern- Creational pattern 2015 4 | P a g e Almas Ansari • The client may use the AbstractFactory interface to initiate creation, or

Design Pattern- Creational pattern 2015

12 | P a g e

Almas Ansari

PROTOTYPE (Object Creational)

Intent: Specify the kinds of objects to create using a prototypical instance, and create new objects by copying

this prototype.

Motivation:

– Framework implements Graphic class for graphical components and GraphicTool class for tools

manipulating/creating those components

– Actual graphical components are application-specific

– How to parameterize instances of Graphic Tool class with type of objects to create?

Solution: create new objects in Graphic Tool by cloning a prototype object instance

Applicability

• Use the Prototype pattern when a system should be independent of how its products are created,

composed, and represented;

– when the classes to instantiate are specified at run-time, for example, by dynamic loading; or

– to avoid building a class hierarchy of factories that parallels the class hierarchy of products; or

– when instances of a class can have one of only a few different combinations of state. It may

be more convenient to install a corresponding number of prototypes and clone them rather

than instantiating the class manually, each time with the appropriate state.

Page 13: Design Pattern- Creational pattern · Design Pattern- Creational pattern 2015 4 | P a g e Almas Ansari • The client may use the AbstractFactory interface to initiate creation, or

Design Pattern- Creational pattern 2015

13 | P a g e

Almas Ansari

Structure

Participants:

Prototype (Graphic): Declares an interface for cloning itself

ConcretePrototype (Staff, WholeNote, HalfNote): Implements an interface for cloning itself

Client (GraphicTool): Creates a new object by asking a prototype to clone itself

Collaborations:

• A client asks a prototype to clone Itself.

Consequences

1. Adding and removing products at run-time. Prototypes let you incorporate a new concrete product class into

a system simply by registering a prototypical instance with the client.

2. Specifying new objects by varying values. Highly dynamic systems let you define new behavior through

object composition—by specifying values for an object's variables

3. Specifying new objects by varying structure. Many applications build objects from parts and subparts.

4. Reduced subclassing. Factory Method (121) often produces a hierarchy of Creator classes that parallels the

product class hierarchy.

5. Configuring an application with classes dynamically. Some run-time environments let you load classes into

an application dynamically.

Implementation

1. Using a prototype manager. When the number of prototypes in a system isn't fixed (that is, they can be

created and destroyed dynamically), keep a registry of available prototypes.

2. Implementing the Clone operation. The hardest part of the Prototype pattern is implementing the Clone

operation correctly. It's particularly tricky when object structures contain circular references.

3. Initializing clones. While some clients are perfectly happy with the clone as is, others will want to initialize

some or all of its internal state to values of their choosing.

Page 14: Design Pattern- Creational pattern · Design Pattern- Creational pattern 2015 4 | P a g e Almas Ansari • The client may use the AbstractFactory interface to initiate creation, or

Design Pattern- Creational pattern 2015

14 | P a g e

Almas Ansari

Related Patterns

Prototype and Abstract Factory

Designs that make heavy use of the Composite and Decorator patterns often can benefit from Prototype as

well.

Example

The Prototype pattern specifies the kind of objects to create using a prototypical instance. Prototypes of new

products are often built prior to full production, but in this example, the prototype is passive and does not

participate in copying itself. The mitotic division of a cell - resulting in two identical cells - is an example of a

prototype that plays an active role in copying itself and thus, demonstrates the Prototype pattern. When a cell

splits, two cells of identical genotvpe result. In other words, the cell clones itself.

Page 15: Design Pattern- Creational pattern · Design Pattern- Creational pattern 2015 4 | P a g e Almas Ansari • The client may use the AbstractFactory interface to initiate creation, or

Design Pattern- Creational pattern 2015

15 | P a g e

Almas Ansari

SINGELTON

Intent: Ensure a class only has one instance, and provide a global point of access to it.

Motivation:

• Some classes should have exactly one instance

(one print spooler, one file system, one window manager)

• A global variable makes an object accessible but doesn’t prohibit instantiation of multiple objects

• Class should be responsible for keeping track of its sole interface

Applicability

Use the Singleton pattern when

• there must be exactly one instance of a class, and it must be accessible to clients from a well-known

access point.

• when the sole instance should be extensible by subclassing, and clients should be able to use an extended

instance without modifying their code.

Structure

Participants

Singleton:

• Defines an instance operation that lets clients access its unique interface

• Instance is a class operation (static in Java)

• May be responsible for creating its own unique instance

Collaborations:

• Clients access a Singleton instance solely through Singleton’s Instance operation.

Implementation

• Ensures a class has only one instance

• Subclassing the Singleton class.

Related Patterns

Abstract Factory, Builder and Prototype.

Page 16: Design Pattern- Creational pattern · Design Pattern- Creational pattern 2015 4 | P a g e Almas Ansari • The client may use the AbstractFactory interface to initiate creation, or

Design Pattern- Creational pattern 2015

16 | P a g e

Almas Ansari

Example

The Singleton pattern ensures that a class has only one instance and provides a global point of access to that

instance. It is named after the singleton set, which is defined to be a set containing one element. The office of

the President of the United States is a Singleton. The United States Constitution specifies the means by which

a president is elected, limits the term of office, and defines the order of succession. As a result, there can be at

most one active president at any given time. Regardless of the personal identity of the active president, the

title, "The President of the United States" is a global point of access that identifies the person in the office.