SlideShare a Scribd company logo
1 of 25
Download to read offline
Text
Factory Patterns
Contents
Basics (Review)
(Simple) Factory Pattern
Factory Method Pattern
Abstract Factory Pattern
Factory Method vs Abstract
Factory Pattern
Basics (Review)
B1: Interface, Abstract Class, and
Concrete Class
An interface is an empty shell, there are only the signatures
(name / params / return type) of the methods.
Abstract classes look a lot like interfaces, but they have
something more : you can define a behavior for them.
When you use new you are certainly instantiating a
concrete class, so that’s definitely an implementation, not
an interface.
B2: Class Diagram
Association is reference based relationship between two
classes.
Dependency is often confused as Association. Dependency
is normally created when you receive a reference to a class
as part of a particular operation / method.
An extends relationship (also called an inheritance or an is-a
relationship) implies that a specialized (child) class is based on a
general (parent) class.
An implements relationship exists between two classes when one of
them must implement, or realize, the behavior specified by the other.
Aggregation is same as association and is often seen as redundant
relationship. A common perception is that aggregation represents one-
to-many / many-to-many / part-whole relationships
Composition relates to instance creational responsibility. When class B
is composed by class A, class A instance owns the creation or controls
lifetime of instance of class B.
Simple Factory Pattern
creates objects without exposing the instantiation logic to
the client.
refers to the newly created object through a common
interface.
# Not using Simple Factory!
class PizzaStore!
def order_pizza(pizza_type)!
pizza = case pizza_type.downcase!
when "cheese"!
CheesePizza.new!
when "clam"!
ClamPizza.new!
when "veggie"!
VeggiePizza.new!
else!
raise "Unknown"!
end!
pizza.prepare!
pizza.bake!
pizza.cut!
pizza.box!
pizza!
end!
end!
!
class Pizza!
# more codes!
end!
!
class CheesePizza < Pizza!
# more codes!
end!
!
class ClamPizza < Pizza!
# more codes!
end!
!
class VeggiePizza < Pizza!
# more codes!
end
# Using Simple Factory!
class PizzaStore!
attr_accessor :factory!
!
def initialize(factory)!
@factory = factory!
end!
!
def order_pizza(pizza_type)!
pizza = factory.create_pizza(pizza_type)!
pizza.prepare!
pizza.bake!
pizza.cut!
pizza.box!
pizza!
end!
end!
!
class SimplePizzaFactory!
def create_pizza(pizza_type)!
case pizza_type.downcase!
when "cheese"!
CheesePizza.new!
when "clam"!
ClamPizza.new!
when "veggie"!
VeggiePizza.new!
else!
raise "Unknown"!
end!
end!
end!
def self.create_pizza(pizza_type)!
const_get("#{pizza_type.capitalize}Pizza").new!
end
Factory Method Pattern
Defines an interface for creating objects, but let subclasses
to decide which class to instantiate.
Refers to the newly created object through a common
interface.
class PizzaStore!
def order_pizza(pizza_type)!
pizza = create_pizza(pizza_type)!
pizza.prepare!
pizza.bake!
pizza.cut!
pizza.box!
pizza!
end!
!
def create_pizza(pizza_type)!
raise "need to implement"!
end!
end!
!
class NYPizzaStore < PizzaStore!
def create_pizza(pizza_type)!
const_get("NYStyle#{pizza_type.capitalize}Pizza")!
end!
end!
!
class ChicagoPizzaStore < PizzaStore!
def create_pizza(pizza_type)!
const_get("ChicagoStyle#{pizza_type.capitalize}Pizza")!
end!
end!
!
class NYStyleCheesePizza < Pizza!
def prepare!
"prepare for cheese pizza of NY style"!
end!
end
Abstract Factory Pattern
Abstract Factory offers the interface for creating a family of
related objects, without explicitly specifying their classes.
class PizzaStore!
attr_accessor :ingredient_factory!
!
def order_pizza(pizza_type)!
pizza = create_pizza(pizza_type)!
pizza.prepare!
pizza.bake!
pizza.cut!
pizza.box!
pizza!
end!
!
def create_pizza(pizza_type)!
raise "need to implement"!
end!
end!
!
class NYPizzaStore < PizzaStore!
def initialize!
@ingredient_factory = NYPizzaIngredientFactory.new!
end!
!
def create_pizza(pizza_type)!
# CheesePizza.new(ingredient_factory)!
self.class.const_get("#{pizza_type.capitalize}
Pizza").new(ingredient_factory)!
end!
end!
class Pizza!
attr_accessor :ingredient_factory, :name, :dough,!
:sauce, :cheese, :veggie, :pepperoni, :clam!
!
def initialize(ingredient_factory)!
@ingredient_factory = ingredient_factory;!
end!
def prepare!
raise "need to implement"!
end!
# more methods: bake, cut, box!
end!
!
class CheesePizza < Pizza !
def prepare!
puts "Preparing #{name}"!
@dough = ingredient_factory.create_dough!
@sauce = ingredient_factory.create_sauce!
@cheese = ingredient_factory.create_cheese!
end!
end!
!
class NYPizzaIngredientFactory < PizzaIngredientFactory!
def create_dough; ThinCrustDough.new end!
def create_sauce; MarinaraSauce.new end!
def create_cheese; ReggianoCheese.new end!
def create_veggies!
[ Garlic.new, Mushroom.new ]!
end!
def create_pepperoni; SlicedPepperoni.new end!
def create_clam; FreshClams.new end!
end
Factory Method vs. Abstract Factory
The methods of an Abstract Factory are implemented as factory
methods.
Both Abstract Factory and Factory Method create objects, but
Factory Method do it through inheritance, and Abstract do it
through object composition.
Abstract Factory is used whenever you have families of products
you need to create and you want to make sure your clients create
products that belong together.
Factory Method is used to decouple your client code from the
concrete classes you need to instantiate, or if you don’t know
ahead of time all the concrete classes you are going to need.
References
http://www.oodesign.com
http://stackoverflow.com/questions/1913098/what-is-the-
difference-between-an-interface-and-abstract-class
http://nirajrules.wordpress.com/2011/07/15/association-vs-
dependency-vs-aggregation-vs-composition/
http://www.amazon.com/Head-First-Design-Patterns-
Freeman/dp/0596007124
Code: https://github.com/kuyseng/design-patterns-in-ruby/
tree/first_head_factory

More Related Content

Similar to Factory patterns

How To Navigate And Extend The Flex Infrastructure
How To Navigate And Extend The Flex InfrastructureHow To Navigate And Extend The Flex Infrastructure
How To Navigate And Extend The Flex Infrastructure
michael.labriola
 
Layers of Smalltalk Application
Layers of Smalltalk ApplicationLayers of Smalltalk Application
Layers of Smalltalk Application
speludner
 

Similar to Factory patterns (19)

Software System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptxSoftware System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptx
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
 
Creational pattern
Creational patternCreational pattern
Creational pattern
 
Static and Dynamic polymorphism in C++
Static and Dynamic polymorphism in C++Static and Dynamic polymorphism in C++
Static and Dynamic polymorphism in C++
 
Composite pattern
Composite patternComposite pattern
Composite pattern
 
Bringing classical OOP into JavaScript
Bringing classical OOP into JavaScriptBringing classical OOP into JavaScript
Bringing classical OOP into JavaScript
 
How To Navigate And Extend The Flex Infrastructure
How To Navigate And Extend The Flex InfrastructureHow To Navigate And Extend The Flex Infrastructure
How To Navigate And Extend The Flex Infrastructure
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204
 
Layers of Smalltalk Application
Layers of Smalltalk ApplicationLayers of Smalltalk Application
Layers of Smalltalk Application
 
OOP
OOPOOP
OOP
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Factory Method Design Pattern
Factory Method Design PatternFactory Method Design Pattern
Factory Method Design Pattern
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Snippet for .net
Snippet for .netSnippet for .net
Snippet for .net
 
Introduction to JavaScript design patterns
Introduction to JavaScript design patternsIntroduction to JavaScript design patterns
Introduction to JavaScript design patterns
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
 
Code snippets
Code snippetsCode snippets
Code snippets
 

Recently uploaded

Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
daisycvs
 
Jual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan Cytotec
Jual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan CytotecJual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan Cytotec
Jual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan Cytotec
ZurliaSoop
 
Structuring and Writing DRL Mckinsey (1).pdf
Structuring and Writing DRL Mckinsey (1).pdfStructuring and Writing DRL Mckinsey (1).pdf
Structuring and Writing DRL Mckinsey (1).pdf
laloo_007
 
Mckinsey foundation level Handbook for Viewing
Mckinsey foundation level Handbook for ViewingMckinsey foundation level Handbook for Viewing
Mckinsey foundation level Handbook for Viewing
Nauman Safdar
 
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al MizharAl Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
allensay1
 

Recently uploaded (20)

Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGParadip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
 
Escorts in Nungambakkam Phone 8250092165 Enjoy 24/7 Escort Service Enjoy Your...
Escorts in Nungambakkam Phone 8250092165 Enjoy 24/7 Escort Service Enjoy Your...Escorts in Nungambakkam Phone 8250092165 Enjoy 24/7 Escort Service Enjoy Your...
Escorts in Nungambakkam Phone 8250092165 Enjoy 24/7 Escort Service Enjoy Your...
 
Buy gmail accounts.pdf buy Old Gmail Accounts
Buy gmail accounts.pdf buy Old Gmail AccountsBuy gmail accounts.pdf buy Old Gmail Accounts
Buy gmail accounts.pdf buy Old Gmail Accounts
 
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
 
Rice Manufacturers in India | Shree Krishna Exports
Rice Manufacturers in India | Shree Krishna ExportsRice Manufacturers in India | Shree Krishna Exports
Rice Manufacturers in India | Shree Krishna Exports
 
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
 
Marel Q1 2024 Investor Presentation from May 8, 2024
Marel Q1 2024 Investor Presentation from May 8, 2024Marel Q1 2024 Investor Presentation from May 8, 2024
Marel Q1 2024 Investor Presentation from May 8, 2024
 
How to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League CityHow to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League City
 
Jual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan Cytotec
Jual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan CytotecJual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan Cytotec
Jual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan Cytotec
 
Falcon Invoice Discounting: Unlock Your Business Potential
Falcon Invoice Discounting: Unlock Your Business PotentialFalcon Invoice Discounting: Unlock Your Business Potential
Falcon Invoice Discounting: Unlock Your Business Potential
 
Cracking the 'Career Pathing' Slideshare
Cracking the 'Career Pathing' SlideshareCracking the 'Career Pathing' Slideshare
Cracking the 'Career Pathing' Slideshare
 
PHX May 2024 Corporate Presentation Final
PHX May 2024 Corporate Presentation FinalPHX May 2024 Corporate Presentation Final
PHX May 2024 Corporate Presentation Final
 
Structuring and Writing DRL Mckinsey (1).pdf
Structuring and Writing DRL Mckinsey (1).pdfStructuring and Writing DRL Mckinsey (1).pdf
Structuring and Writing DRL Mckinsey (1).pdf
 
Over the Top (OTT) Market Size & Growth Outlook 2024-2030
Over the Top (OTT) Market Size & Growth Outlook 2024-2030Over the Top (OTT) Market Size & Growth Outlook 2024-2030
Over the Top (OTT) Market Size & Growth Outlook 2024-2030
 
New 2024 Cannabis Edibles Investor Pitch Deck Template
New 2024 Cannabis Edibles Investor Pitch Deck TemplateNew 2024 Cannabis Edibles Investor Pitch Deck Template
New 2024 Cannabis Edibles Investor Pitch Deck Template
 
Uneak White's Personal Brand Exploration Presentation
Uneak White's Personal Brand Exploration PresentationUneak White's Personal Brand Exploration Presentation
Uneak White's Personal Brand Exploration Presentation
 
Phases of Negotiation .pptx
 Phases of Negotiation .pptx Phases of Negotiation .pptx
Phases of Negotiation .pptx
 
CROSS CULTURAL NEGOTIATION BY PANMISEM NS
CROSS CULTURAL NEGOTIATION BY PANMISEM NSCROSS CULTURAL NEGOTIATION BY PANMISEM NS
CROSS CULTURAL NEGOTIATION BY PANMISEM NS
 
Mckinsey foundation level Handbook for Viewing
Mckinsey foundation level Handbook for ViewingMckinsey foundation level Handbook for Viewing
Mckinsey foundation level Handbook for Viewing
 
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al MizharAl Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
 

Factory patterns

  • 2. Contents Basics (Review) (Simple) Factory Pattern Factory Method Pattern Abstract Factory Pattern Factory Method vs Abstract Factory Pattern
  • 4. B1: Interface, Abstract Class, and Concrete Class An interface is an empty shell, there are only the signatures (name / params / return type) of the methods. Abstract classes look a lot like interfaces, but they have something more : you can define a behavior for them. When you use new you are certainly instantiating a concrete class, so that’s definitely an implementation, not an interface.
  • 6. Association is reference based relationship between two classes. Dependency is often confused as Association. Dependency is normally created when you receive a reference to a class as part of a particular operation / method.
  • 7. An extends relationship (also called an inheritance or an is-a relationship) implies that a specialized (child) class is based on a general (parent) class. An implements relationship exists between two classes when one of them must implement, or realize, the behavior specified by the other.
  • 8. Aggregation is same as association and is often seen as redundant relationship. A common perception is that aggregation represents one- to-many / many-to-many / part-whole relationships Composition relates to instance creational responsibility. When class B is composed by class A, class A instance owns the creation or controls lifetime of instance of class B.
  • 10. creates objects without exposing the instantiation logic to the client. refers to the newly created object through a common interface.
  • 11.
  • 12. # Not using Simple Factory! class PizzaStore! def order_pizza(pizza_type)! pizza = case pizza_type.downcase! when "cheese"! CheesePizza.new! when "clam"! ClamPizza.new! when "veggie"! VeggiePizza.new! else! raise "Unknown"! end! pizza.prepare! pizza.bake! pizza.cut! pizza.box! pizza! end! end! ! class Pizza! # more codes! end! ! class CheesePizza < Pizza! # more codes! end! ! class ClamPizza < Pizza! # more codes! end! ! class VeggiePizza < Pizza! # more codes! end # Using Simple Factory! class PizzaStore! attr_accessor :factory! ! def initialize(factory)! @factory = factory! end! ! def order_pizza(pizza_type)! pizza = factory.create_pizza(pizza_type)! pizza.prepare! pizza.bake! pizza.cut! pizza.box! pizza! end! end! ! class SimplePizzaFactory! def create_pizza(pizza_type)! case pizza_type.downcase! when "cheese"! CheesePizza.new! when "clam"! ClamPizza.new! when "veggie"! VeggiePizza.new! else! raise "Unknown"! end! end! end! def self.create_pizza(pizza_type)! const_get("#{pizza_type.capitalize}Pizza").new! end
  • 14. Defines an interface for creating objects, but let subclasses to decide which class to instantiate. Refers to the newly created object through a common interface.
  • 15.
  • 16.
  • 17. class PizzaStore! def order_pizza(pizza_type)! pizza = create_pizza(pizza_type)! pizza.prepare! pizza.bake! pizza.cut! pizza.box! pizza! end! ! def create_pizza(pizza_type)! raise "need to implement"! end! end! ! class NYPizzaStore < PizzaStore! def create_pizza(pizza_type)! const_get("NYStyle#{pizza_type.capitalize}Pizza")! end! end! ! class ChicagoPizzaStore < PizzaStore! def create_pizza(pizza_type)! const_get("ChicagoStyle#{pizza_type.capitalize}Pizza")! end! end! ! class NYStyleCheesePizza < Pizza! def prepare! "prepare for cheese pizza of NY style"! end! end
  • 19. Abstract Factory offers the interface for creating a family of related objects, without explicitly specifying their classes.
  • 20.
  • 21.
  • 22. class PizzaStore! attr_accessor :ingredient_factory! ! def order_pizza(pizza_type)! pizza = create_pizza(pizza_type)! pizza.prepare! pizza.bake! pizza.cut! pizza.box! pizza! end! ! def create_pizza(pizza_type)! raise "need to implement"! end! end! ! class NYPizzaStore < PizzaStore! def initialize! @ingredient_factory = NYPizzaIngredientFactory.new! end! ! def create_pizza(pizza_type)! # CheesePizza.new(ingredient_factory)! self.class.const_get("#{pizza_type.capitalize} Pizza").new(ingredient_factory)! end! end!
  • 23. class Pizza! attr_accessor :ingredient_factory, :name, :dough,! :sauce, :cheese, :veggie, :pepperoni, :clam! ! def initialize(ingredient_factory)! @ingredient_factory = ingredient_factory;! end! def prepare! raise "need to implement"! end! # more methods: bake, cut, box! end! ! class CheesePizza < Pizza ! def prepare! puts "Preparing #{name}"! @dough = ingredient_factory.create_dough! @sauce = ingredient_factory.create_sauce! @cheese = ingredient_factory.create_cheese! end! end! ! class NYPizzaIngredientFactory < PizzaIngredientFactory! def create_dough; ThinCrustDough.new end! def create_sauce; MarinaraSauce.new end! def create_cheese; ReggianoCheese.new end! def create_veggies! [ Garlic.new, Mushroom.new ]! end! def create_pepperoni; SlicedPepperoni.new end! def create_clam; FreshClams.new end! end
  • 24. Factory Method vs. Abstract Factory The methods of an Abstract Factory are implemented as factory methods. Both Abstract Factory and Factory Method create objects, but Factory Method do it through inheritance, and Abstract do it through object composition. Abstract Factory is used whenever you have families of products you need to create and you want to make sure your clients create products that belong together. Factory Method is used to decouple your client code from the concrete classes you need to instantiate, or if you don’t know ahead of time all the concrete classes you are going to need.