Factory Pattern to build many derived classes

前端 未结 3 357
北海茫月
北海茫月 2021-02-03 12:14

I have a factory object ChallengeManager to generate instances of a Challenge object for a game I\'m building. There are many challenges. The constru

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-03 12:57

    Not necessarily the answer you are looking for but... You can use following implementation, if you can move away from static method per class.

    using System;
    
    public class Test
    {
        public static void Main()
        {
            var c1 = ChallengeManager.CreateChallenge();
            var c2 = ChallengeManager.CreateChallenge();
            //var c = ChallengeManager.CreateChallenge(); // This statement won't compile
        }
    }
    
    public class ChallengeManager
    {
        public static Challenage CreateChallenge()
        {
            // identify which challenge to instantiate. e.g. Challenage1
            var c = CreateChallenge();
            return c;
        }
    
        private static Challenage CreateChallenge() where T: Challenage, new()
        {
            return new T();
        }
    }
    
    public abstract class Challenage{}
    public class Challenage1: Challenage{}
    public class Challenage2: Challenage{}
    

提交回复
热议问题