我創建了一個工廠類,以簡化不污染目標類的構造函數創建另一個類的對象(我認爲這就是工廠是)創建在C#一個簡單的工廠類
這是我在這一刻。
public class QFactory
{
public Quiz.Question q(string text, string buttonname)
{
Quiz.Question question = new Quiz.Question();
question.QuestionText = text;
question.QuestionImage = buttonname;
return question;
}
public Quiz.Answer a(string answerText, bool answerRight = false)
{
Quiz.Answer answer = new Quiz.Answer();
answer.text = answerText;
answer.correct = answerRight;
return answer;
}
}
爲了使用它來創建Quiz.Question和Quiz.Answer對象,我必須按以下方式使用它。
Quiz.Question q = (new QFactory()).q("What is a tomato?","But_01_Idle");
Quiz.Answer a = (new QFactory()).a("fruit",true);
Quiz.Answer b = (new QFactory()).a("vegetable");
Quiz.Answer c = (new QFactory()).a("animal");
q.Answers = new List<Quiz.Answer>{a,b,c}; // add a,b,c answer to the question
我該如何更改QFactory類,以便它的使用是這樣(singletons?)?
Quiz.Question q = QFactory.q("what is a Tomato?","But_01_Idle");
...
謝謝,我試圖讓這個類只是靜態的。 –
靜態類是一個只有靜態方法和字段的類,所以你可以(也應該)在靜態方法中標記靜態類。 –
謝謝,我希望我正確使用工廠。 –