SlideShare a Scribd company logo
Factory Method Pattern
Virtual Constructor
Sameer Singh Rathoud
About presentation
This presentation provide information to understand factory method pattern, it’s
various implementation and Applicability.
I have tried my best to explain the concept in very simple language.

The programming language used for implementation is c#. But any one from
different programming background can easily understand the implementation.
Definition
The factory method pattern is a design pattern that define an interface for

creating an object from one among a set of classes based on some logic.

Factory method pattern is a creational design pattern.
Factory method pattern is also known as virtual constructor pattern.

Factory method pattern is the most widely used pattern in the software
engineering world
Motivation and Intent
At times, application only knows about the super class (may be abstract class),
but doesn’t know which sub class (concrete implementation) to be instantiated at

compile time.
Choice of sub class may be based on factors like:
• Application configuration.
• Expansion of requirements or enhancements.
• The state of the application running.

• Creates objects without exposing the instantiation logic to the client.
• Refers to the newly created object through a common interface
Structure
Client uses Product

Client

Ask for a new Product

Factory
<< interface >>
Product

Inheritance

Concrete ProductA

Concrete ProductB

+CreateProduct(): Product
Implementation (C#)
Product product = new Product()

Product productA = new ProductA();
Product productB = new ProductB();

When we are using “new” keyword in C#, It allocates the
memory and creates a object of specified type.
This will be ok if we are having only one type of product
and a concrete class named “Product”.

But if we are having more than one product type, we can
create our “Product” as interface and provide various
implementation to it. Let the classes providing
implementation to our “Product” interface are “ProductA”
and “ProductB”. But now for Instantiating “Product” we
need to call the constructor of “Product” implementation.
But here Product type specified is fixed (hard-coded).
Let’s try for some generic implementation for this
scenario.
Implementation (C#)
public Product CreateProduct(string productType)
{
Product product = null;
if (productType.Equals("ProductA"))
{
product = new ProductA();
}
else if (productType.Equals("ProductB"))
{
product = new ProductB();
}
return product;
}

Client:
Product productA = CreateProduct(“ProductA”);
Product productB = CreateProduct(“ProductB”);

Here function “CreateProduct” provide us a
generic implementation of our scenario.
“CreateProduct” function takes argument as
“string productType” and returns a object of
“ProductA” or “ProductB” based on the
condition and now we can call this function
with particular type of product and we will
get the object.
Although the code shown is far from
perfection like:
• Argument “string productType” can be
replaced by an “enum”.
• “if else” condition can be replaced by
“switch case” statements … etc.
But we can call our function “CreateProduct”
as a factory.
Let’s try to explore a better factory for our
product.
Implementation (C#)
class ProductFactory {
public Product CreateProduct(string productType) {
Product product = null;
if (productType.Equals("ProductA")) {
product = new ProductA();
}
else if (productType.Equals("ProductB")){
product = new ProductB();
}
return product;
}
}
Client:
ProductFactory factory = new ProductFactory();
factory.CreateProduct(“ProductA”);
factory.CreateProduct(“ProductB”);

Instead of function “CreateProduct” we
can have a class “ProductFactory” which
will help us in creating product and
provide a better control (class can have
helper function for product like packaging
etc.) on creation of product.
Implementation (C#)
enum ProductType {
ProductA, ProductB,
};

Modified our “ProductFactory” class
by adding a “enum ProductType”
and added “switch” statement
instead of “If-else”.
Now our “ProductFactory” is good
to go.
If user is adding a new “ProductC”
in its product range, he a has to
define a new implementation to
Product
interface
(class
“ProductC”), Need to make changes
for
“ProductC”
in
enum
“ProductType” and need to add a
switch
case
in
our
“ProductFactory.CreateProduct”.

class ProductFactory {
public Product CreateProduct(ProductType productType) {
Product product = null;
switch(productType) {
case ProductType.ProductA:
product = new ProductA();
break;
case ProductType.ProductB:
product = new ProductB();
break;
default:
product = null;
break;
Client:
}
ProductFactory factory = new ProductFactory();
return product;
factory.CreateProduct(ProductType.ProductA);
}
factory.CreateProduct(ProductType.ProductB);
}
Options for adding new class without change in factory (C#)
If user is adding a new product in his product range he has to modify his “ProductFactory”. To
solve this problem we need a mechanism where “ProductFactory” is always aware of supported
Product types.

There can be two possible ways to achieve this solution:
• Using reflection (C#/Java).
• Without reflection (C++/C#/Java)
Factory using reflection (C#)
public enum ProductType : int {
ProductA = 1,
ProductB,
};
[AttributeUsage(AttributeTargets.Class)]
public class ProductAttribute : Attribute {
private ProductType mProductType;
public ProductAttribute(ProductType vProductType) {
mProductType = vProductType;
}
public ProductType ProductSupported {
get {
return mProductType;
}
set {
mProductType = value;
}
}
}
Factory using reflection continue ….
[AttributeUsage(AttributeTargets.Interface)]
public class ImplAttr : Attribute {
private Type[] mImplementorList;
public ImplAttr(Type[] Implementors) {
mImplementorList = Implementors;
}
public Type[] ImplementorList {
get {
return mImplementorList;
}
set {
mImplementorList = value;
}
}

}
Factory using reflection continue ….
[ImplAttr(new Type[] { typeof(ProductA), typeof(ProductB)})]
interface Product {
void Print();
}
[ProductAttribute(ProductType.ProductA)]
class ProductA : Product {
public void Print() {
Console.WriteLine("I am ProductA");
}
}
[ProductAttribute(ProductType.ProductB)]
class ProductB : Product {
public void Print() {
Console.WriteLine("I am ProductB");
}
}
Factory using reflection continue ….
class ProductFactory {
public Product CreateProduct(ProductType vProductType)
{
Product product = null;
object Obj;
Type[] IntrfaceImpl;
Attribute Attr;
ProductType productType;
ProductAttribute productAttr;
int ImplementorCount;
Attr = Attribute.GetCustomAttribute(typeof(Product), typeof(ImplAttr));
IntrfaceImpl = ((ImplAttr)Attr).ImplementorList;
ImplementorCount = IntrfaceImpl.GetLength(0);
for (int i = 0; i < ImplementorCount; i++) {
Attr = Attribute.GetCustomAttribute(IntrfaceImpl[i], typeof(ProductAttribute));
productAttr = (ProductAttribute)Attr;
Factory using reflection continue ….
productType = productAttr.ProductSupported;

if ((int)productType == (int)vProductType) {
Obj = Activator.CreateInstance(IntrfaceImpl[i]);
product = (Product)Obj;

break;
}
}
return product;
}
}
Factory using reflection continue ….
class Client

{
static void Main(string[] args)
{

ProductFactory factory = new ProductFactory();
Product product = factory.CreateProduct(ProductType.ProductA);
product.Print();
}
}
In the above mentioned code, we are having a factory which will remain unchanged even when user
is adding in product classes (new implementation of Product Interface) in his product range. In the
above implementation we have used reflection to achieve our objective.
Factory without reflection
class ProductFactory {
private static Dictionary<string, Product> registeredProducts = new Dictionary<string,Product>();
private static ProductFactory factoryInstance = new ProductFactory();
private ProductFactory() {
}
public static ProductFactory Instance {
get {
return factoryInstance;
}
}

public void registerProduct(String productID, Product p) {
registeredProducts.Add(productID, p);
}
Factory without reflection continue ….
public Product createProduct(String productID) {
Product product = null;
if (registeredProducts.ContainsKey(productID)) {
product = (Product)registeredProducts[productID];
}
return product;
}
}
Factory without reflection continue ….
interface Product {
void Print();
}
class ProductA: Product {
public static void RegisterID(string id) {
ProductFactory.Instance.registerProduct(id, new ProductA());
}
public void Print() {
System.Console.WriteLine("I am ProductA");
}
}
class ProductB : Product {
public static void RegisterID(string id) {
ProductFactory.Instance.registerProduct(id, new ProductB());
}
public void Print() {
System.Console.WriteLine("I am ProductB");
}
}
Factory without reflection continue ….
class Client {
static void Main(string[] args) {
ProductFactory factory = ProductFactory.Instance;
ProductA.RegisterID("ProductA");
Product productA = factory.createProduct("ProductA");
((ProductA)productA).Print();
ProductB.RegisterID("ProductB");
Product productB = factory.createProduct("ProductB");
((ProductB)productB).Print();
}
}
In the above mentioned code, we are having a factory which will remain unchanged even when user
is adding in product classes (new implementation of Product Interface) in his product range. The
above implementation is achieved without reflection. In the above implementation the
“ProductFactory” class is created as singleton.
End of Presentation . . .

More Related Content

What's hot (20)

Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
Rana Muhammad Asif
 
An introduction to inkscape
An introduction to inkscapeAn introduction to inkscape
An introduction to inkscape
Ange Albertini
 
Design patterns
Design patternsDesign patterns
Design patterns
Elyes Mejri
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Pattern
Shahriar Hyder
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Satheesh Sukumaran
 
Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
Shakil Ahmed
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
Sanae BEKKAR
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Pattern
sahilrk911
 
Decorator Pattern
Decorator PatternDecorator Pattern
Decorator Pattern
Dimuthu Anuraj
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Arif Ansari
 
Design patterns
Design patternsDesign patterns
Design patterns
abhisheksagi
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
Mindfire Solutions
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
Shakil Ahmed
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
Varun Arora
 
Refactoring and code smells
Refactoring and code smellsRefactoring and code smells
Refactoring and code smells
Paul Nguyen
 
Facade pattern
Facade patternFacade pattern
Facade pattern
JAINIK PATEL
 
Visitor design pattern
Visitor design patternVisitor design pattern
Visitor design pattern
Salem-Kabbani
 
Introduction To Django
Introduction To DjangoIntroduction To Django
Introduction To Django
Jay Graves
 
Django Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersDjango Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python Developers
Rosario Renga
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
Simon Willison
 
An introduction to inkscape
An introduction to inkscapeAn introduction to inkscape
An introduction to inkscape
Ange Albertini
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
Sanae BEKKAR
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Pattern
sahilrk911
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
Mindfire Solutions
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
Varun Arora
 
Refactoring and code smells
Refactoring and code smellsRefactoring and code smells
Refactoring and code smells
Paul Nguyen
 
Visitor design pattern
Visitor design patternVisitor design pattern
Visitor design pattern
Salem-Kabbani
 
Introduction To Django
Introduction To DjangoIntroduction To Django
Introduction To Django
Jay Graves
 
Django Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersDjango Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python Developers
Rosario Renga
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
Simon Willison
 

Viewers also liked (7)

Factory method pattern
Factory method patternFactory method pattern
Factory method pattern
Shahriar Iqbal Chowdhury
 
Factory method
Factory method Factory method
Factory method
Hibatallah Aouadni
 
Factory Method Design Pattern
Factory Method Design PatternFactory Method Design Pattern
Factory Method Design Pattern
melbournepatterns
 
Reflection in Java
Reflection in JavaReflection in Java
Reflection in Java
Nikhil Bhardwaj
 
Reflection in java
Reflection in javaReflection in java
Reflection in java
upen.rockin
 
Design pattern - Software Engineering
Design pattern - Software EngineeringDesign pattern - Software Engineering
Design pattern - Software Engineering
Nadimozzaman Pappo
 
Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder
paramisoft
 
Factory Method Design Pattern
Factory Method Design PatternFactory Method Design Pattern
Factory Method Design Pattern
melbournepatterns
 
Reflection in java
Reflection in javaReflection in java
Reflection in java
upen.rockin
 
Design pattern - Software Engineering
Design pattern - Software EngineeringDesign pattern - Software Engineering
Design pattern - Software Engineering
Nadimozzaman Pappo
 
Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder
paramisoft
 

Similar to Factory method pattern (Virtual Constructor) (20)

Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
Anjan Kumar Bollam
 
Unit 2-Design Patterns.ppt
Unit 2-Design Patterns.pptUnit 2-Design Patterns.ppt
Unit 2-Design Patterns.ppt
MsRAMYACSE
 
03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdf03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdf
ssusera587d2
 
Code Like a Ninja Session 7 - Creational Design Patterns
Code Like a Ninja Session 7 - Creational Design PatternsCode Like a Ninja Session 7 - Creational Design Patterns
Code Like a Ninja Session 7 - Creational Design Patterns
Deon Meyer
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
Betclic Everest Group Tech Team
 
OOPSDesign PPT ( introduction to opps and design (
OOPSDesign PPT ( introduction to opps and design (OOPSDesign PPT ( introduction to opps and design (
OOPSDesign PPT ( introduction to opps and design (
bhfcvh531
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
Sergio Ronchi
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
Naga Muruga
 
Software System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptxSoftware System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptx
ssuser9a23691
 
Design patterns and Refactoring
Design patterns and RefactoringDesign patterns and Refactoring
Design patterns and Refactoring
Valerio Maggio
 
design patter related ppt and presentation
design patter related ppt and presentationdesign patter related ppt and presentation
design patter related ppt and presentation
Indu32
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
Gaurav Tyagi
 
Dot Net Design Patterns Interview Questions PDF By ScholarHat
Dot Net Design Patterns Interview Questions PDF By ScholarHatDot Net Design Patterns Interview Questions PDF By ScholarHat
Dot Net Design Patterns Interview Questions PDF By ScholarHat
Scholarhat
 
Design patterns
Design patternsDesign patterns
Design patterns
◄ vaquar khan ► ★✔
 
Object Oriented Programming with Object Orinted Concepts
Object Oriented Programming with Object Orinted ConceptsObject Oriented Programming with Object Orinted Concepts
Object Oriented Programming with Object Orinted Concepts
farhanghafoor5
 
Creational Patterns
Creational PatternsCreational Patterns
Creational Patterns
Asma CHERIF
 
Joel Landis Net Portfolio
Joel Landis Net PortfolioJoel Landis Net Portfolio
Joel Landis Net Portfolio
jlshare
 
Software Patterns
Software PatternsSoftware Patterns
Software Patterns
Artem Tabalin
 
Framework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users GroupFramework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users Group
brada
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
Srikanth R Vaka
 
Unit 2-Design Patterns.ppt
Unit 2-Design Patterns.pptUnit 2-Design Patterns.ppt
Unit 2-Design Patterns.ppt
MsRAMYACSE
 
03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdf03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdf
ssusera587d2
 
Code Like a Ninja Session 7 - Creational Design Patterns
Code Like a Ninja Session 7 - Creational Design PatternsCode Like a Ninja Session 7 - Creational Design Patterns
Code Like a Ninja Session 7 - Creational Design Patterns
Deon Meyer
 
OOPSDesign PPT ( introduction to opps and design (
OOPSDesign PPT ( introduction to opps and design (OOPSDesign PPT ( introduction to opps and design (
OOPSDesign PPT ( introduction to opps and design (
bhfcvh531
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
Naga Muruga
 
Software System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptxSoftware System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptx
ssuser9a23691
 
Design patterns and Refactoring
Design patterns and RefactoringDesign patterns and Refactoring
Design patterns and Refactoring
Valerio Maggio
 
design patter related ppt and presentation
design patter related ppt and presentationdesign patter related ppt and presentation
design patter related ppt and presentation
Indu32
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
Gaurav Tyagi
 
Dot Net Design Patterns Interview Questions PDF By ScholarHat
Dot Net Design Patterns Interview Questions PDF By ScholarHatDot Net Design Patterns Interview Questions PDF By ScholarHat
Dot Net Design Patterns Interview Questions PDF By ScholarHat
Scholarhat
 
Object Oriented Programming with Object Orinted Concepts
Object Oriented Programming with Object Orinted ConceptsObject Oriented Programming with Object Orinted Concepts
Object Oriented Programming with Object Orinted Concepts
farhanghafoor5
 
Creational Patterns
Creational PatternsCreational Patterns
Creational Patterns
Asma CHERIF
 
Joel Landis Net Portfolio
Joel Landis Net PortfolioJoel Landis Net Portfolio
Joel Landis Net Portfolio
jlshare
 
Framework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users GroupFramework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users Group
brada
 

More from Sameer Rathoud (8)

Platformonomics
PlatformonomicsPlatformonomics
Platformonomics
Sameer Rathoud
 
AreWePreparedForIoT
AreWePreparedForIoTAreWePreparedForIoT
AreWePreparedForIoT
Sameer Rathoud
 
Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
Sameer Rathoud
 
Decorator design pattern (A Gift Wrapper)
Decorator design pattern (A Gift Wrapper)Decorator design pattern (A Gift Wrapper)
Decorator design pattern (A Gift Wrapper)
Sameer Rathoud
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
Sameer Rathoud
 
Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)
Sameer Rathoud
 
Builder Design Pattern (Generic Construction -Different Representation)
Builder Design Pattern (Generic Construction -Different Representation)Builder Design Pattern (Generic Construction -Different Representation)
Builder Design Pattern (Generic Construction -Different Representation)
Sameer Rathoud
 
Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)
Sameer Rathoud
 
Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
Sameer Rathoud
 
Decorator design pattern (A Gift Wrapper)
Decorator design pattern (A Gift Wrapper)Decorator design pattern (A Gift Wrapper)
Decorator design pattern (A Gift Wrapper)
Sameer Rathoud
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
Sameer Rathoud
 
Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)
Sameer Rathoud
 
Builder Design Pattern (Generic Construction -Different Representation)
Builder Design Pattern (Generic Construction -Different Representation)Builder Design Pattern (Generic Construction -Different Representation)
Builder Design Pattern (Generic Construction -Different Representation)
Sameer Rathoud
 
Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)
Sameer Rathoud
 

Recently uploaded (20)

Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
TrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy ContractingTrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy Contracting
TrustArc
 
Master tester AI toolbox - Kari Kakkonen at Testaus ja AI 2025 Professio
Master tester AI toolbox - Kari Kakkonen at Testaus ja AI 2025 ProfessioMaster tester AI toolbox - Kari Kakkonen at Testaus ja AI 2025 Professio
Master tester AI toolbox - Kari Kakkonen at Testaus ja AI 2025 Professio
Kari Kakkonen
 
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk TechniciansOffshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
john823664
 
Contributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptxContributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptx
Patrick Lumumba
 
Splunk Leadership Forum Wien - 20.05.2025
Splunk Leadership Forum Wien - 20.05.2025Splunk Leadership Forum Wien - 20.05.2025
Splunk Leadership Forum Wien - 20.05.2025
Splunk
 
Measuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI SuccessMeasuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI Success
Nikki Chapple
 
Introducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRCIntroducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRC
Adtran
 
"AI in the browser: predicting user actions in real time with TensorflowJS", ...
"AI in the browser: predicting user actions in real time with TensorflowJS", ..."AI in the browser: predicting user actions in real time with TensorflowJS", ...
"AI in the browser: predicting user actions in real time with TensorflowJS", ...
Fwdays
 
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...
pranavbodhak
 
Security Operations and the Defense Analyst - Splunk Certificate
Security Operations and the Defense Analyst - Splunk CertificateSecurity Operations and the Defense Analyst - Splunk Certificate
Security Operations and the Defense Analyst - Splunk Certificate
VICTOR MAESTRE RAMIREZ
 
Break Down of Service Mesh Concepts and Implementation in AWS EKS.pptx
Break Down of Service Mesh Concepts and Implementation in AWS EKS.pptxBreak Down of Service Mesh Concepts and Implementation in AWS EKS.pptx
Break Down of Service Mesh Concepts and Implementation in AWS EKS.pptx
Mohammad Jomaa
 
SAP Sapphire 2025 ERP1612 Enhancing User Experience with SAP Fiori and AI
SAP Sapphire 2025 ERP1612 Enhancing User Experience with SAP Fiori and AISAP Sapphire 2025 ERP1612 Enhancing User Experience with SAP Fiori and AI
SAP Sapphire 2025 ERP1612 Enhancing User Experience with SAP Fiori and AI
Peter Spielvogel
 
AI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AI
AI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AIAI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AI
AI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AI
Buhake Sindi
 
cloudgenesis cloud workshop , gdg on campus mita
cloudgenesis cloud workshop , gdg on campus mitacloudgenesis cloud workshop , gdg on campus mita
cloudgenesis cloud workshop , gdg on campus mita
siyaldhande02
 
Introducing Ensemble Cloudlet vRouter
Introducing Ensemble  Cloudlet vRouterIntroducing Ensemble  Cloudlet vRouter
Introducing Ensemble Cloudlet vRouter
Adtran
 
Marko.js - Unsung Hero of Scalable Web Frameworks (DevDays 2025)
Marko.js - Unsung Hero of Scalable Web Frameworks (DevDays 2025)Marko.js - Unsung Hero of Scalable Web Frameworks (DevDays 2025)
Marko.js - Unsung Hero of Scalable Web Frameworks (DevDays 2025)
Eugene Fidelin
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
TrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy ContractingTrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy Contracting
TrustArc
 
Master tester AI toolbox - Kari Kakkonen at Testaus ja AI 2025 Professio
Master tester AI toolbox - Kari Kakkonen at Testaus ja AI 2025 ProfessioMaster tester AI toolbox - Kari Kakkonen at Testaus ja AI 2025 Professio
Master tester AI toolbox - Kari Kakkonen at Testaus ja AI 2025 Professio
Kari Kakkonen
 
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk TechniciansOffshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
john823664
 
Contributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptxContributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptx
Patrick Lumumba
 
Splunk Leadership Forum Wien - 20.05.2025
Splunk Leadership Forum Wien - 20.05.2025Splunk Leadership Forum Wien - 20.05.2025
Splunk Leadership Forum Wien - 20.05.2025
Splunk
 
Measuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI SuccessMeasuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI Success
Nikki Chapple
 
Introducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRCIntroducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRC
Adtran
 
"AI in the browser: predicting user actions in real time with TensorflowJS", ...
"AI in the browser: predicting user actions in real time with TensorflowJS", ..."AI in the browser: predicting user actions in real time with TensorflowJS", ...
"AI in the browser: predicting user actions in real time with TensorflowJS", ...
Fwdays
 
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...
pranavbodhak
 
Security Operations and the Defense Analyst - Splunk Certificate
Security Operations and the Defense Analyst - Splunk CertificateSecurity Operations and the Defense Analyst - Splunk Certificate
Security Operations and the Defense Analyst - Splunk Certificate
VICTOR MAESTRE RAMIREZ
 
Break Down of Service Mesh Concepts and Implementation in AWS EKS.pptx
Break Down of Service Mesh Concepts and Implementation in AWS EKS.pptxBreak Down of Service Mesh Concepts and Implementation in AWS EKS.pptx
Break Down of Service Mesh Concepts and Implementation in AWS EKS.pptx
Mohammad Jomaa
 
SAP Sapphire 2025 ERP1612 Enhancing User Experience with SAP Fiori and AI
SAP Sapphire 2025 ERP1612 Enhancing User Experience with SAP Fiori and AISAP Sapphire 2025 ERP1612 Enhancing User Experience with SAP Fiori and AI
SAP Sapphire 2025 ERP1612 Enhancing User Experience with SAP Fiori and AI
Peter Spielvogel
 
AI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AI
AI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AIAI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AI
AI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AI
Buhake Sindi
 
cloudgenesis cloud workshop , gdg on campus mita
cloudgenesis cloud workshop , gdg on campus mitacloudgenesis cloud workshop , gdg on campus mita
cloudgenesis cloud workshop , gdg on campus mita
siyaldhande02
 
Introducing Ensemble Cloudlet vRouter
Introducing Ensemble  Cloudlet vRouterIntroducing Ensemble  Cloudlet vRouter
Introducing Ensemble Cloudlet vRouter
Adtran
 
Marko.js - Unsung Hero of Scalable Web Frameworks (DevDays 2025)
Marko.js - Unsung Hero of Scalable Web Frameworks (DevDays 2025)Marko.js - Unsung Hero of Scalable Web Frameworks (DevDays 2025)
Marko.js - Unsung Hero of Scalable Web Frameworks (DevDays 2025)
Eugene Fidelin
 

Factory method pattern (Virtual Constructor)

  • 1. Factory Method Pattern Virtual Constructor Sameer Singh Rathoud
  • 2. About presentation This presentation provide information to understand factory method pattern, it’s various implementation and Applicability. I have tried my best to explain the concept in very simple language. The programming language used for implementation is c#. But any one from different programming background can easily understand the implementation.
  • 3. Definition The factory method pattern is a design pattern that define an interface for creating an object from one among a set of classes based on some logic. Factory method pattern is a creational design pattern. Factory method pattern is also known as virtual constructor pattern. Factory method pattern is the most widely used pattern in the software engineering world
  • 4. Motivation and Intent At times, application only knows about the super class (may be abstract class), but doesn’t know which sub class (concrete implementation) to be instantiated at compile time. Choice of sub class may be based on factors like: • Application configuration. • Expansion of requirements or enhancements. • The state of the application running. • Creates objects without exposing the instantiation logic to the client. • Refers to the newly created object through a common interface
  • 5. Structure Client uses Product Client Ask for a new Product Factory << interface >> Product Inheritance Concrete ProductA Concrete ProductB +CreateProduct(): Product
  • 6. Implementation (C#) Product product = new Product() Product productA = new ProductA(); Product productB = new ProductB(); When we are using “new” keyword in C#, It allocates the memory and creates a object of specified type. This will be ok if we are having only one type of product and a concrete class named “Product”. But if we are having more than one product type, we can create our “Product” as interface and provide various implementation to it. Let the classes providing implementation to our “Product” interface are “ProductA” and “ProductB”. But now for Instantiating “Product” we need to call the constructor of “Product” implementation. But here Product type specified is fixed (hard-coded). Let’s try for some generic implementation for this scenario.
  • 7. Implementation (C#) public Product CreateProduct(string productType) { Product product = null; if (productType.Equals("ProductA")) { product = new ProductA(); } else if (productType.Equals("ProductB")) { product = new ProductB(); } return product; } Client: Product productA = CreateProduct(“ProductA”); Product productB = CreateProduct(“ProductB”); Here function “CreateProduct” provide us a generic implementation of our scenario. “CreateProduct” function takes argument as “string productType” and returns a object of “ProductA” or “ProductB” based on the condition and now we can call this function with particular type of product and we will get the object. Although the code shown is far from perfection like: • Argument “string productType” can be replaced by an “enum”. • “if else” condition can be replaced by “switch case” statements … etc. But we can call our function “CreateProduct” as a factory. Let’s try to explore a better factory for our product.
  • 8. Implementation (C#) class ProductFactory { public Product CreateProduct(string productType) { Product product = null; if (productType.Equals("ProductA")) { product = new ProductA(); } else if (productType.Equals("ProductB")){ product = new ProductB(); } return product; } } Client: ProductFactory factory = new ProductFactory(); factory.CreateProduct(“ProductA”); factory.CreateProduct(“ProductB”); Instead of function “CreateProduct” we can have a class “ProductFactory” which will help us in creating product and provide a better control (class can have helper function for product like packaging etc.) on creation of product.
  • 9. Implementation (C#) enum ProductType { ProductA, ProductB, }; Modified our “ProductFactory” class by adding a “enum ProductType” and added “switch” statement instead of “If-else”. Now our “ProductFactory” is good to go. If user is adding a new “ProductC” in its product range, he a has to define a new implementation to Product interface (class “ProductC”), Need to make changes for “ProductC” in enum “ProductType” and need to add a switch case in our “ProductFactory.CreateProduct”. class ProductFactory { public Product CreateProduct(ProductType productType) { Product product = null; switch(productType) { case ProductType.ProductA: product = new ProductA(); break; case ProductType.ProductB: product = new ProductB(); break; default: product = null; break; Client: } ProductFactory factory = new ProductFactory(); return product; factory.CreateProduct(ProductType.ProductA); } factory.CreateProduct(ProductType.ProductB); }
  • 10. Options for adding new class without change in factory (C#) If user is adding a new product in his product range he has to modify his “ProductFactory”. To solve this problem we need a mechanism where “ProductFactory” is always aware of supported Product types. There can be two possible ways to achieve this solution: • Using reflection (C#/Java). • Without reflection (C++/C#/Java)
  • 11. Factory using reflection (C#) public enum ProductType : int { ProductA = 1, ProductB, }; [AttributeUsage(AttributeTargets.Class)] public class ProductAttribute : Attribute { private ProductType mProductType; public ProductAttribute(ProductType vProductType) { mProductType = vProductType; } public ProductType ProductSupported { get { return mProductType; } set { mProductType = value; } } }
  • 12. Factory using reflection continue …. [AttributeUsage(AttributeTargets.Interface)] public class ImplAttr : Attribute { private Type[] mImplementorList; public ImplAttr(Type[] Implementors) { mImplementorList = Implementors; } public Type[] ImplementorList { get { return mImplementorList; } set { mImplementorList = value; } } }
  • 13. Factory using reflection continue …. [ImplAttr(new Type[] { typeof(ProductA), typeof(ProductB)})] interface Product { void Print(); } [ProductAttribute(ProductType.ProductA)] class ProductA : Product { public void Print() { Console.WriteLine("I am ProductA"); } } [ProductAttribute(ProductType.ProductB)] class ProductB : Product { public void Print() { Console.WriteLine("I am ProductB"); } }
  • 14. Factory using reflection continue …. class ProductFactory { public Product CreateProduct(ProductType vProductType) { Product product = null; object Obj; Type[] IntrfaceImpl; Attribute Attr; ProductType productType; ProductAttribute productAttr; int ImplementorCount; Attr = Attribute.GetCustomAttribute(typeof(Product), typeof(ImplAttr)); IntrfaceImpl = ((ImplAttr)Attr).ImplementorList; ImplementorCount = IntrfaceImpl.GetLength(0); for (int i = 0; i < ImplementorCount; i++) { Attr = Attribute.GetCustomAttribute(IntrfaceImpl[i], typeof(ProductAttribute)); productAttr = (ProductAttribute)Attr;
  • 15. Factory using reflection continue …. productType = productAttr.ProductSupported; if ((int)productType == (int)vProductType) { Obj = Activator.CreateInstance(IntrfaceImpl[i]); product = (Product)Obj; break; } } return product; } }
  • 16. Factory using reflection continue …. class Client { static void Main(string[] args) { ProductFactory factory = new ProductFactory(); Product product = factory.CreateProduct(ProductType.ProductA); product.Print(); } } In the above mentioned code, we are having a factory which will remain unchanged even when user is adding in product classes (new implementation of Product Interface) in his product range. In the above implementation we have used reflection to achieve our objective.
  • 17. Factory without reflection class ProductFactory { private static Dictionary<string, Product> registeredProducts = new Dictionary<string,Product>(); private static ProductFactory factoryInstance = new ProductFactory(); private ProductFactory() { } public static ProductFactory Instance { get { return factoryInstance; } } public void registerProduct(String productID, Product p) { registeredProducts.Add(productID, p); }
  • 18. Factory without reflection continue …. public Product createProduct(String productID) { Product product = null; if (registeredProducts.ContainsKey(productID)) { product = (Product)registeredProducts[productID]; } return product; } }
  • 19. Factory without reflection continue …. interface Product { void Print(); } class ProductA: Product { public static void RegisterID(string id) { ProductFactory.Instance.registerProduct(id, new ProductA()); } public void Print() { System.Console.WriteLine("I am ProductA"); } } class ProductB : Product { public static void RegisterID(string id) { ProductFactory.Instance.registerProduct(id, new ProductB()); } public void Print() { System.Console.WriteLine("I am ProductB"); } }
  • 20. Factory without reflection continue …. class Client { static void Main(string[] args) { ProductFactory factory = ProductFactory.Instance; ProductA.RegisterID("ProductA"); Product productA = factory.createProduct("ProductA"); ((ProductA)productA).Print(); ProductB.RegisterID("ProductB"); Product productB = factory.createProduct("ProductB"); ((ProductB)productB).Print(); } } In the above mentioned code, we are having a factory which will remain unchanged even when user is adding in product classes (new implementation of Product Interface) in his product range. The above implementation is achieved without reflection. In the above implementation the “ProductFactory” class is created as singleton.