如何扩展类
本文关键字:扩展 何扩展 | 更新日期: 2023-09-27 17:53:44
我正在对提供数据的API进行更改。有些搜索需要作者的数据,并采用IAuthor
对象。该API有一个IAuthor
接口和一个实现IAuthor
的具体类Author
。
我需要添加一个布尔属性,IsNovelist
,这将改变一些但不是所有搜索的语义。
我听说过开放/封闭原则,似乎改变IAuthor
和/或Author
类会违反这个原则。那么如何做出这个简单的改变呢?
更新:也许我把注意力集中在错误的课程上。我不想添加行为到
Author
类(它只是传递参数给API的一种方式)。因此,Decorated
作者不需要布尔标志,因为它将隐含为isNovelist == true
。
我需要改变GetBooks
方法的行为给定的作者谁被标记为小说家。所以更像这样的东西,但我的想法可能是不稳定的,因为现在我正在改变(不扩展)Books
类:
//Before
class Books
{
public Books[] GetBooks(IAuthor author){
// Call data access GetBooks...
}
}
//After
class Books
{
public Books[] GetBooks(IAuthor author){
// To maintain pre-existing behaviour
// call data access GetBooks with SQL param @isNovelist = false...
// (or don't pass anything because the SQL param defaults to false)
}
public Books[] GetBooksForNovelist(IAuthor author){
// To get new behaviour
// call data access GetBooks with SQL param @isNovelist = true
}
}
方案二:
class Program
{
private static void Main(string[] args)
{
IAuthor author = new Novelist();
author.Name = "Raj";
// i guess u have check if author is a novelist
// the simple way is by safe typecasting
Novelist novelist = author as Novelist;
if (novelist != null)
{
Console.WriteLine("Wohoo, i am a novelist");
}
else
{
Console.WriteLine("Damn,i cant write novel");
}
}
方案1:
public enum AuthourType
{
Novelist,
Other
}
public interface IAuthor
{
string Name { get; set; }
AuthourType Type { get; set; }
}
public class Novelist : IAuthor
{
public string Name { get; set; }
public AuthourType Type { get; set; }
// incase u dont want it to be set to other value
/*
public AuthourType Type
{
get { return type; }
set
{
if (value != AuthourType.Novelist)
{
throw new NotSupportedException("Type");
}
type = value;
}
}
*/
}
如何使用装饰器模式
interface IAuthor
{
void someMethod();
}
class Author:IAuthor{
public void someMethod(){
//Implementation here
}
}
//Class that will add the extra behavior.
class DecoratedAuthor : IAuthor
{
IAuthor author;
public bool isNovelist{get;set;}//Add the extra Behavior
public DecoratedAuthor(IAuthor auth)
{
this.author = auth;
}
public void someMethod(){
//Call the Author's version here
author.someMethod();
//check if he is a novelist
isNovelist = true;
}
}
public class program{
public static void Main(string[] args)
{
IAuthor auth = new Author();
DecoratedAuthor novAuth = new DecoratedAuthor(auth);
DecoratedAuthor.someMethod();
//see if he is a novelist
Console.WriteLine(novAuth.isNovelist);
}
}