使用“key”创建子项的实例

时间:2014-12-16 10:52:33

标签: c#

我有一个基类"游戏"和每个游戏的儿童约会,其方法为每个游戏制定特定的动作,但有些功能是通用的。我将Games类抽象化,每个子类都实现抽象方法或使用base clase泛型方法。每个孩子都有相同的功能,但在某些情况下实现的不同。 (我认为这是正确的方式)

using System.IO;
using System;

namespace AppGames {

    public abstract class Games 
    { 
        protected string name;

        public Games(string name)  // constructor
        { 
            this.name = name;
        }

        public abstract void Show();  // abstract show method

    }

    public class GameWOW: Games
    { 
        public GameWOW(string name) : base(name) {}  // constructor

        public override void Show()  //override the abstract show method
        {
            System.Console.WriteLine("Name W : " + name);
        }
    }

    public class GameGW2: Games
    { 
        public GameGW2(string name) : base(name) {}  // constructor

        public override void Show()  //override the abstract show method
        {
            System.Console.WriteLine("Name G : " + name);
        }
    }

}

我的问题是在正确的情况下创建每个孩子的实例,因为当一个webservice传递一个" key"时,我需要调用子函数。 (不是班级名称)

我正在使用开关,但不知道如何创建一个"泛型"正确的孩子的实例,并稍后调用函数。

更新澄清:

我需要调用一次,但不要复制实例,如果我多次调用GameWoW,我只使用一个副本:

 switch (game) {

            case "wow":
                className = "GameWoW";
            break;

            case "gw2":
                className = "GameGW2";
            break;

            default:
                className = null;
            break;

        }

        if (className != null) {
          // create instance of the className
          // if exists, use it, if not, create new
        }

感谢。

2 个答案:

答案 0 :(得分:2)

使用Lazy<Games>

这是一个很好的干净方法
public class GameCenter
{
    private Dictionary<string, Lazy<Games>> games = new Dictionary<string, Lazy<Games>>()
    {
        { "GameWOW", new Lazy<Games>(() => new GameWOW("wow")) },
        { "GameGW2", new Lazy<Games>(() => new GameGW2("gw2")) },
    };

    public Games GetGameFor(string gameType)
    {
        return games.ContainsKey(gameType) ? games[gameType].Value : null;
    }
}

答案 1 :(得分:1)

喜欢这个吗?

编辑:每条评论更新

public class GameCenter {
    public Games GetGameFor(string gameType){
        if (!games.ContainsKey(gameType)){
            switch (gameType) {
                case "GameWOW": games.Add("GameWOW", new GameWOW("wow")); break;
                case "GameGW2": games.Add("GameGW2", new GameGW2("gw2")); break;
                default: return null;
            }
        }
        return games[gameType];
    }
    private Dictionary<string, Games> games = new Dictionary<string, Games>();
}

像这样使用:

var gc = new GameCenter();           //create a game center
var game = gc.GetGameFor("GameWOW"); //get a game from the center
game.Show();                         //use the game
//note that you need to keep the gc around, if you make a new GameCenter
//you will get a new game intance when you call GetGameFor