Kihagyás

Factory design pattern

Factory

One of the most used design pattern in languages like java or c#

Example

Here's a simple class, with some derivatives:

namespace Classes
{
    public class User
    {
        string name;
        public User(string name) 
        {
            this.name = name;
        }
    }

    class Guest : User
    {
        int timeAvailable;
        public Guest(string name, int timeAvailable):base(name)
        {
            this.timeAvailable = timeAvailable;
        }
    }

    class RegularUser : User
    {
        string homeDirectory;

        public RegularUser(string name, string homeDirectory):base(name)
        {
            this.homeDirectory = homeDirectory;
        }
    } 

    class SuperUser: User
    {
        OperatingSystem operatingSystem;

        public SuperUser(string name,OperatingSystem operatingSystem):base(name)
        {
            this.operatingSystem = operatingSystem;
        }
    }
}

... and we want to keep those derived classes hidden so everyone can only see the User class.

Now these derived classes has some default values (like the user tends to name the home folder after themself, and the superuser has the current system), so we can create a factory method to create them.

using Classes;

namespace Design_Patterns.Patterns
{   
    internal class UserFactory
    {
        User createRegularUser(string name)
        {
            return new RegularUser(name, name.ToLower().Trim());
        }

        User createSuperuser(string name)
        {
            return new SuperUser(name, new OperatingSystem(PlatformID.Other,Version.Parse("1.0")));
        }

        User createGuest(string name)
        {
            return new Guest(name, 1000);
        }
    }
}

This example avoids the usage of Reflection, but most cases of the real Factory methods needs reflection to create these classes at runtime. These ones exist at compile time.