0

我正在对提供数据的 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
    }
}
4

2 回答 2

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;
        }
    }
    */
}
于 2013-01-17T06:55:06.817 回答
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);

    }

}
于 2013-01-17T07:21:50.010 回答