Factory Design Pattern
Factory Design Pattern
Pattern
Marya Amouri
Introduction
Every codebase can be
improved
Product Creator
FactoryMethod() return concrete Product
Operation()
Problem
Problem
When adding Sea Track:
Most of your code is coupled to the
Truck class.
Adding Ships into the app would require
making changes to the entire codebase.
Structure IProduct = CreateProduct()
IProduct
ICreator
+CreateProduct()
+DoStuff()
ProductA ProductB
IDialog
IButton
+Render()
+Render()
+CreateButton()
+OnClick()
Windows Web
Button Button
WindowsDialog WebDialog
+Render() +Render()
+OnClick() +OnClick() +CreateProduct() +CreateProduct()
Art
Deco
Victorian
Modern
Problem
Furniture
Store Class-
Diagram
ICoffee
IChair
Table
Modern Victorian
Modern Victorian ArtCoffee
ArtChair Coffee Coffee
Chair Chair Table
Table Table
ISofa
Modern Victorian
ArtSofa
Sofa Sofa
Furniture Store
Chair Sofa Coffee Table
Art
Deco
Victorian
Modern
Furniture Store
Chair Sofa Coffee Table
Art
Deco
Victorian
Modern
solution
IFactory
-------------------------------------
+CreateChair(): IChair
+CreateCoffeTable():ICoffeeTablr
+CreateSofa():ISofa
// Abstract Product B
interface IProductB { string GetName( ); }
Code
// Concrete Product A1
class ProductA1 : IProductA
{
public string GetName() { return "Product A1"; }
}
// Concrete Product A2 class ProductA2 : IProductA {
public string GetName() { return "Product A2"; }
}
Code
// Concrete Product B1
class ProductB1 : IProductB
{ public string GetName() { return "Product B1"; } }
// Concrete Product B2
class ProductB2 : IProductB
{ public string GetName() { return "Product B2"; } }
Code
// Abstract Creator
interface ICreator {
IProductA CreateProductA();
IProductB CreateProductB(); }
// Concrete Creator 1
class Creator1 : ICreator {
public IProductA CreateProductA() { return new ProductA1(); }
public IProductB CreateProductB() { return new ProductB1(); } }
Code
// Concrete Creator 2