我正在更改提供数据的API。某些搜索需要有关作者的数据并采用IAuthor
对象。 API有一个IAuthor
接口和一个实现名为IAuthor
的{{1}}的具体类。
我需要添加一个布尔属性Author
,它将改变某些但不是所有搜索的语义。
我听说过open/closed principle,似乎更改IsNovelist
和/或IAuthor
类会违反此规定。那怎么做这个简单的改变?
更新:
也许我专注于错误的课程。我不想将行为添加到Author
类(这只是将参数传递给API的一种方式)。所以Author
作者不需要布尔标志,因为暗示它是Decorated
。
我需要改变isNovelist == true
方法的行为,给予被标记为小说家的作者。所以更像这样的东西,但我的想法可能很糟糕,因为现在我正在改变(不扩展)GetBooks
类:
Books
答案 0 :(得分:1)
解决方案2:
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;
}
}
*/
}
答案 1 :(得分:1)
以下是使用装饰器模式的方法
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);
}
}