gpt4 book ai didi

c# - 我有哪种设计模式

转载 作者:行者123 更新时间:2023-11-30 17:47:36 25 4
gpt4 key购买 nike

我有两个类,每个类都做同样的事情,但唯一的区别是,它们在代码的某些函数中使用不同的逻辑。假设:

class A
{
//has same fields, and method
void GetDataTable()
{
//logic here changes up to table of the database and for some fields.
}
}

class B
{
//has same fields, and method
void GetDataTable()
{
//logic here changes up to table of the database and for some fields.
}
}

在一天结束时,我会添加另一个相同的行为类和具有不同逻辑的 GetDataTable 方法。我必须申请什么样的设计模式或OO技术才能获得更高质量的代码。

最佳答案

您可能正在寻找 Strategy Pattern .

您使用每个“逻辑”类必须实现的方法定义一个接口(interface)。每个“逻辑”类都将实现此接口(interface)并在实现的方法中执行其逻辑。

interface IGetDataTable
{
void GetDataTable();
}

class A : IGetDataTable
{
public void GetDataTable() { /* Do logic here for class A */ }
}

class B : IGetDataTable
{
public void GetDataTable() { /* Do logic here for class B */ }
}

然后根据需要选择合适的类(实现 IGetDataTable)。

关于c# - 我有哪种设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24465886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com