factory pattern code example

Example 1: factory subfactory

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.User

    name = "John"
    lang = factory.SelfAttribute('country.lang')
    country = factory.SubFactory(CountryFactory)

class CompanyFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.Company

    name = "ACME, Inc."
    country = factory.SubFactory(CountryFactory)
    # use ".." to go a step back and access to CompanyFactory attrs
    owner = factory.SubFactory(UserFactory, country=factory.SelfAttribute('..country'))

Example 2: factory in testng

The @Factory annotation is useful when we want to run multiple test 
cases through a single test class. It is mainly used for the dynamic 
execution of test cases.

Let's say we have in 2 different classes, there are 2 different test cases.
If we want to run both in the same class. We use @Factory annotaions which
takes Object[] array. We put the test cases into it. it returns Object array 
value.

Example 3: simple factory pattern

enum FanType
{
    TableFan,
    CeilingFan,
    ExhaustFan
}

interface IFan
{
    void SwitchOn();
    void SwitchOff();
}

class TableFan : IFan {.... }

class CeilingFan : IFan {.... }

class ExhaustFan : IFan {..... }

interface IFanFactory
{
    IFan CreateFan(FanType type);
}

class FanFactory : IFanFactory
{
    public IFan CreateFan(FanType type)
    {
        switch (type)
        {
            case FanType.TableFan:
                return new TableFan();
            case FanType.CeilingFan:
                return new CeilingFan();
            case FanType.ExhaustFan:
                return new ExhaustFan();
            default:
                return new TableFan();
        }
    }
}

//The client code is as follows:

static void Main(string[] args)
{
        IFanFactory simpleFactory = new FanFactory();
        // Creation of a Fan using Simple Factory
        IFan fan = simpleFactory.CreateFan(FanType.TableFan);
        // Use created object
        fan.SwitchOn();

        Console.ReadLine();
 }