dp unit 2 Creational Patterns

Download as pdf or txt
Download as pdf or txt
You are on page 1of 46

UNIT-II

CREATIONAL
PATTERNS
CREATIONAL PATTERNS

 Creational design patterns abstract the instantiation


process.

 They help make a system independent of how its


objects are created, composed, and represented.

 A class creational pattern uses inheritance to vary the


class that's instantiated,

 An object creational pattern will delegate instantiation to


another object.
ABSTRACT FACTORY:(Object Creational)

Intent:
Provide an interface for creating families of related
or dependent objects without specifying their concrete
classes.
Also Known As: Kit
Motivation: Consider a user interface toolkit that
supports multiple look-and-feel standards, such as Motif
and Presentation Manager.
•We can solve this problem by defining an abstract
WidgetFactory class that declares an interface for
creating each basic kind of widget.
ABSTRACT FACTORY:(Object Creational)
•There's also an abstract class for each kind of widget,
and concrete subclasses implement widgets for
specific look-and-feel standards.

•There is a concrete subclass of WidgetFactory for each


look-and-feel standard, that implements the operations to
create the appropriate widget for the look and feel.

•For example, the CreateScrollBar() operation on the


MotifWidgetFactory instantiates and returns a
Motif scrollbar,
•Clients create widgets solely through the
WidgetFactory interface and have no knowledge of the
classes that implement widgets for a particular look and
feel.
Applicability:
Use the AbstractFactory 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 products.


•A family of related product objects is designed to be used together, and we
need to enforce this constraint.
•We want to provide a class library of products, and you want to reveal just
their interfaces, not their implementations.
Structure:
Participants:

AbstractFactory (WidgetFactory)
o Declares an interface for operations that create abstract product objects.
ConcreteFactory (MotifWidgetFactory, PMWidgetFactory)
o Implements the operations to create concrete product objects.
AbstractProduct(Window, ScrollBar)
o Declares an interface for a type of product object.
ConcreteProduct(MotifWindow, MotifScrollBar)
Defines a product object to be created by the corresponding concrete factory by implementing
the AbstractProduct interface.
Client
Uses the interfaces of Abstract Factory and Product classes.
Collaborations:
•Normally a single instance of a Concrete Factory class is created at run-time.
•This concrete factory creates product objects having a particular implementation.
•To create different product objects, clients should use a different concrete factory.
•AbstractFactory defers creation of product objects to its ConcreteFactory subclass.

Consequences:
The AbstractFactory pattern has the following benefits sand liabilities:
1. It isolates concrete classes: Helps you control the classes of objects than an
application creates.

2.It makes exchanging product families easy: The classes of a concrete factory
appears only once in an application -i.e., where its instantiated.

3.It promotes consistency among products: An application use objects from only one
family at a time. Abstract Factory makes this easy to enforce.

4.Supporting new kinds of products is difficult: Extending Abstract Factories to


produce new kinds of products isn’t easy.
Implementation:

Here are some useful techniques for implementing the AbstractFactory pattern.
1. Factories as singletons: An application typically needs only one instance
of a concrete factory per product family.
2. Creating the products: Abstract factory only declares an interface for creating
products.
3. Defining extensible factories:. Adding new kind of product requires
changing the Abstract Factory interface and all the classes that depend on it.

Sample Code
// Each concrete factory has a
interface GUIFactory { //corresponding product variant.
Button createButton(); class MacFactory implements GUIFactory {
Checkbox createCheckbox(); Button createButton(){
} return new MacButton() }
Checkbox createCheckbox(){
class WinFactory implements GUIFactory { return new MacCheckbox() }
Button createButton() { }
return new WinButton() }
Checkbox createCheckbox() {
return new WinCheckbox() }
}
KnownUses:
• InterViews uses the"Kit“ suffix to denote AbstractFactory classes. It defines
WidgetKit and DialogKit abstract factories for generating look-and-feel-specific user
interface objects.
• InterViews also includes a LayoutKit that generates different composition objects
depending on the layout desired.

• ET++ uses the Abstract Factory pattern to achieve portability across different
window systems.

RelatedPatterns:
• Abstract Factory classes are often implemented with factory methods (Factory
Method),

• They can also be implemented using Prototype.

• A concretefactory is often a singleton (Singleton).


Builder:
Intent
Separate the construction of a complex object from its
representation so that the same construction process can create
different representations.

Motivation:
•A reader for the RTF document exchange format should be able to
convert RTF to many text formats.

•It should be easy to add a new conversion without modifying the


reader.

• A solution is to configure the RTF Reader class with a


TextConverter object that converts RTF to another textual
representation.
Motivation Contd

•As the RTF Reader parses the RTF document, it uses the
TextConverter to perform the conversion.

•Whenever the RTF Reader recognizes an RTF token, it issues a


request to the TextConverter to convert the token.

•Text Converter objects are responsible both for performing the


data conversion and for representing the token in a particular
format.

• Each converter sub-class takes the mechanism for creating


and assembling a complex object and puts it behind an abstract
interface.
• Reader is responsible for parsing an RTF document.
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're assembled.

The construction process must allow different representations for


the object that's constructed.

Structure:
Participants:
Builder(TextConverter)
Specifies an abstract interface for creating parts of a Product
object.

ConcreteBuilder (ASCIIConverter, TeXConverter, TextWidgetConverter)


1) Constructs and assembles parts of the product by implementing the Builder
interface.
2) Defines and keeps track of the representation it creates.
3) Provides an interface for retrieving the product (e.g., GetASCIIText,
GetTextWidget).

Director(RTFReader)
Constructs an object using the Builder interface.

Product(ASCIIText, TeXText, TextWidget)


Represents the complex object under construction.
Collaborations:
• The client creates the Director object and configures it with the desired
Builder object.
• Director notifies the builder whenever apart of the product should be
built.
• Builder handles requests from the director and adds parts to the product.
• The 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:
An abstract Builder class that defines an operation for each
component that a director may ask it to create.
Here are other implementation issues:

1. Assembly and construction interface:


a) The builder class interface must be general enough to
allow the construction of products for all kinds of concrete
builders.
b) The builder return child nodes to the director, which then
would pass them back to the builder to build the parent
nodes.

2. Why no abstract class for products? The client knows which


concrete subclass of builder is in use and can handle its products
accordingly.

3. Empty methods as default in Builder: In C++, the builder


methods are defined as empty methods.
Sample Code: Car buider

interface Builder { // The concrete builder classes follow the builder interface

void reset() ; class CarBuilder implements Builder{


private Car car;
void setSeats(...) ;
void reset() {
void setEngine(...) ; this.car = new Car() ;
} }
void setSeats(...) {
// Set the number of seats in the car.
}
void setEngine(...) {
// Install a given engine. }
}
FactoryMethod

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.
AlsoKnown As: Virtual Constructor

Motivation:

• Frameworks use abstract classes to define and maintain relationships


between objects.

• Consider a framework for applications that can present multiple


documents to the user.

•The Factory Method pattern encapsulates the knowledge of which


Document subclass to create and moves this knowledge out of the
framework.
•Application subclasses redefine an abstract CreateDocument operation on
Application to return the appropriate Document subclass.

• Once an Application subclass is instantiated, it can then instantiate


application-specific Documents without knowing their class.

• We call CreateDocument a factory method because it's responsible for


"manufacturing" an object.
Applicability: Use the Factory Method pattern when A class can't expect 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:
Participants
Product(Document)
Defines the interface of objects the factorymethod creates.
ConcreteProduct (MyDocument)
Implements the Product interface.

Creator(Application)
• Declares the factory method, which returns an object of type Product.
• Define a default implementation of the factory method that returns a
default ConcreteProduct object.
• Calls the factorymethod to create a Product object.
ConcreteCreator (MyApplication)
Overrides the factorymethod to return an instance of a ConcreteProduct.
Consequences
Factory methods eliminate the need to bind application-specific classes into
our code.
A potential disadvantage of factory methods is that clients might have to
subclass the Creator class just to create a Concrete Product object.

Here are two additional consequences of the FactoryMethod pattern:

1. Provides hooks for subclasses:


Creating objects inside a class with a factory method is always more
flexible than creating an object directly.
2. Connects parallel class hierarchies: The factory method is only called by
creators.
Parallel class hierarchies results when a class delegates some of its
responsibilities to a separate class.
Implementation:
Consider the following issues when applying the FactoryMethod pattern:
1.Two major varieties. (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.

2.Parameterized factory methods. 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.

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


interesting variations and requirements.

4.Using templates to avoid sub classing. Another potential problem with factory
methods is that they might force you to subclass just to create the appropriate Product
objects.
5.Naming conventions. Using naming conventions makes it clear you're using factory
methods.
SAMPLE CODE

public class City {


public Business getBusiness() {…}
}
public class Seattle extends City {
@Override
public Business getBusiness() {
return new SeattleBusiness();
}
}
public class Minneapolis extends City {
. . .
}
City seattle = new Seattle();
seattle.getBusiness();
Known Uses:
•Factory methods provide toolkits and frameworks.
•The document example is a typical use in MacApp and ET++.
•ClassView in the Smalltalk-80 Model/View/Controller framework
has a method default Controller that creates a controller, and this
might appear to be a factory method.
•Another example in Smalltalk-80 is the factory method parser Class
defined by Behavior (a super class of all objects representing classes).This
enables a class to use a customized parser for its source code

•The OrbixORB system from IONA Technologies uses FactoryMethod to


generate an appropriate type of proxy when an object requests a reference
to a remote object.

RelatedPatterns: AbstractFactory is often implemented with factory methods.


Factory methods are usually called within Template Methods.
Prototype
Intent:
Specify the kinds of objects to create using a prototypical instance, and
create new objects by copying this prototype.
Motivation:

•We could build an editor for music scores by customizing a general


framework for graphical editors and adding new objects that represent
notes, rests, and staves.

Let's assume the framework provides an abstract Graphic class for


graphical components, like notes and staves.

It'll provide an abstract Tool class for defining tools like those in the
palette.

The framework also predefines a GraphicTool subclass for tools that


create instances of graphical objects and add them to the document.
•We could subclass GraphicTool for each kind of music object, but that
would produce lots of subclasses that differ only in the kind of music
object they instantiate.

•The solution is making GraphicTool create a new Graphic by


copying or "cloning" an instance of a Graphic subclass. We call this
instance a prototype.

•GraphicTool is parameterized by the prototype it should clone and add to


the document.

•If all Graphic subclasses support a Clone operation, then the


GraphicTool can clone any kind of Graphic.

•Each GraphicTool instance will produce a music object by cloning


its prototype and adding the clone to the score.

•This can reduce the number of classes in the system dramatically. It also
makes it easier to add a new kind of note to the music editor.
Applicability:
•Use the Prototype pattern when a system should be independent of
how its products are created, composed, and represented; and
•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.

Structure
Participants:

Prototype(Graphic)
Declares an interface for cloningitself.
ConcretePrototype (Staff, WholeNote, HalfNote)
Implements an operation for cloning itself.
Client(GraphicTool)
Creates a new object by asking a prototype to clone itself.

Consequences:
It hides the concrete product classes from the client,
Additional benefits of the Prototype pattern are listed below.

1. Adding and removing products at run-time:


2. Specifying new objects by varying values:
3.Specifying new objects by varying structure:
4.Reduced subclassing
5.Configuring an application with classes dynamically
Implementation:

Consider the following issues when implementing prototypes:


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(prototype manager.) of available prototypes.

•A client will ask the registry for a prototype before cloning it.

2.Implementing the Clone operation.


•The hardest part of the Prototype pattern is implementing the
Clone operation correctly.

3.Initializing clones.
Clients will want to initialize some or all of its internal state to values
of their choosing.
// The clone operation returns one of the Shape subclasses.
// Base prototype. abstract method clone():Shape
abstract class Shape is
field X: int
field Y: int class Rectangle extends Shape is
field color: string field width: int
field height: int
// A regular constructor.
constructor Shape() is constructor Rectangle(source: Rectangle) is
// ... // A parent constructor call is needed to copy private
// fields defined in the parent class.
// The prototype constructor. A fresh object is initialized super(source)
// with values from the existing object. this.width = source.width
constructor Shape(source: Shape) is this.height = source.height
this()
this.X = source.X method clone():Shape is
this.Y = source.Y return new Rectangle(this)
this.color = source.color
Known Uses:
•Perhaps the first example of the Prototype pattern was in Ivan
Sutherland's Sketchpad system.

•The first widely known application of the pattern in an object-


oriented language was in ThingLab.

•Etgdb is a debugger front-end based on ET++ that provides a


point-and-click interface to different line-oriented debuggers.

•Each debugger has a corresponding DebuggerAdaptor subclass.

•The "interaction technique library" in Mode Composer stores prototypes


of objects that support various interaction techniques.
Related Patterns:
•Prototype and Abstract Factory are competing patterns in some ways. But,
they can also be used together.

•An AbstractFactory might store a set of prototypes from which to clone


and return product objects.

•Designs that make heavy use of the Composite and Decorator patterns
often can benefit from Prototype as well.
Singleton
Intent:
Ensure a class only has one instance, and provide a global point of access to
it.

Motivation:
It's important for some classes to have exactly one instance.
Examples:

• Although there can be many printers in a system, there should be


only one printer spooler.

•There should be only one file system and one window manager.

• A digital filter will have one A/D converter. An accounting system


will be dedicated to serving one company.
A better solution is to make the class itself responsible for keeping track of its sole instance.

The class can ensure that no other instance can be created, and it can provide a way to

access the instance. This is the Singleton pattern.

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
instance. Instance is a class operation that is responsible for creating its
own unique instance.

Consequences:
The Singleton pattern has several benefits:
1.Controlled access to sole instance. Because the Singleton class
encapsulates its sole instance, it can have strict control over how and when
clients access it.
2.Reduced name space. The Singleton pattern is an improvement
over global variables. It avoids polluting the name space with global
variables that store sole instances.
3.Permits refinement of operations and representation. We can
configure the application with an instance of the class we need at run-time.
1.Permits a variable number of instances. The pattern makes it easy to change your
mind and allow more than one instance of the Singleton class.

2.More flexible than class operations. Another way to package a singleton's


functionality is to use class operations.

Implementation:
Here are implementation issues to consider when using the Singleton pattern:
1.Ensuring a unique instance. The Singleton pattern makes the sole instance a
normal instance of a class, but that class is written so that only one instance can ever be
created by hiding the operation that creates the instance behind a class operation that
guarantees only one instance is created.

2.Registry for Singletons. The main issue is installing its unique instance so that
clients will be able to use it. A more flexible approach uses a registry of singletons. The
Singleton classes can register their singleton instance by name in a well-known registry.
This approach frees Instance from knowing all possible Singleton classes or
instances.
SampleCode:

class Database is
// The field for storing the singleton instance should be
// declared static and private.
private static field instance: Database
class Application is method main() is
// The singleton's constructor should always be private to
// prevent direct construction calls with the `new` Database foo = Database.getInstance()
// operator. foo.query("SELECT ...")
private constructor Database() is // ...
// Some initialization code, such as the actual
// database connection
Database bar = Database.getInstance()
public static method getInstance() is bar.query("SELECT ...")
// Ensure that the instance hasn't yet been // The variable `bar` will contain the same
if (Database.instance == null) then
//object as the variable `foo`.
Database.instance = new Database()
return Database.instance
// Finally, any singleton should define some business logic
// which can be executed on its instance.
public method query(sql) is
// For instance, all database queries of an app go
// through this method. Therefore, you can place
// throttling or caching logic here.
// ...
SampleCode:

class Database is
class Application is method main() is
private static field instance: Database
Database foo = Database.getInstance()
private constructor Database() is
foo.query("SELECT ...")
public static method getInstance() is
// ...
if (Database.instance == null) then
Database bar = Database.getInstance()
Database.instance = new Database()
bar.query("SELECT ...")
return Database.instance
// The variable `bar` will contain the same
public method query(sql) is
//object as the variable `foo`.
// ...
Known Uses:
An example of the Singleton pattern in Smalltalk-80 is the set of changes to
the code, which is ChangeSet current. A more subtle example is the
relationship between classes and their meta classes.

The InterViews user interface toolkit uses the Singleton pattern to access the
unique instance of its Session and WidgetKit classes, among others.

Related Patterns:
Many patterns can be implemented using the Singleton pattern:
AbstractFactory, Builder, and Prototype.
Discussion of Creational Patterns

There are two common ways to parameterize a system by the classes of


objects it creates.

1.Subclass the class that creates the objects; this corresponds to using
the Factory Method pattern. The main drawback of this approach is that it
can require creating a new subclass just to change the class of the product.
Such changes can cascade.

2.The other way to parameterize a system relies more on object composition:


Define an object that's responsible for knowing the class of the product
objects, and make it a parameter of the system. This is a key aspect of the
Abstract Factory, Builder, and Prototype patterns.
• Builder has the factory object building a complex product incrementally
using a correspondingly complex protocol.
• Prototype has the factory object building a product by copying a
prototype object.
• AbstractFactory has the factory(sometimes a Prototype) object
producing objects of several classes.
Consider the drawing editor framework described in the Prototype pattern.
There are several ways to parameterize a GraphicTool by the class of
product:

• By applying the Factory Method pattern, a subclass of GraphicTool


will be created for each subclass of Graphic in the palette.

• By applying the Abstract Factory pattern, there will be a class


hierarchy of Graphics Factories, one for each Graphic subclass. Each
factory creates just one product in this case: CircleFactory will create
Circles, LineFactory will create Lines
•By applying the Prototype pattern, each subclass of Graphics will implement
the Clone operation, and a GraphicTool will be parameterized with a
prototype of the Graphic it creates.
•In our drawing editor framework, the Factory Method pattern is easiest to
use at first.
•AbstractFactory doesn't offer much of an improvement, because it requires
an equally large GraphicsFactory class hierarchy.

•Overall, the Prototype pattern is probably the best for the drawing
editor framework, because it only requires implementing a Clone
operation on each Graphics class. That reduces the number of
classes, and Clone can be used for purposes other than pure instantiation.

•FactoryMethod makes a design more customizable and only a little more


complicated.

•Other design patterns require new classes, whereas Factory Method only
requires a new operation.

•Designs that use Abstract Factory, Prototype, or Builder are even more
flexible than those that use Factory Method, but they're also more complex.

You might also like