0% found this document useful (0 votes)
14 views82 pages

2-DP

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views82 pages

2-DP

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

DESIGN PATTERNS

UNIT-II
Abstract Factory(creational pattern)
• Abstract Factory patterns work around a
super-factory which creates other factories.
This factory is also called as factory of
factories. This type of design pattern comes
under creational pattern as this pattern
provides one of the best ways to create an
object.
What is Abstract Factory Pattern?
• Abstract factory pattern falls into “Creational
design pattern” category. Abstract factory
design pattern is used to mange different
object types of same family.
• All the object should belong to same family
but they are of different categories.
• Pattern name &classification: Abstract factory
& Creational Pattern
• Intent: Provide an interface for creating
families of related or dependent objects
without specifying their concrete classes.
• Also known as: Kit
• Motivation:
Extends key Generalization

impliments realization
Applicability
We should use Abstract Factory design pattern when:
• The system needs to be independent of the products it
works with are created.
• The system should be configured to work with
multiple families of products.
• A family of products is designed to be used together
and this constraint is needed to be enforced.
• A library of products is to be provided and only their
interfaces are to be revealed but not their
implementations.
Structure
• AbstractFactory - This class declares an
interface that is used to create abstract
product objects. We interact with this
interface to allow the client to access
instances of the our ConcreteFactory concrete
subclasses.
• ConcreteFactory - A subclass of the Abstract
factory, these concrete classes implement the
operations which are used to create concrete
product objects. Each Factory has it’s own
individual family of products which it creates.
• AbstractProduct - The AbstractProduct class is used to
declare an interface for a specific type of product
object.
• ConcreteProduct - The concrete product is provided by
it’s ConcreteFactory and defines the individual
implementation details for the specified product
through the implementation of its AbstractProduct
interface.
• Client - Only uses and has access to the interfaces that
are defined by the AbstractFactory and
AbstractProduct classes, making it completely unaware
of the implementation details of the system.
• Collaborations
➢ The ConcreteFactory class creates products
objects having a particular implementation. To
create different product, the client should use
a different concrete factory.
➢AbstractFactory defers creation of product
objects to its ConcreteFactory subclass
Implementation
1. Declare abstract product interfaces for all product
types. Then make all concrete product classes
implement these interfaces.
2. Declare the abstract factory interface with a set of
creation methods for all abstract products.
3. Implement a set of concrete factory classes, one for
each product variant.
4. Create factory initialization code somewhere in the
app. It should instantiate one of the concrete factory
classes, depending on the application configuration or
the current environment. Pass this factory object to all
classes that construct products.
5. Scan through the code and find all direct calls to
product constructors. Replace them with calls to the
appropriate creation method on the factory object.
Consequences
• It isolates concrete classes.
• It makes exchanging product families easy.
• It creates consistency among products
Sample Code
AbstractFactory.java
public abstract class AbstractFactory
{
abstract Shape getShape(String shapeType) ;
}
• Shape.java
public interface Shape
{
void draw();
}

• RoundedRectangle.java
public class RoundedRectangle implements Shape
{
@Override
public void draw()
{
System.out.println("Inside RoundedRectangle::draw() method.");
}
}
Implementation
ShapeFactory.java
public class ShapeFactory extends AbstractFactory
{
@Override
public Shape getShape(String shapeType)
{
if(shapeType.equalsIgnoreCase("RECTANGLE"))
{
return new Rectangle();
}
else if(shapeType.equalsIgnoreCase("SQUARE"))
{
return new Square();
}
return null;
}
}
public class RoundedShapeFactory extends AbstractFactory
{
@Override
public Shape getShape(String shapeType)
{
if(shapeType.equalsIgnoreCase("RECTANGLE"))
{
return new RoundedRectangle();
}
else if(shapeType.equalsIgnoreCase("SQUARE"))
{
return new RoundedSquare();
}
return null;
}
}
• Known uses: ET++ [WGM88] uses the Abstract
Factory pattern to achieve portability across
different window systems (X Windows and
SunView, for example).
• Related patterns
AbstractFactory classes are often
implemented with factory methods but they
can also be implemented using Prototype.
A concrete factory is often a Singleton.
2.Builder
• Pattern name and classification: Builder and Creational
• Intent: Separate the construction of a complex object from its
representation so that the same construction process can
create different representations.
• Builder pattern builds a complex object using simple objects
and using a step by step approach. This type of design pattern
comes under creational pattern as this pattern provides one
of the best ways to create an object.
• A Builder class builds the final object step by step. This builder
is independent of other objects

• Also known as:


Motivation
Motivation
Applicability
• 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
Participants
• Product – The product class defines the type of the complex object that is to be
generated by the builder pattern.
• Builder – This abstract base class defines all of the steps that must be taken in
order to correctly create a product. Each step is generally abstract as the actual
functionality of the builder is carried out in the concrete subclasses. The
GetProduct method is used to return the final product. The builder class is often
replaced with a simple interface.
• ConcreteBuilder – There may be any number of concrete builder classes inheriting
from Builder. These classes contain the functionality to create a particular complex
product.
• Director – The director class controls the algorithm that generates the final
product object. A director object is instantiated and its Construct method is called.
The method includes a parameter to capture the specific concrete builder object
that is to be used to generate the product. The director then calls methods of the
concrete builder in the correct order to generate the product object. On
completion of the process, the GetProduct method of the builder object can be
used to return the product.
Collaborations
• The client creates the Director Object and
configures it with the desired Builder object.
• Director notifies the builder whenever a part o
f 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.
Implement
1. Make sure that you can clearly define the common
construction steps for building all available product
representations. Otherwise, you won’t be able to
proceed with implementing the pattern.
2. Declare these steps in the base builder interface.
3. Create a concrete builder class for each of the
product representations and implement their
construction steps.
4. Think about creating a director class. It may
encapsulate various ways to construct a product
using the same builder object.
5. The client code creates both the builder and the
director objects. Before construction starts, the
client must pass a builder object to the director.
Advantages of the Builder pattern include:
• Allows you to vary a product's internal representation.
• Encapsulates code for construction and representation.
• Provides control over steps of construction process.
Disadvantages
• Disadvantages of the Builder pattern include:
• Requires creating a separate ConcreteBuilder for each
different type of product.
• Requires the builder classes to be mutable.
• Dependency injection may be less supported.
• Known uses The RTF converter application is
from ET++ [WGM88]. Its text building block
uses a builder to process text stored in the RTF
format. Related patterns
• Related patterns Abstract Factory is similar to
Builder in that it too may construct complex
objects. The primary difference is that the
Builder pattern focuses on constructing a
complex object step by step.
• Implementation:
//Abstract Builder
class abstract class TextConverter
{
abstract void convertCharacter(char c);
abstract void convertParagraph();
}
// Product
class ASCIIText
{
public void append(char c)
{
//Implement the code here
}
}
Sample code
abstract class AbstractProduct implements Cloneable
{
public static AbstractProduct thePrototype;
public static AbstractProduct makeProduct()
try
{
return (AbstractProduct) thePrototype.clone();
}
catch(CloneNotSupportedException e)
{
return null;
}}}
3. FACTORY METHOD
• Pattern name and classification: Factory
method and Creational
• Intent:
A Factory Pattern or Factory Method Pattern
says that just define an interface or abstract
class for creating an object but let the
subclasses decide which class to
instantiate. In other words, subclasses are
responsible to create the instance of the class.
• Also known as: Virtual Constructor
• Motivation: Frameworks use abstract classes
to define and maintain relationships between
objects. A framework is often responsible for
creating these objects as well.
Implementation
1.Make all products follow the same interface.
This interface should declare methods that
make sense in every product.
2.Add an empty factory method inside the
creator class. The return type of the method
should match the common product interface.
3.In the creator’s code find all references to
product constructors. One by one, replace
them with calls to the factory method, while
extracting the product creation code into the
factory method.
implementation

1. Define a factory method inside an interface.


2. Let the subclass implements the above
factory method and decide which object to
create.
Motivation
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
Participants:
• The participants classes in this pattern are:
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
Consequences:
Here are two additional consequences of the
Factory Method pattern
• Provides hooks for subclasses
• Connects parallel class hierarchies
Pros and Cons
• You avoid tight coupling between the creator and the
concrete products.
• Single Responsibility Principle. You can move the product
creation code into one place in the program, making the code
easier to support.
• Open/Closed Principle. You can introduce new types of
products into the program without breaking existing client
code.
• The code may become more complicated since you need to
introduce a lot of new subclasses to implement the pattern.
The best case scenario is when you’re introducing the pattern
into an existing hierarchy of creator classes.
• Known uses: Factory methods pervade(pass through)
toolkits and framework s.The preceding document example
is a typical use in MacApp and ET++. The manipulator
example is from Unidraw.
• This design pattern has been widely used in JDK, such as

1. getInstance() method of java.util.Calendar,


NumberFormat, and ResourceBundle uses factory method.
• design pattern.
2. All the wrapper classes like Integer, Boolean etc, in Java
uses this pattern to evaluate the values using valueOf()
method.
Related patterns
• Abstract Factory is often implemented with
factory methods. as well.
• Factory methods are usually called within
Template Methods
• Prototypes don't require sub classing Creator.
• 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.
Sample Code
Prototype
• Pattern name and classification: Prototype and Creational
• Intent: Specify the kinds of objects to create using a prototypical instance,
and create new objects by copying this prototype.
Example
Class Diagram
Motivation
• 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. 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.
Structure
Participants
1) Prototype : This is the prototype of actual
object.
2) Prototype registry : This is used as registry
service to have all prototypes accessible using
simple string parameters.
3) Client : Client will be responsible for using
registry service to access prototype instances.
• Collaborations: A client asks a prototype to clone
itself
• Consequences: Additional benefits of the
Prototype pattern are listed below.
• Adding and removing products at run-time
• Specifying new objects by varying values
• Specifying new objects by varying structure
• Reduced sub classing
• Configuring an application with classes
dynamically
Implementation: Configuring an application
with classes dynamically
• Using a prototype manager
• Implementing the Clone operation
• Initializing clones
Advantage of Prototype Pattern
• The main advantages of prototype pattern are
as follows:
• It reduces the need of sub-classing.
• It hides complexities of creating objects.
• The clients can get new objects without
knowing which type of object it will be.
• It lets you add or remove objects at runtime.
Usage of Prototype Pattern
• When the classes are instantiated at runtime.
• When the cost of creating an object is
expensive or complicated.
• When you want to keep the number of classes
in an application minimum.
• When the client application needs to be
unaware of object creation and
representation.
Implementation
• We are going to create an interface Prototype that
contains a method getClone() of Prototype type.
• Then, we create a concrete class
EmployeeRecord whichimplements Prototype
interface that does the cloning of Employee Record
object.
• PrototypeDemo class will uses this concrete
class EmployeeRecord.
• Known uses
The first widely known application o f the
pattern in an objectoriented language was in
ThingLab, where users could form a composite
object and then promote it to a prototype by
installing it in a library of reusable objects
Related patterns

• Prototype and Abstract Factory are competing


patterns in some ways
• Designs that make heavy use of the
Composite and Decorator patterns often can
benefit from Prototype as well.

You might also like