Bob大叔提出併發揚了S.O.L.I.D
五大原則,用來更好地進行面向對象編程,五大原則分別是:javascript
The Single Responsibility Principle(單一職責SRP)html
The Open/Closed Principle(開閉原則OCP)java
The Liskov Substitution Principle(里氏替換原則LSP)程序員
The Interface Segregation Principle(接口分離原則ISP)ajax
The Dependency Inversion Principle(依賴反轉原則DIP)編程
五大原則,我相信被你們說爛了,尤爲是C#的實現,可是相對於JavaScript
這種以原型爲base的動態類型語言來講還爲數很少,該系列將分5篇文章以JavaScript
編程語言爲基礎來展現五大原則的應用。 OK,開始咱們的第一篇:單一職責。segmentfault
英文原文:http://freshbrewedcode.com/derekgreer/2011/12/08/solid-javascript-single-responsibility-principle/設計模式
Robert C. Martin,世界級軟件開發大師,設計模式和敏捷開發先驅,敏捷聯盟首任主席,C++ Report 前主編,被後輩程序員尊稱爲「Bob大叔」。20世紀70年代初成爲職業程序員,後創辦Object Mentor公司並任總裁。Martin仍是一名多產的做家,至今已發表數百篇文章、論文和博客,除本書外,還著有《代碼整潔之道》、《敏捷軟件開發:原則、模式和實踐》、《UML:Java程序員指南》等。他最近創辦了cleancoders.com網站,專爲軟件開發人員提供教育視頻。併發
單一職責的描述以下:app
A class should have only one reason to change
類發生更改的緣由應該只有一個
一個類(JavaScript
下應該是一個對象)應該有一組緊密相關的行爲的意思是什麼?遵照單一職責的好處是可讓咱們很容易地來維護這個對象,當一個對象封裝了不少職責的話,一旦一個職責須要修改,勢必會影響該對象想的其它職責代碼。經過解耦可讓每一個職責工更加有彈性地變化。
不過,咱們如何知道一個對象的多個行爲構造多個職責仍是單個職責?咱們能夠經過參考Object Design: Roles, Responsibilies, and Collaborations一書提出的Role Stereotypes概念來決定,該書提出了以下Role Stereotypes來區分職責:
Information holder – 該對象設計爲存儲對象並提供對象信息給其它對象。
Structurer – 該對象設計爲維護對象和信息之間的關係
Service provider – 該對象設計爲處理工做並提供服務給其它對象
Controller – 該對象設計爲控制決策一系列負責的任務處理
Coordinator – 該對象不作任何決策處理工做,只是委派工做到其它對象上
Interfacer – 該對象設計爲在系統的各個部分轉化信息(或請求)
一旦你知道了這些概念,那就狠容易知道你的代碼究竟是多職責仍是單一職責了。
該實例代碼演示的是將商品添加到購物車,代碼很是糟糕,代碼以下:
function Product(id, description) { this.getId = function () { return id; }; this.getDescription = function () { return description; }; } function Cart(eventAggregator) { var items = []; this.addItem = function (item) { items.push(item); }; } (function () { var products = [new Product(1, "Star Wars Lego Ship"), new Product(2, "Barbie Doll"), new Product(3, "Remote Control Airplane")], cart = new Cart(); function addToCart() { var productId = $(this).attr('id'); var product = $.grep(products, function (x) { return x.getId() == productId; })[0]; cart.addItem(product); var newItem = $('<li></li>').html(product.getDescription()).attr('id-cart', product.getId()).appendTo("#cart"); } products.forEach(function (product) { var newItem = $('<li></li>').html(product.getDescription()) .attr('id', product.getId()) .dblclick(addToCart) .appendTo("#products"); }); })();
該代碼聲明瞭2個 function
分別用來描述 product
和 cart
,而匿名函數的職責是更新屏幕和用戶交互,這還不是一個很複雜的例子,但匿名函數裏卻包含了不少不相關的職責,讓咱們來看看到底有多少職責:
首先,有product
的集合的聲明
其次,有一個將product
集合綁定到#product
元素的代碼,並且還附件了一個添加到購物車的事件處理
第三,有Cart
購物車的展現功能
第四,有添加product item
到購物車並顯示的功能
讓咱們來分解一下,以便代碼各自存放到各自的對象裏,爲此,咱們參考了martinfowler的事件聚合(Event Aggregator)理論來處理代碼以便各對象之間進行通訊。
Event Aggregator 模式定義:渠道事件從多個對象經過一個單一的對象來簡化clients的註冊
首先咱們先來實現事件聚合的功能,該功能分爲2部分,1個是Event
,用於Handler
回調的代碼,1個是EventAggregator
用來訂閱和發佈Event
,代碼以下:
function Event(name) { var handlers = []; this.getName = function () { return name; }; this.addHandler = function (handler) { handlers.push(handler); }; this.removeHandler = function (handler) { for (var i = 0; i < handlers.length; i++) { if (handlers[i] == handler) { handlers.splice(i, 1); break; } } }; this.fire = function (eventArgs) { handlers.forEach(function (h) { h(eventArgs); }); }; } function EventAggregator() { var events = []; function getEvent(eventName) { return $.grep(events, function (event) { return event.getName() === eventName; })[0]; } this.publish = function (eventName, eventArgs) { var event = getEvent(eventName); if (!event) { event = new Event(eventName); events.push(event); } event.fire(eventArgs); }; this.subscribe = function (eventName, handler) { var event = getEvent(eventName); if (!event) { event = new Event(eventName); events.push(event); } event.addHandler(handler); }; }
而後,咱們來聲明Product對象,代碼以下:
function Product(id, description) { this.getId = function () { return id; }; this.getDescription = function () { return description; }; }
接着來聲明Cart對象,該對象的addItem
的function
裏咱們要觸發發佈一個事件itemAdded
,而後將item做爲參數傳進去。
function Cart(eventAggregator) { var items = []; this.addItem = function (item) { items.push(item); eventAggregator.publish("itemAdded", item); }; }
CartController
主要是接受cart
對象和事件聚合器,經過訂閱itemAdded
來增長一個li
元素節點,經過訂閱productSelected
事件來添加product
。
function CartController(cart, eventAggregator) { eventAggregator.subscribe("itemAdded", function (eventArgs) { var newItem = $('<li></li>').html(eventArgs.getDescription()).attr('id-cart', eventArgs.getId()).appendTo("#cart"); }); eventAggregator.subscribe("productSelected", function (eventArgs) { cart.addItem(eventArgs.product); }); }
Repository
的目的是爲了獲取數據(能夠從ajax
裏獲取),而後暴露get
數據的方法。
function ProductRepository() { var products = [new Product(1, "Star Wars Lego Ship"), new Product(2, "Barbie Doll"), new Product(3, "Remote Control Airplane")]; this.getProducts = function () { return products; } }
ProductController
裏定義了一個onProductSelect
方法,主要是發佈觸發productSelected
事件,forEach
主要是用於綁定數據到產品列表上,代碼以下:
function ProductController(eventAggregator, productRepository) { var products = productRepository.getProducts(); function onProductSelected() { var productId = $(this).attr('id'); var product = $.grep(products, function (x) { return x.getId() == productId; })[0]; eventAggregator.publish("productSelected", { product: product }); } products.forEach(function (product) { var newItem = $('<li></li>').html(product.getDescription()) .attr('id', product.getId()) .dblclick(onProductSelected) .appendTo("#products"); }); }
最後聲明匿名函數(須要確保HTML
都加載完了才能執行這段代碼,好比放在jQuery
的ready
方法裏):
(function () { var eventAggregator = new EventAggregator(), cart = new Cart(eventAggregator), cartController = new CartController(cart, eventAggregator), productRepository = new ProductRepository(), productController = new ProductController(eventAggregator, productRepository); })();
能夠看到匿名函數的代碼減小了不少,主要是一個對象的實例化代碼,代碼裏咱們介紹了Controller
的概念,他接受信息而後傳遞到action
,咱們也介紹了Repository
的概念,主要是用來處理product
的展現,重構的結果就是寫了一大堆的對象聲明,可是好處是每一個對象有了本身明確的職責,該展現數據的展現數據,改處理集合的處理集合,這樣耦合度就很是低了。
看到這個重構結果,有人可能要問了,真的有必要作這麼複雜麼?我只能說:要不要這麼作取決於你項目的狀況。
若是你的項目是個是個很是小的項目,代碼也不是不少,那實際上是沒有必要重構得這麼複雜,但若是你的項目是個很複雜的大型項目,或者你的小項目未來可能增加得很快的話,那就在前期就得考慮SRP原則進行職責分離了,這樣纔有利於之後的維護。
本文轉自TOM大叔的深刻理解JavaScript系列。關於S.O.L.I.D
系列的五篇文章我糾結了好久,原本不想去整理的,但最終發現其實中間說的不少都是關於OOP
(面向對象)編碼原則的東西,十分值得研讀,因此最後仍是決定整理出來。
【深刻理解JavaScript系列】文章,包括了原創,翻譯,轉載,整理等各種型文章,原文是TOM大叔的一個很是不錯的專題,現將其從新整理髮布。謝謝大叔。若是你以爲本文不錯,請幫忙點個推薦,支持一把,感激涕零。
更多優秀文章歡迎關注個人專欄