最近又重新理解了物件導向設計,我覺得它想要解決的核心問題,除了DRY(Don't repeat yourself),還有為了避免程式碼太混亂,難以共同維護及擴充等等,透過模組化,來達成管理和簡化
根據官網介紹有4種概念,那比較通俗的例子如下:
就像你在使用別人已經開發好的模組,你不需要知道它內部是怎麼實作的,只要會用它提供的功能就好
開發人員只需要專注在想要達到的目的就好
駕駛汽車的過程,不會讓你動到裡面的汽車零件造成破壞,而是提供外部的按鈕,依你想要的方式行駛
當汽車去做美容保養,可能會拆裝部分皮件清潔,但不會去動你的引擎
決定什樣的資料或功能要揭露
像富二代繼承父母的公司,基本架構和功能都不用重寫,直接拿來用,還可以依需求做擴充或修改。
在既有的基礎上,去增加功能
我今天定義付款這個類別,然後有付錢功能,然後我可以有多種付款方式去繼承,他們都有付錢的功能,但可以用不一樣的方式付
那之前提到定義介面,去替換不同服務,也是多型的一種
// Polymorphism at work #1: a Rectangle, Triangle and Circle
// can all be used wherever a Shape is expected. No cast is
// required because an implicit conversion exists from a derived
// class to its base class.
var shapes = new List<Shape>
{
new Rectangle(),
new Triangle(),
new Circle()
};
// Polymorphism at work #2: the virtual method Draw is
// invoked on each of the derived classes, not the base class.
foreach (var shape in shapes)
{
shape.Draw();
}
/* Output:
Drawing a rectangle
Performing base class drawing tasks
Drawing a triangle
Performing base class drawing tasks
Drawing a circle
Performing base class drawing tasks
*/
今天不開發,倒車回來,釐清觀念