简体   繁体   中英

C# Implementing Abstract factory pattern

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?

this is readonly. So you cannot assign to it.

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:

QuestaoBaseResposta qs = new QuestaoFactory().CreateQuestao();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM