I have 3 classes in Data Access project, and all 3 classes have many data access methods ( GetSomeList
, InsertSomeData
, UpdateSomeData
…). All 3 classes have several methods that are same. I don't want to write same methods 3 times. What is best approach here?
One possible solution would be to define one common class that will be inherited. Is this good approach?
Example:
public abstract class CommonDataLayer
{
public int CommonMethod()
{
Random random = new Random();
int randomNumber = random.Next(0, 100);
return randomNumber;
}
}
public class FirstDataLayer : CommonDataLayer
{
public int FirstMethod()
{
return CommonMethod() + 1;
}
}
public class SecondDataLayer : CommonDataLayer
{
public int SecondMethod()
{
return CommonMethod() + 2;
}
}
public class ThirtDataLayer : CommonDataLayer
{
public int ThirtMethod()
{
return CommonMethod() +3;
}
}
为所有类创建一个超类,并为该超类创建通用方法实现。
A good approach is to:
One possible solution would be to define one common class that will be inherited. Is this good approach?
Yes
But in your code example, its not necessary to have FirstMethod
, SecondMethod
and ThirdMethod
. You can invoke the CommonMethod
directly from the derived class. You can override the CommonMethod if the derived method requires specific functionality.
public class FirstDataLayer : CommonDataLayer
{
// This class uses CommonMethod from the Base Class
}
public class SecondDataLayer : CommonDataLayer
{
@Override
public int CommonMethod(){
// EDIT code
// Class specific implementation
return base.CommonMethod() +1;
}
}
public class ThirdDataLayer : CommonDataLayer
{
public int ThirdMethod(){
// Class specific implementation
return base.CommonMethod() +2;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.