天天看点

设计模式学习之路-设计模式什么设计模式的六大原则设计模式的分类实际使用场景

设计模式是什么?我能想到的是「套路」,或者说是「最佳实践」。要写出「好代码」,我们需要遵循一些「最佳实践」,就好像我们要培养优秀的个人品行,需要遵循一些「美德」。

以下是美国国父富兰克林给自己列的「美德」清单:

节制:食不可饱,衣不过量。

慎言:只讲对人对己有益之言,不说无聊琐碎之话。

条理:让拥有的每件东西都各有其位,让要做的每件事都各有其时。

坚毅:一旦决定做一件事,就马上义无反顾的去做。

节俭:将钱用在于人于己有益的事情上,杜绝浪费。

勤奋:不耽误任何时间,总是在干有用的事情,终止不必要的行为。

真诚:不采用任何有害的欺骗行为,想问题和说话都要公平公正。

正直:绝不做损人利己之事。

适度:避免极端,避免别人对你产生怨恨。

清洁:决不允许身体、衣服和居所不洁。

心静:不被琐碎之事,寻常之事,和不可避免之事萦绕。

贞洁:不过度行房事,也不因男女关系损害和他人的关系。

谦卑:以耶稣和苏格拉底为楷模。

为什么列这么多美德?富兰克林的逻辑是把美德分的细一些,每个美德只包含一个简单、清晰的外延,这样就更容易做到了。

这么多美德记都记不过来,怎样才能做到?富兰克林的方案是一周只注重培养其中一个美德,这样13周就是一个周期,一年可以循环4次。

以上的13条美德和2条富兰克林的实践,就是富兰克林培养优秀个人品行的「设计模式」吧?

回到设计模式,设计模式中也有一些「美德」,我们简称它们为六大设计原则。

单一职责原则 single responsibility principle

定义:一个类应该只有一个发生变化的原因。

there should never be more than one reason for a class to change.

开闭原则 open closed principle

定义:软件实体(类、模块、函数等)应该对扩展开放,对修改关闭。

software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

里氏替换原则 liskov substitution principle

定义:如果对每一个类型为s的对象o1,都有类型为t的对象o2,使得以t定义的所有程序p在所在的对象o1都代换为o2时,程序p的行为没有发生变化,那么类型s是类型t的子类型。

if for each object o1 of type s there is an object o2 of type t such that for all programs p defined in terms of t,the behavior of p is unchanged when o1 is substituted for o2 then s is a subtype of t.

迪米特法则 law of demeter

定义:一个对象应该对其他对象有最少的了解。

only talk to your immediate friends.

接口隔离原则 interface segregation principle

定义:客户端不应该依赖它不需要的接口。

clients should not be forced to depend upon interfaces that they don’t use.

依赖倒置原则 dependence inversion principle

定义:高层模块不应该依赖低层模块,二者都应该依赖其抽象;抽象不应该依赖细节;细节应该依赖抽象。

high level modules should not depend upon low level modules.both should depend upon abstractions.abstractions should not depend upon details.details should depend upon abstractions.

创建型模式

简单工厂模式 simple factory pattern

工厂方法模式 factory method pattern

抽象工厂模式 abstract factory

建造者模式

单例模式

结构型模式

设配器模式

桥接模式

装饰模式

外观模式

享元模式

代理模式

行为型模式

命令模式

中介者模式

观察者模式

状态模式

策略模式

spring核心容器的主要组件是beanfactory,它是工厂模式的实现。

参考链接

<a href="http://design-patterns.readthedocs.io/zh_cn/latest/creational_patterns/simple_factory.html">http://design-patterns.readthedocs.io/zh_cn/latest/creational_patterns/simple_factory.html</a>

<a href="https://yq.aliyun.com/articles/109934">https://yq.aliyun.com/articles/109934</a>