您好,感谢您的帮助。
使用 .Net 3.5 C#;
假设我有大约 10 个方法都遵循相同的模式
以3为例:
public Customer CreateCustomer(Customer c) { .. }
public Car CreateCar(Car c) { .. }
public Planet CreatePlanet(Planet p) { ..}
每个方法的内部逻辑具有完全相同的模式。
即:
public Customer CreateCustomer(Customer c)
{
Log.BeginRequest(c, ActionType.Create);
Validate(customer);
WebService.Send(Convert(c));
Log.EndRequest(c, ActionType.Create);
}
public Car CreateCar(Car c)
{
Log.BeginRequest(c, ActionType.Create);
Validate(c);
WebService.Send(Convert(c));
Log.EndRequest(c, ActionType.Create);
}
CreatePlanet 和其他 7 个方法也是如此。
这些方法是否可以重写,它们都遵循相同的模式,我觉得我缺少了一些东西......是否可以导出另一个抽象级别?
问题:应该如何重写以利用适当的架构模式?
谢谢, 史蒂文
最佳答案
这似乎是一个符合模板模式的案例。您可以让所有实体实现相同的接口(interface)/基础,并针对该接口(interface)执行操作。
我假设唯一必须知道实际类型的部分是 Validate()
。可以通过两种方式解决:
- 让接口(interface)/基础声明验证,然后在每个具体实体中实现它。
- 定义具体实体类型与实际验证策略之间的策略映射。
使用基类抽象验证的示例 -
实体的基础,它具有用于创建的内部服务和用于验证的抽象定义:
public abstract class EntityBase
{
protected abstract void Validate();
protected void Create(EntityBase c)
{
Log.BeginRequest(c, ActionType.Create);
c.Validate();
WebService.Send(Convert(c));
Log.EndRequest(c, ActionType.Create);
}
}
具有验证功能的具体实现者:
public class Customer : EntityBase
{
private int year;
public Customer(int year)
{
this.year = year;
}
public void CreateCustomer(Customer c)
{
Create(c);
}
protected override void Validate()
{
if (year < 1900)
{
throw new Exception("Too old");
}
}
}
我在原始代码中没有看到 Create
返回什么,所以我将其更改为 void 以使示例清晰
关于c# - 帮助 c# 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1813032/