0% found this document useful (0 votes)
61 views

8 - Creational Design Pattern

The document discusses design patterns, specifically focusing on creational patterns. It defines what design patterns and creational patterns are, provides examples of common creational patterns like the abstract factory and builder patterns, and explains how to implement them. The abstract factory pattern provides a way to encapsulate object creation and allows clients to vary products independently of their implementations. The builder pattern separates object construction from representation, allowing the same construction steps to create different types of objects.

Uploaded by

Coding Vault
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

8 - Creational Design Pattern

The document discusses design patterns, specifically focusing on creational patterns. It defines what design patterns and creational patterns are, provides examples of common creational patterns like the abstract factory and builder patterns, and explains how to implement them. The abstract factory pattern provides a way to encapsulate object creation and allows clients to vary products independently of their implementations. The builder pattern separates object construction from representation, allowing the same construction steps to create different types of objects.

Uploaded by

Coding Vault
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Creational patterns

Mohsin Bilal
Design patterns
• design pattern:
A standard solution to a common software problem in a
context.
• describes a recurring software structure or idiom
• is abstract from any particular programming language
• identifies classes and their roles in the solution to a problem

• in 1990 a group called the Gang of Four or "GoF"


(Gamma, Helm, Johnson, Vlissides) compile a
catalog of design patterns
• 1995 book Design Patterns:
Elements of Reusable Object-Oriented
Software is a classic of the field
Describing a pattern
• Problem: In what situation should this pattern be used?

• Solution: What should you do? What is the pattern?


• describe details of the objects/classes/structure needed
• should be somewhat language-neutral

• Advantages: Why is this pattern useful?

• Disadvantages: Why might someone not want this pattern?


Gang of Four (GoF) patterns
• Creational Patterns (abstracting the object-instantiation process)
• Factory Method Abstract Factory Singleton
• Builder Prototype

• Structural Patterns (how objects/classes can be combined)


• Adapter Bridge Composite
• Decorator Facade Flyweight
• Proxy

• Behavioral Patterns (communication between objects)


• Command Interpreter Iterator
• Mediator Observer State
• Strategy Chain of Responsibility Visitor
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
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
Singleton pattern
• Singleton pattern is one of the simplest design patterns in Java.
• This pattern involves a single class which is responsible to create an object while
making sure that only single object gets created.
• Singleton class should be globally accessible.
• java.lang.Runtime and java.awt.Desktop are 2 singleton classes provided by JVM
• This class provides a way to access its only object which can be accessed directly
without need to instantiate the object of the class.
• Used to prevent concurrent access, e.g., for hardware interface access, logging,
and cache etc.
Singleton class - implementation
• Two step implementation:

1. Create a Singleton Class.


2. Get the only object from the singleton class.
Singleton class - implementation
Abstract Factory: An Example
• PIM system
• Manage addresses and phone numbers
• Let’s say it’s hard-coded it for some country’s data
• At some point, we wanted to extend it to incorporate any address / phone
number
• So, we subclassed
• DutchAddress, JapanesePhoneNumber, etc.
• But now, how do we create them?
Abstract Factory: Overview
• Intent
• Provide an interface for creating families of related or
dependent objects without specifying their concrete
classes
• Analogous to a pasta maker
Your code is the pasta maker
Different disks create different pasta shapes:
these are the factories
All disks have certain properties in common
so that they will work with the pasta maker
All pastas have certain characteristics in
common that are inherited from the generic
“Pasta” object
Abstract Factory pattern
• Work around a super-factory which creates other factories – factory
of factories

• 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.
Abstract Factory: Participants
• AbstractFactory
Declares an interface for operations that create
abstract products

• ConcreteFactory
Implements the operations to create concrete
product objects: usually
instantiated as a Singleton

• AbstractProduct
Declares 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
Implementation
1. Create a Shape interface

2. Create concrete classes implementing the same


interface Rectangle, RoundedRectangle etc.)

3. Create an AbstractFactory to get factories for


Normal and Rounded Shape Objects

4. Create Shape Factory and RoundedShapeFactory


classes extending AbstractFactory to generate object
of concrete class based on given information.

5. Create a FactoryProducer to get factories either


RoundedShapeFactory or ShapeFactory

6. Use the FactoryProducer to get AbstractFactory in


order to get factories of concrete classes by passing an
information such as type.
Boolean rounded
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
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
Abstract Factory: Implementation
• Usually should be a Singleton
• Define a Factory Method (GoF) in AbstractFactory –
ConcreteFactory then specifies its products by
overriding the factory for each
public class USAddressFactory implements AddressFactory{
public Address createAddress(){
return new USAddress();
}

public PhoneNumber createPhoneNumber(){


return new USPhoneNumber();
}
}
Builder: Overview
• Intent
• Separate the construction of a complex object from its
representation so that the same construction process can
create different representations
• Think of a car factory
• Boss tells workers (or
robots) to build each
part of a car
• Workers build each
part and add them to
the car being constructed
Builder: Participants
• Builder – the abstract class of all workers
Specifies an abstract interface for creating parts of a Product object

• ConcreteBuilder – A specific worker


Constructs and assembles parts of the product by implementing the Builder interface

• Director – the boss


Constructs an object using the Builder interface

• Product – the car


Represents the complex
object under construction

Includes classes that define


the constituent parts

Gives interfaces for assembling the parts


Builder: Collaborations
• Client creates Director object and configures it with a Builder
• Director notifies Builder to build each part of the product
• Builder handles requests from Director and adds parts to the product
• Client retrieves product from the Builder
Builder: Applicability
• Use Builder 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
being constructed
• The building process can be broken down into discrete steps (difference
between Builder and Abstract Factory)
Builder: Consequences
• Lets you vary a product’s internal representation by using different
Builders
• Isolates code for construction and representation
• Gives finer-grain control over the construction process
Builder: Implementation
• Issues to consider:
• Assembly and construction interface: generality
• Is an abstract class for all Products necessary?
• Usually products don’t have a common interface
• Usually there’s an abstract Builder class that defines an
operation for each component that a director may ask it to
create.
• These operations do nothing by default (empty, non-virtual
methods in C++)
• The ConcreteBuilder overrides operations selectively
Fast-food restaurant example
1. Create an interface Item representing food item and a
Packing interface
2. Create concrete classes implementing the Packing
interface
3. Create abstract classes implementing the Item
interface providing default functionalities.
4. Create concrete classes extending Burger and
ColdDrink classes
5. Create a Meal class having Item objects defined
above.
6. Create a MealBuilder class, the actual builder class
responsible to create Meal objects.
7. BuiderPatternDemo uses MealBuider to
demonstrate builder pattern.
AbstractFactory Builder
Factory of factories, family of Construction of complex object
products building discrete parts separately
Conclusions
• Creational design patterns are beneficial in that they allow your
software to tightly control the way in which it constructs objects
• Separate users of the code from the messy details of creating and
building objects
Conclusions
• Abstract Factory:
• Lets you choose what family of products to create at runtime
• Isolates the implementation from clients, since clients only use the interfaces
• Makes exchanging product families simple
Conclusions
• Builder:
• Lets you vary how a product gets assembled.
• Can define a new kind of builder for a product to assemble it in a different
way
• Client doesn’t need to know anything about the construction process, nor the
parts that make up a product.

You might also like