C# Implementing Abstract factory pattern

Ive ABSTRACT FACTORY pattern in one of my projects: http://www.dofactory.com/Patterns/PatternAbstract.aspx


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.


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:

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

this is readonly. So you cannot assign to it.

Need Your Help

Generating Interfaces from entity framework database first auto-generated code

c# entity-framework separation-of-concerns

I am using MVC3, C# 4.0 and Entity Framework in Visual Studio 2010. I am generating my edmx and Designed.cs files from a database. I am then generating interfaces from the entities in the Designer.cs

Getting a Jetty exception when I reloading my GWT development web server

java gwt jetty

I'm getting this exception when restarting my GWT server. I can't find any information on this exception that pertains to a server reload. The exception doesn't seem to cause any problems but it's