c# - 帮助 c# 模式

标签 c# .net oop design-patterns architecture

您好,感谢您的帮助。

使用 .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()。可以通过两种方式解决:

  1. 让接口(interface)/基础声明验证,然后在每个具体实体中实现它。
  2. 定义具体实体类型与实际验证策略之间的策略映射。

使用基类抽象验证的示例 -

实体的基础,它具有用于创建的内部服务和用于验证的抽象定义:

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/

相关文章:

c# - 如何以编程方式在 IIS 7 中获取站点列表和虚拟目录?

C#引用;隐藏成员

java - java中的继承 : object state and behavior

c# - 什么是 'api_key' 以及如何正确使用它

c# - 为什么使用匿名类型而不是创建类

c# - 机器人框架 : Loop through Prompts

.net - 将 VC 6.0 应用程序移植到 VS 2003 VC++ 应用程序

c# - 如何让 Visual Studio 在不显式编译的情况下对我的代码进行错误检查(显示波浪线)?

c# - 查找未转义字符时使用 Regex Replace

java - GameManager 类型类的单一职责原则