我有很好的静态方法感

时间:2010-10-14 16:50:40

标签: c# oop static

我有国家级,其中包含城市的集合。

在客户端我使用webmethod

[WebMethod]
public void AddCity(string countryCode,string name)
{
MyFacade.AddCity(countryCode,name);
}
在Facade我有方法

public void AddCity(string countryCode,string name)
{
Country.AddCity(countryCode,name); <-in this method is simple sql operation
}

和我的问题的核心:

public class Country
{
public static void AddCity(string countryCode, string cityName)
{
//insert into table cities new city
}
}

没关系?或者我必须创建objectCountry,并且有非静态方法AddCity?

另一个问题:

更好用:

City[] cities=  Country.GetAllCities(countryCode)

City[] cities=  new Country(countryCode).GetAllCities()

2 个答案:

答案 0 :(得分:1)

接受countryCodecityName作为参数适用于数据访问层,但我没有看到任何应该是静态的方法。

AddCity应该是DataConnection的非静态成员或其他成员,这样您就可以轻松地模拟它,替换数据库等,而无需更改调用接口。

答案 1 :(得分:1)

您是否希望能够使用模拟框架对代码进行单元测试?

以Ben的答案为基础,用界面替换Facade:

[WebMethod]
public void AddCity(string countryCode, string name)
{
    ICountryDataAccess dao = GetDAOFromDI(); // basically get a DI framework to manage this object instance.
    dao.AddCity(countryCode, name);
}

public interface ICountryDataAccess 
{
    void AddCity(string countryCode, string name);
    ICollection<City> GetAllCities(string countryCode);
    // OR !
    Country Retrieve(string countryCode);
    // using an ORM or something Country then as a list of cities
}

public Country 
{
    public virtual string CountryCode {get;set;} 
    public virtual ICollection<City> Cities {get; protected set;}
}
相关问题