文档章节

设计模式之阅读篇

你我的宿命
 你我的宿命
发布于 2018/05/24 11:40
字数 4444
阅读 54
收藏 0

概述

设计模块有六大原则:单一职责原则、里氏替换原则、依赖倒置原则、接口隔离原则、迪米特法则、开闭原则

单一职责原则

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

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."

个人理解:一个类只负责一个业务功能

以用户管理系统为例,用户信息的增删改查通常会对应一个类,这个类会有四个方法:增删改查。

里氏替换原则

摘自: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上列的一些设计模式未列入(能力有限,没看懂)。

 

课外知识:

如有大神路过,请批评指正。

 

© 著作权归作者所有

你我的宿命
粉丝 4
博文 23
码字总数 16669
作品 0
西城
高级程序员
私信 提问
加载中

评论(0)

炒冷饭系列:设计模式 抽象工厂模式

炒冷饭系列:设计模式 抽象工厂模式 摘要: 原创出处: http://www.cnblogs.com/Alandre/ 泥沙砖瓦浆木匠 希望转载,保留摘要,谢谢! 亲爱我,孝何难;亲恶我,孝方贤。 一、什么是抽象工厂模...

泥沙砖瓦浆木匠
2014/07/24
188
0
《JavaScript设计模式与开发实践》原则篇(2)—— 最少知识原则

最少知识原则(LKP)说的是一个软件实体应当尽可能少地与其他实体发生相互作用。这 里的软件实体是一个广义的概念,不仅包括对象,还包括系统、类、模块、函数、变量等。 单一职责原则指导我们...

嗨呀豆豆呢
2018/12/30
0
0
《JavaScript设计模式与开发实践》最全知识点汇总大全

系列文章: 《JavaScript设计模式与开发实践》基础篇(1)—— this、call 和 apply 《JavaScript设计模式与开发实践》基础篇(2)—— 闭包和高阶函数 《JavaScript设计模式与开发实践》模式...

嗨呀豆豆呢
2019/01/04
0
0
编程中的那些经典套路——设计模式汇总

在正式阅读前,我先谈谈我们该用什么姿势和心态学习设计模式: 如果你还没有过多的编程经验(泛指半年以下),我建议你把它当做小说来看,能看懂多少是多少,因为半年以下经验的程序员用到设...

gzchen
2018/08/27
0
0
六个前端开发工程师必备的Web设计模式/模块资源

Yahoo的设计模式库 Yahoo的设计模式库包含了很多可以帮助开发设计人员解决遇到的问题的资源,包括开发中常常需要处理的导航,互动效果及其布局网格等大家常用的组件和模块 响应式设计模式库 ...

gbin1
2014/07/30
14
0

没有更多内容

加载失败,请刷新页面

加载更多

django

aiodns 1.1.1aiohttp 3.6.1asn1crypto 0.24.0async-timeout 3.0.1attrs 19......

MtrS
5分钟前
0
0
SQL查询单表数据(一)

本节讲述 基本的 select 查询单表数据语句 1 从单表中查询所有的行和列 查询表中所有的数据 select * from t_user 在 SQL 中,字符 "*" 具有特殊的含义,使用用它,将从指定的表中返回每一列...

赵子龙
12分钟前
5
0
签名与无符号整数

我是否正确地说有符号和无符号整数之间的区别是: 无符号可以保持较大的正值,而不是负值。 无符号使用前导位作为值的一部分,而带符号版本使用最左侧位来标识数字是正数还是负数。 有符号整...

javail
17分钟前
25
0
【Vue_05】前端工程化

一、ES6的模块化 1. ES6模块化规范 每个 js 文件都是一个独立的模块 导入模块成员使用 import 关键字 暴露模块成员使用 export 关键字 2. 基本语法 发使用 export default { }导出默认成员 ...

Demo_Null
18分钟前
18
0
阿里P7高级架构师分享6年多的Java工作经验(想冲破瓶颈者必看)

很多工作了五年左右的程序员每天已经习惯了机器般的写代码,如果是这样那么你永远只会是个基础程序员,因为你不能只会用,你要知道原理,不至于让你自己实现一个出来,但是基本原理要知道。 ...

JAVA一方
30分钟前
15
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部