Ive ABSTRACT FACTORY pattern in one of my projects:
http://www.dofactory.com/Patterns/PatternAbstract.aspx
Code:
public class QuestaoResposta : QuestaoBaseResposta, IQuestao,IQuestionario
{
public int IDQuestaoResposta { get; set; }
}
public class QuestaoFactory : QuestoesFactory
{
public override QuestaoBaseResposta CreateQuestao()
{
return new QuestaoResposta();
}
}
public abstract class QuestoesFactory
{
public abstract QuestaoBaseResposta CreateQuestao();
}
public class QuestaoBaseResposta : IQuestao, IMarcas, IQuestionario
{
// Constructor where i want to create a concrete instance
// of any class that inherits QuestaoBaseResposta using QuestoesFactory
// abstract class, and assign it to current instance of
// QuestaoBaseResposta class
public QuestaoBaseResposta(QuestoesFactory qf)
{
this = qf.CreateQuestao();
}
}
Problem is that i cant assing a value to current class using “THIS” keyword.
Example:
QuestaoBaseResposta qs = new QuestaoBaseResposta(new QuestaoFactory());
// Here i want the qs intance to be type of QuestaoResposta
// since im passing QuestaoFactory as argument,without cast anything.
qs.IDQuestaoResposta = 0;
What would you suggest to cast the QuestaoBaseResposta class to the inherit type (QuestaoResposta),without cast?
No you can’t cast without cast. The usefulness of a factory comes from the fact that xyou do not need to know the exact derived class of the returned object. This is different if you donÄt use a factory but instead calling a constructor where you know the exact type.
Why don’t you do it this way: