SlideShare a Scribd company logo
1 of 21
Download to read offline
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

Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternMudasir Qazi
 
Factory design pattern
Factory design patternFactory design pattern
Factory design patternFarhad Safarov
 
Creational pattern
Creational patternCreational pattern
Creational patternHimanshu
 
Design Patterns - Factory Method & Abstract Factory
Design Patterns - Factory Method & Abstract FactoryDesign Patterns - Factory Method & Abstract Factory
Design Patterns - Factory Method & Abstract FactoryGuillermo Daniel Salazar
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)paramisoft
 
Factory Pattern
Factory PatternFactory Pattern
Factory PatternDeepti C
 
Creational abstract factory_design_pattern
Creational abstract factory_design_patternCreational abstract factory_design_pattern
Creational abstract factory_design_patternbhaskara k
 
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
 
Abstract Factory Pattern
Abstract Factory PatternAbstract Factory Pattern
Abstract Factory Patternguestcb0002
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objectsSandeep Chawla
 
Module 10 : creating and destroying objects
Module 10 : creating and destroying objectsModule 10 : creating and destroying objects
Module 10 : creating and destroying objectsPrem Kumar Badri
 
Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfacesİbrahim Kürce
 

What's hot (18)

Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory Pattern
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
 
Factory design pattern
Factory design patternFactory design pattern
Factory design pattern
 
Creational pattern
Creational patternCreational pattern
Creational pattern
 
Design Patterns - Factory Method & Abstract Factory
Design Patterns - Factory Method & Abstract FactoryDesign Patterns - Factory Method & Abstract Factory
Design Patterns - Factory Method & Abstract Factory
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
 
Factory Pattern
Factory PatternFactory Pattern
Factory Pattern
 
Composite design pattern
Composite design patternComposite design pattern
Composite design pattern
 
Creational abstract factory_design_pattern
Creational abstract factory_design_patternCreational abstract factory_design_pattern
Creational abstract factory_design_pattern
 
Factory method pattern
Factory method patternFactory method pattern
Factory method pattern
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Write readable tests
Write readable testsWrite readable tests
Write readable tests
 
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)
 
Abstract Factory Pattern
Abstract Factory PatternAbstract Factory Pattern
Abstract Factory Pattern
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
JAX 08 - Agile RCP
JAX 08 - Agile RCPJAX 08 - Agile RCP
JAX 08 - Agile RCP
 
Module 10 : creating and destroying objects
Module 10 : creating and destroying objectsModule 10 : creating and destroying objects
Module 10 : creating and destroying objects
 
Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfaces
 

Similar to Factory method pattern (Virtual Constructor)

27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examplesQuang Suma
 
Unit 2-Design Patterns.ppt
Unit 2-Design Patterns.pptUnit 2-Design Patterns.ppt
Unit 2-Design Patterns.pptMsRAMYACSE
 
Software System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptxSoftware System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptxssuser9a23691
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2Naga Muruga
 
Padroes Projeto
Padroes ProjetoPadroes Projeto
Padroes Projetolcbj
 
Diving into VS 2015 Day5
Diving into VS 2015 Day5Diving into VS 2015 Day5
Diving into VS 2015 Day5Akhil Mittal
 
Creating web api and consuming- part 1
Creating web api and consuming- part 1Creating web api and consuming- part 1
Creating web api and consuming- part 1Dipendra Shekhawat
 
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.pdfssusera587d2
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1Shahzad
 
Android architecture
Android architecture Android architecture
Android architecture Trong-An Bui
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 
Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andevMike Nakhimovich
 

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

Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Unit 2-Design Patterns.ppt
Unit 2-Design Patterns.pptUnit 2-Design Patterns.ppt
Unit 2-Design Patterns.ppt
 
Software System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptxSoftware System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptx
 
Factory pattern in Java
Factory pattern in JavaFactory pattern in Java
Factory pattern in Java
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
 
Padroes Projeto
Padroes ProjetoPadroes Projeto
Padroes Projeto
 
Abstract factory
Abstract factoryAbstract factory
Abstract factory
 
Diving into VS 2015 Day5
Diving into VS 2015 Day5Diving into VS 2015 Day5
Diving into VS 2015 Day5
 
Creating web api and consuming- part 1
Creating web api and consuming- part 1Creating web api and consuming- part 1
Creating web api and consuming- part 1
 
S313937 cdi dochez
S313937 cdi dochezS313937 cdi dochez
S313937 cdi dochez
 
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
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1
 
Android architecture
Android architecture Android architecture
Android architecture
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andev
 

More from Sameer Rathoud

Observer design pattern
Observer design patternObserver design pattern
Observer design patternSameer 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
 
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
 

More from Sameer Rathoud (7)

Platformonomics
PlatformonomicsPlatformonomics
Platformonomics
 
AreWePreparedForIoT
AreWePreparedForIoTAreWePreparedForIoT
AreWePreparedForIoT
 
Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
 
Decorator design pattern (A Gift Wrapper)
Decorator design pattern (A Gift Wrapper)Decorator design pattern (A Gift Wrapper)
Decorator design pattern (A Gift Wrapper)
 
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())
 
Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)
 
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)
 

Recently uploaded

Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 

Recently uploaded (20)

Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 

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.