vendredi 30 septembre 2016

Which design pattern to use in the scenario where object type is unknown and I have to check the object type?

I have the scenario below where a service layer call returns objects of type DistributionPrompt, MentoringPathPrompt, BossLetterPrompt, and CertificatePrompt in an object[]. I've managed to localize this checking to a single function but I feel as if this is not an elegant solution but I'm not quite sure which design pattern I can apply that would be ideal for this scenario.

Could someone let me know the design pattern name that I can use for this situation? I don't need the final solution as I'd like to work it out myself but just the name would suffice as I don't know design patterns as well as I should. Also, please explain how this design pattern would be more useful compared to the existing function if another Prompt type were introduced?

private static PromptVisibility ParsePrompts(IEnumerable prompts)
        {
            var promptVisibility = new PromptVisibility();

            foreach (var t in prompts)
            {

                if (t is DistributionPrompt)
                {
                    promptVisibility.IsDistributionPromptVisible = true;
                    promptVisibility.DistributionNumber = ((DistributionPrompt)t).DistributionNumber;
                }

                if (t is MentoringPathPrompt)
                {
                    promptVisibility.IsMentoringPathPromptVisible = true;
                }

                if (t is BossLetterPrompt)
                {
                    promptVisibility.IsBossLetterPromptVisible = true;
                    promptVisibility.EmployerAddress = ((BossLetterPrompt)t).ExistingEmployerAddress;
                }

                if (t is CertificatePrompt)
                {
                    promptVisibility.IsCertificationPromptVisible = true;
                }
            }

            return promptVisibility;
        }

Aucun commentaire:

Enregistrer un commentaire