設計模式之閱讀篇

概述

設計模塊有六大原則:單一職責原則、里氏替換原則、依賴倒置原則、接口隔離原則、迪米特法則、開閉原則html

單一職責原則

 摘自:https://en.wikipedia.org/wiki/Single_responsibility_principlereact

The single responsibility principle is a computer programming principle that states that every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility. Robert C. Martin expresses the principle as, "A class should have only one reason to change."git

我的理解:一個類只負責一個業務功能github

以用戶管理系統爲例,用戶信息的增刪改查一般會對應一個類,這個類會有四個方法:增刪改查。express

里氏替換原則

摘自:https://en.wikipedia.org/wiki/Liskov_substitution_principle編程

介於本人英語能力有限理解,沒法理解Wikipedia上的描述,只能從其餘大神的總結中學習。設計模式

我的理解

里氏替換原則是一個規定了如何抽象出基類的原則。緩存

摘自:https://baike.baidu.com/item/%E9%87%8C%E6%B0%8F%E6%9B%BF%E6%8D%A2%E5%8E%9F%E5%88%99/3744239多線程

Liskov於1987年提出了一個關於繼承的原則「Inheritance should ensure that any property proved about supertype objects also holds for subtype objects.」——「繼承必須確保超類所擁有的性質在子類中仍然成立。」也就是說,當一個子類的實例應該可以替換任何其超類的實例時,它們之間才具備is-A關係。併發

依賴倒置原則

摘自:https://en.wikipedia.org/wiki/Dependency_inversion_principle

In object-oriented design, the dependency inversion principle refers to a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details. The principle states:[1]

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.

B. Abstractions should not depend on details. Details should depend on abstractions.

我的理解:

「依賴」是指類A的方法須要類B,即A依賴B。

    至於類A如何使用類B的對象,能夠經過構造函數傳入,也能夠經過方法的入參,根據實際狀況而定。

「倒置」是指A依賴B時,儘可能將B抽象成一個接口,固然A也能夠一個接口。

簡言之,依賴倒置原則就是面向接口編程。

接口隔離原則

摘自:https://en.wikipedia.org/wiki/Interface_segregation_principle

The interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use.[1] ISP splits interfaces that are very large into smaller and more specific ones so that clients will only have to know about the methods that are of interest to them. Such shrunken interfaces are also called role interfaces.[2] ISP is intended to keep a system decoupled and thus easier to refactor, change, and redeploy. ISP is one of the five SOLID principles of object-oriented design, similar to the High Cohesion Principle of GRASP.[3]

我的理解:接口細分,儘可能保證接口的任一實現類不能出現一個方法不實現。

迪米特法則

摘自:https://en.wikipedia.org/wiki/Law_of_Demeter

The Law of Demeter (LoD) or principle of least knowledge is a design guideline for developing software, particularly object-oriented programs. In its general form, the LoD is a specific case of loose coupling. The guideline was proposed by Ian Holland at Northeastern University towards the end of 1987, and can be succinctly summarized in each of the following ways:[1]

  • Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.
  • Each unit should only talk to its friends; don't talk to strangers.
  • Only talk to your immediate friends.

我的理解:減小類之間的耦合度。

舉例說明:

類A的方法m的入參有類B,方法m中只能使用類A的屬性和方法、類B的public屬性和方法,使用類B的屬性和方法越少越好(低耦合)

 

開閉原則

摘自:https://en.wikipedia.org/wiki/Open/closed_principle

In object-oriented programming, the open/closed principle states "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification";[1] that is, such an entity can allow its behaviour to be extended without modifying its source code.

我的理解:

開:經過擴展來實現新功能。

閉:不能經過修改實現新功能。

舉例說明,類B繼承類A,重寫類A的方法,此處重寫便是開原則,不修改類A的方法便是閉原則,閉原則不表明不修改。

----------------------------建立型模式(Creational patterns)-------------------------

抽象工廠模式

摘自:https://en.wikipedia.org/wiki/Abstract_factory_pattern

The essence of the Abstract Factory Pattern is to "Provide an interface for creating families of related or dependent objects without specifying their concrete classes."

Abstract factory.svg

我的理解:高層只引用接口/抽象類,抽象工廠負責提供接口/抽象類的實現類。

遵循依賴倒置原則

建造者模式

摘自:https://en.wikipedia.org/wiki/Builder_pattern

The intent of the Builder design pattern is to separate the construction of a complex object from its representation. By doing so the same construction process can create different representations.

Builder Structure

我的理解:若是Product類的屬性過多,能夠用Builder類逐步設置這些屬性,高層經過Builder類建立Product類的對象。

優勢:

  • Allows you to vary a product’s internal representation.
  • Encapsulates code for construction and representation.
  • Provides control over steps of construction process.

缺點:

  • Requires creating a separate ConcreteBuilder for each different type of product. 代碼量增長
  • Requires the builder classes to be mutable.
  • Data members of class aren't guaranteed to be initialized.
  • Dependency injection may be less supported.

依賴注入

摘自:https://en.wikipedia.org/wiki/Dependency_injection

Application frameworks such as CDI and its implementation Weld, Spring, Guice, Play framework, Salta, Glassfish HK2, Dagger, and Managed Extensibility Framework (MEF) support dependency injection but are not required to do dependency injection.

優勢:

  • A依賴B,A不須要知道B是如何建立  

缺點:

  • 可讀性差

工廠模式

摘自:https://en.wikipedia.org/wiki/Factory_method_pattern

"Define an interface for creating an object, but let subclasses decide which class to instantiate. The Factory method lets a class defer instantiation it uses to subclasses." (Gang Of Four)

我的理解:同抽象工廠模式。

懶人工廠模式

摘自:https://en.wikipedia.org/wiki/Lazy_initialization

我的理解:在第一次使用的時候建立一個對象,以後都是用這個對象。

對象池模式

注:未使用過

原型模式

摘自:https://en.wikipedia.org/wiki/Prototype_pattern

The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:

  • avoid subclasses of an object creator in the client application, like the factory method pattern does.
  • avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.

我的理解:基於Cloneable接口實現複製。

優勢:

  • 減小代碼,不須要每次寫setter和getter方法
  • clone一個對象內存的消耗比new一個對象少

注:

  • 淺複製:clone默認只會複製對象的基本類型的屬性。
  • 深複製:對象的複合類型的屬性須要單獨進行clone。

 

單例模式

單例模式是最經常使用的設計模式之一,使用場景:一般用於數據共享。

書寫方式詳見(我的喜歡第五種):http://www.runoob.com/design-pattern/singleton-pattern.html

--------------------------結構型模式(Structural patterns)---------------------------

適配器模式

摘自:https://en.wikipedia.org/wiki/Adapter_pattern

An adapter allows two incompatible interfaces to work together. This is the real-world definition for an adapter. Interfaces may be incompatible, but the inner functionality should suit the need. The Adapter design pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients.

https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/ClassAdapter.png/300px-ClassAdapter.png

我的理解:類1能夠播放音樂,類2能夠播放視頻,類3集成類1和類2既能夠播放音樂也能夠播放視頻。

橋接模式

摘自:https://en.wikipedia.org/wiki/Bridge_pattern

The bridge pattern is a design pattern used in software engineering that is meant to "decouple an abstraction from its implementation so that the two can vary independently", introduced by the Gang of Four.[1] The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.

我的理解:遵循依賴倒置原則,只依賴接口/抽象類

組合模式

摘自:https://en.wikipedia.org/wiki/Composite_pattern

In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes a group of objects that is treated the same way as a single instance of the same type of object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.[1]

我的理解:Composite實現了接口Component,Composite有屬性C是「集合」,屬性C的元素是Leaf,Composite的operation方法中屬性C的元素的operation方法

裝飾器模式

摘自:https://en.wikipedia.org/wiki/Decorator_pattern

In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.[1] The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern.[2] The decorator pattern is structurally nearly identical to the chain of responsibility pattern, the difference being that in a chain of responsibility, exactly one of the classes handles the request, while for the decorator, all classes handle the request.

我的理解:WindowDecorator實現了Window,可是WindowDecorator又必須有一個Window成員,跟適配器模式和組合模式有點像。

門面模式

摘自:https://en.wikipedia.org/wiki/Facade_pattern

A facade is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can:

  • make a software library easier to use, understand, and test, since the facade has convenient methods for common tasks
  • make the library more readable, for the same reason
  • reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system
  • wrap a poorly-designed collection of APIs with a single well-designed API

https://upload.wikimedia.org/wikipedia/en/5/57/Example_of_Facade_design_pattern_in_UML.png

我的理解:提供給第三方調用的API

代理模式

摘自:https://en.wikipedia.org/wiki/Proxy_pattern

A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate. In short, a proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes. Use of the proxy can simply be forwarding to the real object, or can provide additional logic. In the proxy, extra functionality can be provided, for example caching when operations on the real object are resource intensive, or checking preconditions before operations on the real object are invoked. For the client, usage of a proxy object is similar to using the real object, because both implement the same interface.

我的理解:跟裝飾器模式有點像。

動態代理:InvocationHandler

模塊模式

摘自:https://en.wikipedia.org/wiki/Module_pattern

In software engineering, the module pattern is a design pattern used to implement the concept of software modules, defined by modular programming, in a programming language with incomplete direct support for the concept.

In software development, source code can be organized into components that accomplish a particular function or contain everything necessary to accomplish a particular task. Modular programming is one of those approaches.

The concept of a "module" is not fully supported in many common programming languages.

The object module pattern expressed in UML.

我的理解:按照功能進行模塊化,StringClass是一個大模塊(負責字符串的操做),uppercaseCopy是一個小模塊(字符串的拷貝)。

 

--------------------------行爲型模式(Behavioral patterns)---------------------------

黑版模式

摘自:https://en.wikipedia.org/wiki/Blackboard_(design_pattern)

In software engineering, the blackboard pattern is a behavioral design pattern[1] that provides a computational framework for the design and implementation of systems that integrate large and diverse specialized modules, and implement complex, non-deterministic control strategies.

我的理解:待學習

責任鏈模式

摘自:https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern

In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects.[1] Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain. Thus, the chain of responsibility is an object oriented version of the if ... else if ... else if ....... else ... endif idiom, with the benefit that the condition–action blocks can be dynamically rearranged and reconfigured at runtime.

我的理解:一批業務邏輯類依次處理一個數據類,能夠在中間某一環節中止處理(由業務定)。

命令模式

摘自:https://en.wikipedia.org/wiki/Command_pattern

In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.

我的理解:每一個功能能夠封裝成一個命令(command),再有一個命令管理器統一管理這些命令。

解釋器模式

摘自:https://en.wikipedia.org/wiki/Interpreter_pattern

In computer programming, the interpreter pattern is a design pattern that specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialized computer language. The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence for a client.[1]:243 See also Composite pattern.

我的理解:有點像命令模式,經過開發語言實現一些命令。

迭代器模式

摘自:https://en.wikipedia.org/wiki/Iterator_pattern

In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.

即Java中的Iterator

介體模式

摘自:https://en.wikipedia.org/wiki/Mediator_pattern

In software engineering, the mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program's running behavior.

我的理解:使用一個類完成多個類之間的複雜的業務場景,減小這些類之間的耦合度。

備忘錄模式

摘自:https://en.wikipedia.org/wiki/Memento_pattern

The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback).

我的理解:作緩存。

空對象設計模式

摘自:https://en.wikipedia.org/wiki/Null_object_pattern

In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral ("null") behavior. The null object design pattern describes the uses of such objects and their behavior (or lack thereof). It was first published in the Pattern Languages of Program Design book series.

我的理解:接口-實現類的方法中什麼都不作,能夠做爲缺省不處理邏輯。

觀察者模式

摘自:https://en.wikipedia.org/wiki/Observer_pattern

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

即Java的Obserable(可觀察-被後者觀察)和Observer(觀察-觀察前者)

僕人模式

摘自:https://en.wikipedia.org/wiki/Servant_(design_pattern)

In software engineering, the servant pattern defines an object used to offer some functionality to a group of classes without defining that functionality in each of them. A Servant is a class whose instance (or even just class) provides methods that take care of a desired service, while objects for which (or with whom) the servant does something, are taken as parameters.

我的理解:將一批具備相同邏輯的類的這個邏輯交由一個類完成,這個類稱做僕人。

規範模式

摘自:https://en.wikipedia.org/wiki/Specification_pattern

In computer programming, the specification pattern is a particular software design pattern, whereby business rules can be recombined by chaining the business rules together using boolean logic. The pattern is frequently used in the context of domain-driven design.

我的理解:暫時不能理解其使用場景

狀態模式

摘自:https://en.wikipedia.org/wiki/State_pattern

The state pattern is a behavioral software design pattern that implements a state machine in an object-oriented way. With the state pattern, a state machine is implemented by implementing each individual state as a derived class of the state pattern interface, and implementing state transitions by invoking methods defined by the pattern's superclass.

我的理解:Context有State屬性,State的實現類不一樣執行結果不一樣。

策略模式

摘自:https://en.wikipedia.org/wiki/Strategy_pattern

In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.

我的理解:根狀態模式有點像,Context有Strategy屬性,Strategy實現類不一樣執行結果不一樣。

模板方法模式

摘自:https://en.wikipedia.org/wiki/Template_method_pattern

In software engineering, the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in an operation, deferring some steps to subclasses.[1] It lets one redefine certain steps of an algorithm without changing the algorithm's structure.[2] The template method is one of the twenty-three well-known patterns described in the "Gang of Four" book Design Patterns.

我的理解:抽象類定義N個方法,一個方法(流程固定:public final)按照必定業務場景調用其它抽象方法(細節待定: protected)

訪問者模式

摘自:https://en.wikipedia.org/wiki/Visitor_pattern

In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existent object structures without modifying the structures. It is one way to follow the open/closed principle.

UML diagram of the Visitor pattern example with Car Elements

我的理解:經過訪問者來完成對一個對象的各個成員的操做。

--------------------------併發模式(Concurrency patterns)-------------------------

活動對象模式

摘自:https://en.wikipedia.org/wiki/Active_object

The active object design pattern decouples method execution from method invocation for objects that each reside in their own thread of control. The goal is to introduce concurrency, by using asynchronous method invocation and a scheduler for handling requests.

我的理解:基於消息隊列解決多線程同時操做一個對象的屬性。

緩衝模式

摘自:https://en.wikipedia.org/wiki/Balking_pattern

The balking pattern is a software design pattern that only executes an action on an object when the object is in a particular state. For example, if an object reads ZIP files and a calling method invokes a get method on the object when the ZIP file is not open, the object would "balk" at the request. In the Java programming language, for example, an IllegalStateException might be thrown under these circumstances.

我的理解:基於synchronized,增長同步鎖解決多線程同時操做一個對象的屬性。

綁定屬性模式

摘自:https://en.wikipedia.org/wiki/Binding_properties_pattern

The Binding properties pattern is combining multiple observers to force properties in different objects to be synchronized or coordinated in some way. This pattern was first described as a technique by Victor Porton.[1][2] This pattern comes under concurrency patterns.

我的理解:從定義來分析,經過第三方渠道同步兩個對象的屬性,可是沒法理解如何解決併發問題。

區塊鏈模式

摘自:https://en.wikipedia.org/wiki/Blockchain

待學習

雙重檢查鎖定模式

摘自:https://en.wikipedia.org/wiki/Double-checked_locking

In software engineering, double-checked locking (also known as "double-checked locking optimization"[1]) is a software design pattern used to reduce the overhead of acquiring a lock by first testing the locking criterion (the "lock hint") without actually acquiring the lock. Only if the locking criterion check indicates that locking is required does the actual locking logic proceed.

還沒有理解,從demo中,應用於單例模式。

鏈接模式

摘自:https://en.wikipedia.org/wiki/Join-pattern

Join-patterns provides a way to write concurrent, parallel and distributed computer programs by message passing. Compared to the use of threads and locks, this is a high level programming model using communication constructs model to abstract the complexity of concurrent environment and to allow scalability. Its focus is on the execution of a chord between messages atomically consumed from a group of channels.

待學習,從描述上看,像是基於消息隊列實現。

反應堆模式

摘自:https://en.wikipedia.org/wiki/Reactor_pattern

The reactor design pattern is an event handling pattern for handling service requests delivered concurrently to a service handler by one or more inputs. The service handler then demultiplexes the incoming requests and dispatches them synchronously to the associated request handlers.[1]

待學習

 

問題

  • 各個設計模式分別遵循哪些設計原則?
  • 各個設計模式的使用場景?
  • 擔憂我的理解有誤,特地摘錄Wikipedia上的描述。
  • Wikipedia上列的一些設計模式未列入(能力有限,沒看懂)。

 

課外知識:

若有大神路過,請批評指正。

相關文章
相關標籤/搜索