This page provides practical implementation examples of the Factory Pattern across multiple programming languages. Each example demonstrates both Simple Factory and Factory Method patterns with real-world scenarios.
C# Implementation
Simple Factory
using System;
// Product Interface
public interface INotification
{
void Send(string message);
}
// Concrete Products
public class EmailNotification : INotification
{
public void Send(string message)
{
Console.WriteLine($"Sending Email: {message}");
}
}
public class SMSNotification : INotification
{
public void Send(string message)
{
Console.WriteLine($"Sending SMS: {message}");
}
}
public class PushNotification : INotification
{
public void Send(string message)
{
Console.WriteLine($"Sending Push Notification: {message}");
}
}
// Simple Factory
public class NotificationFactory
{
public static INotification CreateNotification(string type)
{
return type.ToLower() switch
{
"email" => new EmailNotification(),
"sms" => new SMSNotification(),
"push" => new PushNotification(),
_ => throw new ArgumentException($"Unknown notification type: {type}")
};
}
}
Node.js Implementation
// Product Classes
class EmailNotification {
send(message) {
console.log(`Sending Email: ${message}`);
}
}
class SMSNotification {
send(message) {
console.log(`Sending SMS: ${message}`);
}
}
// Simple Factory
class NotificationFactory {
static createNotification(type) {
switch(type.toLowerCase()) {
case 'email':
return new EmailNotification();
case 'sms':
return new SMSNotification();
default:
throw new Error(`Unknown type: ${type}`);
}
}
}
Python Implementation
from abc import ABC, abstractmethod
class Transport(ABC):
@abstractmethod
def deliver(self, destination: str) -> None:
pass
class Truck(Transport):
def deliver(self, destination: str) -> None:
print(f"Delivering by truck to {destination}")
class Ship(Transport):
def deliver(self, destination: str) -> None:
print(f"Delivering by ship to {destination}")
class TransportFactory:
@staticmethod
def create_transport(transport_type: str) -> Transport:
if transport_type == 'truck':
return Truck()
elif transport_type == 'ship':
return Ship()
else:
raise ValueError(f"Unknown type: {transport_type}")
Go Implementation
package main
import "fmt"
type Database interface {
Connect() string
}
type MySQL struct{}
func (m *MySQL) Connect() string {
return "Connected to MySQL"
}
type PostgreSQL struct{}
func (p *PostgreSQL) Connect() string {
return "Connected to PostgreSQL"
}
type DatabaseFactory struct{}
func (f *DatabaseFactory) CreateDatabase(dbType string) (Database, error) {
switch dbType {
case "mysql":
return &MySQL{}, nil
case "postgresql":
return &PostgreSQL{}, nil
default:
return nil, fmt.Errorf("unknown type: %s", dbType)
}
}
C++ Implementation
#include <iostream>
#include <memory>
#include <string>
class Shape {
public:
virtual ~Shape() = default;
virtual void draw() const = 0;
};
class Circle : public Shape {
public:
void draw() const override {
std::cout << "Drawing Circle" << std::endl;
}
};
class Rectangle : public Shape {
public:
void draw() const override {
std::cout << "Drawing Rectangle" << std::endl;
}
};
class ShapeFactory {
public:
static std::unique_ptr<Shape> createShape(const std::string& type) {
if (type == "circle") {
return std::make_unique<Circle>();
} else if (type == "rectangle") {
return std::make_unique<Rectangle>();
}
return nullptr;
}
};
Rust Implementation
trait Vehicle {
fn drive(&self);
}
struct Car;
impl Vehicle for Car {
fn drive(&self) {
println!("Driving a car");
}
}
struct Motorcycle;
impl Vehicle for Motorcycle {
fn drive(&self) {
println!("Riding a motorcycle");
}
}
struct VehicleFactory;
impl VehicleFactory {
fn create_vehicle(vehicle_type: &str) -> Result<Box<dyn Vehicle>, String> {
match vehicle_type {
"car" => Ok(Box::new(Car)),
"motorcycle" => Ok(Box::new(Motorcycle)),
_ => Err(format!("Unknown type: {}", vehicle_type)),
}
}
}