ste*_*ell 1 c# architecture oop design-patterns
您好,感谢您的帮助.
使用.Net 3.5 C#;
假设我有大约10种方法都遵循相同的模式
以3为例:
public Customer CreateCustomer(Customer c) { .. }
public Car CreateCar(Car c) { .. }
public Planet CreatePlanet(Planet p) { ..}
Run Code Online (Sandbox Code Playgroud)
每种方法的内部逻辑具有完全相同的模式.
IE:
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);
}
Run Code Online (Sandbox Code Playgroud)
CreatePlanet和其他7种方法也是如此.
这些方法可以重写,它们都遵循相同的模式,我觉得我错过了一些东西......是否有另一层抽象可以衍生出来?
问题:如何重写以利用适当的架构模式?
谢谢,史蒂文
这似乎适合模板模式的情况.您可以使所有实体实现相同的接口/基础并对接口执行操作.
我假设唯一必须知道实际类型的部分是Validate().它可以通过两种方式解决:
使用基类抽象验证的示例 -
实体的基础,它具有用于创建的内部服务和用于验证的抽象定义:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
具有验证功能的具体实现者:
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我没有在原始代码中看到什么Create返回,所以我将其更改为void以使示例清楚
| 归档时间: |
|
| 查看次数: |
281 次 |
| 最近记录: |