SlideShare una empresa de Scribd logo
1 de 25
Descargar para leer sin conexión
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

Más contenido relacionado

Similar a Factory patterns

Software System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptxSoftware System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptxssuser9a23691
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ ComparatorSean McElrath
 
Creational pattern
Creational patternCreational pattern
Creational patternHimanshu
 
Static and Dynamic polymorphism in C++
Static and Dynamic polymorphism in C++Static and Dynamic polymorphism in C++
Static and Dynamic polymorphism in C++Anil Bapat
 
Bringing classical OOP into JavaScript
Bringing classical OOP into JavaScriptBringing classical OOP into JavaScript
Bringing classical OOP into JavaScriptDmitry Sheiko
 
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 Infrastructuremichael.labriola
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204ealio
 
Layers of Smalltalk Application
Layers of Smalltalk ApplicationLayers of Smalltalk Application
Layers of Smalltalk Applicationspeludner
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2Naga Muruga
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method PatternGeoff Burns
 
Factory Method Design Pattern
Factory Method Design PatternFactory Method Design Pattern
Factory Method Design Patternmelbournepatterns
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Patternguestcb0002
 
Snippet for .net
Snippet for .netSnippet for .net
Snippet for .netSireesh K
 
Introduction to JavaScript design patterns
Introduction to JavaScript design patternsIntroduction to JavaScript design patterns
Introduction to JavaScript design patternsJeremy Duvall
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design patternMindfire Solutions
 
Code snippets
Code snippetsCode snippets
Code snippetsSireesh K
 

Similar a 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
 

Último

Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableCall Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableDipal Arora
 
Pharma Works Profile of Karan Communications
Pharma Works Profile of Karan CommunicationsPharma Works Profile of Karan Communications
Pharma Works Profile of Karan Communicationskarancommunications
 
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Sheetaleventcompany
 
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Dipal Arora
 
Organizational Transformation Lead with Culture
Organizational Transformation Lead with CultureOrganizational Transformation Lead with Culture
Organizational Transformation Lead with CultureSeta Wicaksana
 
Call Girls In Noida 959961⊹3876 Independent Escort Service Noida
Call Girls In Noida 959961⊹3876 Independent Escort Service NoidaCall Girls In Noida 959961⊹3876 Independent Escort Service Noida
Call Girls In Noida 959961⊹3876 Independent Escort Service Noidadlhescort
 
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876dlhescort
 
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
 
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Dave Litwiller
 
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangaloreamitlee9823
 
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableCall Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableSeo
 
Insurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usageInsurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usageMatteo Carbone
 
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdfRenandantas16
 
Katrina Personal Brand Project and portfolio 1
Katrina Personal Brand Project and portfolio 1Katrina Personal Brand Project and portfolio 1
Katrina Personal Brand Project and portfolio 1kcpayne
 
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...rajveerescorts2022
 
Dr. Admir Softic_ presentation_Green Club_ENG.pdf
Dr. Admir Softic_ presentation_Green Club_ENG.pdfDr. Admir Softic_ presentation_Green Club_ENG.pdf
Dr. Admir Softic_ presentation_Green Club_ENG.pdfAdmir Softic
 
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLBAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLkapoorjyoti4444
 
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...lizamodels9
 

Último (20)

Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableCall Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
 
Pharma Works Profile of Karan Communications
Pharma Works Profile of Karan CommunicationsPharma Works Profile of Karan Communications
Pharma Works Profile of Karan Communications
 
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
 
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
 
Organizational Transformation Lead with Culture
Organizational Transformation Lead with CultureOrganizational Transformation Lead with Culture
Organizational Transformation Lead with Culture
 
Call Girls In Noida 959961⊹3876 Independent Escort Service Noida
Call Girls In Noida 959961⊹3876 Independent Escort Service NoidaCall Girls In Noida 959961⊹3876 Independent Escort Service Noida
Call Girls In Noida 959961⊹3876 Independent Escort Service Noida
 
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
 
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...
 
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
 
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableCall Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
 
VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
 
Insurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usageInsurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usage
 
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
 
Forklift Operations: Safety through Cartoons
Forklift Operations: Safety through CartoonsForklift Operations: Safety through Cartoons
Forklift Operations: Safety through Cartoons
 
Katrina Personal Brand Project and portfolio 1
Katrina Personal Brand Project and portfolio 1Katrina Personal Brand Project and portfolio 1
Katrina Personal Brand Project and portfolio 1
 
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
 
Dr. Admir Softic_ presentation_Green Club_ENG.pdf
Dr. Admir Softic_ presentation_Green Club_ENG.pdfDr. Admir Softic_ presentation_Green Club_ENG.pdf
Dr. Admir Softic_ presentation_Green Club_ENG.pdf
 
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLBAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
 
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
 

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.