enum QuestionType {
case MultipleChoice
case Range
case TrueFalse
case Text
}
protocol Question {
func printQuestion()
}
class TextQuestion: Question {
fileprivate init() {
}
func printQuestion() {
print("this is a text question")
}
}
class TrueFalseQuestion: Question {
fileprivate init() {
}
func printQuestion() {
print("this is a TrueFalse question")
}
}
class RangeQuestion: Question {
fileprivate init() {
}
func printQuestion() {
print("this is a Range question")
}
}
class MultipleChoiceQuestion: Question {
fileprivate init() {
}
func printQuestion() {
print("this is a MultipleChoice question")
}
}
// here i have created fileprivate init so that only way to initialize MultipleChoiceQuestion, RangeQuestion, TextQuestion and TrueFalseQuestion is by QuestionFactory. (as QuestionFactory will be in same file).
class QuestionFactory {
class func CreateQuestion(type: QuestionType) -> Question{
switch type {
case .MultipleChoice:
return MultipleChoiceQuestion()
case .Range:
return RangeQuestion()
case .Text:
return TextQuestion()
case .TrueFalse:
return TrueFalseQuestion()
}
}
}
==========
somewhere in other file....
let question: Question = QuestionFactory.CreateQuestion(type: .MultipleChoice) // instead of multiple choice, it should be selected dynamically by user and based on user choice appropriate object should be created.
mercredi 15 janvier 2020
Is below implementation of factory design pattern correct?
Inscription à :
Publier les commentaires (Atom)
Aucun commentaire:
Enregistrer un commentaire