mardi 23 mai 2017

factory design pattern, parent = new child()

When I'm using the factory pattern, i am confused with how to make child classes from it when the child has extra properties/methods. The factory returns the parent type as it works out which child to make but when this happens i cant use what it returns like a child class.

public abstract class Factory 
{
        public abstract Person getPerson(string type);
}

public class PersonFactory : Factory
{
        public override Person getPerson(string type) {
               switch (type) {
                      case "admin": 
                             return new Admin();
                      case "customer": 
                             return new Customer();
                      default: 
                             return new Admin();
               }
        }
}


public abstract class Person
{
        public abstract string Type { get; }
        private int _id;

        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }
}

public class Admin : Person
{
        private string _securityRole;

        public Admin()
        {
            Id = 0;
        }

        public override string Type
        {
            get{
                return "admin";
            }
        }

        public string SecurityRole
        {
            get { return _securityRole; }
            set { _securityRole = value; }
        }
}

So my question is, when i create a PersonFactory object and decide to use that factory to create other derived classes. I noticed that getPerson() returns Person and not actually type Admin or Customer. How can i make the factory create the child classes so that they are actually child objects?

Factory pf = new PersonFactory();
Person admin = pf.getPerson("admin");
admin.Id = 1;            // is fine
admin.SecurityRole       // cannot access

Aucun commentaire:

Enregistrer un commentaire