0
The question is actually derived from this link.如何重構此代碼以使其符合開放式關閉原則?
假設我有這樣一個問題:
書商店購買和出售兩種類型的書: (1)非技術{標題,作者,價格} ( 2)技術{標題,作者,價格,CD}
此外,客戶購買技術書籍時獲得CD。 CD對象被定義爲CD {標題,價格}。
非技術書的價格將只是書的價格。技術書的價格將是書和CD的價格的總和。
創建一個C#程序,以顯示以下信息:
Total number of book Bought & Price: XXX & XXX.XX
Total number of book Sold & Price: XXX & XXX.XX
Total Technical Book Sold & Price: XXX & XXX.XX
Total Non-technical Book sold & Price: XXX & XXX.XX
abstract class Publication
{
public virtual string Title { get; set; }
public virtual double Price { get; set; }
}
class CD : Publication
{
}
abstract class Book : Publication
{
public virtual string Author { get; set; }
}
class TechnicalBook : Book
{
public CD Cd { get; set; }
public override double Price
{
get
{
return (base.Price + Cd.Price);
}
}
}
class NonTechnicalbook : Book
{
}
class Shop
{
private IDictionary<string, Book> boughtDictionary;
private IDictionary<string, Book> soldDictionary;
public Shop()
{
boughtDictionary = new Dictionary<string, Book>();
soldDictionary = new Dictionary<string, Book>();
}
public virtual void Buy(Book item)
{
boughtDictionary.Add(item.Title, item);
}
public virtual void Sell(string title)
{
Book book = boughtDictionary[title];
boughtDictionary.Remove(book.Title);
soldDictionary.Add(book.Title, book);
}
public virtual int GetBoughtBookCount()
{
return boughtDictionary.Count;
}
public virtual double GetBoughtBookPrice()
{
double price = 0.0;
foreach (string title in boughtDictionary.Keys)
{
price = price + boughtDictionary[title].Price;
}
}
public virtual int GetSoldBookCount()
{
return boughtDictionary.Count;
}
public virtual double GetSoldBookPrice()
{
double price = 0.0;
foreach (string title in soldDictionary.Keys)
{
price = price + soldDictionary[title].Price;
}
}
public virtual double GetTotalBookCount()
{
return this.GetBoughtBookCount() + this.GetSoldBookCount();
}
public virtual double GetTotalBookPrice()
{
return this.GetBoughtBookPrice() + this.GetSoldBookPrice();
}
public virtual void Show()
{
Console.WriteLine("Total number of books Bought & Price: ", this.GetTotalBookCount() + " & " + this.GetTotalBookPrice());
Console.WriteLine("Total number of books Sold & Price: ", this.GetSoldBookCount() + " & " + this.GetSoldBookPrice());
}
}
如何顯示技術和非技術書籍的價格,同時保持開閉原則?
派生商店級沒有任何意義。
如果我如下代碼:
if(book is TechnicalBook) {
// ...
} else if(book is NonTechnicalBook) {
// ...
}
我不認爲它使OCP。
那該怎麼辦?