一、设计模式的目的
编写软件过程中,程序员面临着来自耦合性、内聚性以及可维护性。可扩展性、重用性、灵活性等多方面的挑战,设计模式时为了让程序具有更好的:
- 代码重用性
- 可读性
- 可扩展性
- 可靠性
- 使程序呈现高内聚。低耦合的特性
二、程序设计七大原则
设计模式的原则其实就是程序员在编程时应当遵循的原则,也是各种设计模式的基础
设计模式常用的七大原则:
- 单一职责原则
- 接口隔离原则
- 依赖倒转原则
- 里氏替换原则
- 开闭原则
- 迪米特法则
- 合成复用原则
1、单一职责原则
基本介绍
对类来说的,即一个类应该只负责一项职责,如类A负责两个不同职责:职责1,职责2.当职责1需求变更而改变A时,可能造成职责2执行错误,所以需要将来A的粒度分解为A1,A2
应用实例
以交通工具为例
##### 方案一:
package com.slp.principle.singleresponsibility.v1;
public class SingeleResponsibility {
public static void main(String[] args) {
Vehicle v = new Vehicle();
v.run("汽车");
v.run("飞机");
}
}
/**
* 交通工具类
* 方式一
* 1.在方法1的run方法中,违反了单一职责原则
* 2.解决的方案非常的简单,根据交通工具运行的方法不同,分解成不同的类即可
*/
class Vehicle{
public void run(String vehicle){
System.out.println(vehicle+"在公路上奔跑");
}
}
方案二
package com.slp.principle.singleresponsibility.v2;
public class SingleResponsibility {
public static void main(String[] args) {
RodeVehicle rodeVehicle = new RodeVehicle();
rodeVehicle.run("汽车");
AirVehicle airVehicle = new AirVehicle();
airVehicle.run("飞机");
WaterVehicle waterVehicle = new WaterVehicle();
waterVehicle.run("船");
}
}
/**
* 1.遵循单一原则
* 2.但是这样改动很大,将类分解,并且需要修改客户端
* 3。改进 直接修改Vehicle类
*/
class RodeVehicle{
public void run(String name){
System.out.println(name+"在公路上运行");
}
}
class AirVehicle{
public void run(String name){
System.out.println(name+"在天上飞行");
}
}
class WaterVehicle{
public void run(String name){
System.out.println(name+"在水中运行");
}
}
方案三
package com.slp.principle.singleresponsibility.v3;
public class SingleResponsibility {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
vehicle.run("汽车");
vehicle.runAir("飞机");
vehicle.runWater("轮船");
}
}
/**
* 方式3的分析
* 1.这种修改方法没有对原来的类做大的修改,只是增加方法
* 2.虽然没有遵循类的单一职责,但是在方法上遵循了单一职责方法
*/
class Vehicle{
public void run(String vehicle){
System.out.println(vehicle+"在公路上奔跑");
}
public void runAir(String vehicle){
System.out.println(vehicle+"在天空飞行");
}
public void runWater(String vehicle){
System.out.println(vehicle+"在水中");
}
}
注意事项和细节
- 降低类的复杂度,一个类只负责一项职责
- 提高类的可读性,可维护性
- 降低变更引起的风险
- 通常情况下,我们引导遵循单一职责原则,只要逻辑足够简单,才可以在代码级违反单一职责原则:只有类中方法数量足够少,可以猜方法级别保持单一职责原则
2、接口隔离原则
基本介绍
客户端不应该依赖他不需要的接口,即一个雷对另一个类的依赖应该建立在最小的接口上
看一个图:
类A通过Interface1依赖类B,类C通过Interface1依赖类D,如果接口Interface1对于类A和类C来说都不是最小接口,那么累B和类D西部区实现他们不需要的方法
按照隔离原则应该这样处理:
将接口Interface1拆分成独立的几个接口,类A和类C分贝与他们对应的接口发生关系,
应用实例
原有代码:
package com.slp.principle.segregation.v1;
public class Segregation {
}
interface Interface1{
void operation1();
void operation2();
void operation3();
void operation4();
void operation5();
}
class B implements Interface1{
@Override
public void operation1() {
System.out.println("B中实现了operation1");
}
@Override
public void operation2() {
System.out.println("B中实现了operation2");
}
@Override
public void operation3() {
System.out.println("B中实现了operation3");
}
@Override
public void operation4() {
System.out.println("B中实现了operation4");
}
@Override
public void operation5() {
System.out.println("B中实现了operation5");
}
}
class D implements Interface1{
@Override
public void operation1() {
System.out.println("D中实现了operation1");
}
@Override
public void operation2() {
System.out.println("D中实现了operation2");
}
@Override
public void operation3() {
System.out.println("D中实现了operation3");
}
@Override
public void operation4() {
System.out.println("D中实现了operation4");
}
@Override
public void operation5() {
System.out.println("D中实现了operation5");
}
}
//A类通过interface依赖B 但是只用到了1 2 3 方法
class A{
public void depend1(Interface1 interface1){
interface1.operation1();
}
public void depend2(Interface1 interface1){
interface1.operation2();
}
public void depend3(Interface1 interface1){
interface1.operation3();
}
}
//C类通过interface依赖D 但是只用到了1 4 5 方法
class C{
public void depend1(Interface1 interface1){
interface1.operation1();
}
public void depend4(Interface1 interface1){
interface1.operation4();
}
public void depend5(Interface1 interface1){
interface1.operation5();
}
}
按照接口隔离原则对接口进行拆分:
将Interface1拆分为独立的几个接口。
改进后的代码
package com.slp.principle.segregation.v2;
public class Segregation {
public static void main(String[] args) {
A a = new A();
a.depend1(new B());//A类通过接口去依赖B类
a.depend2(new B());
a.depend3(new B());
C c = new C();
c.depend1(new D());
c.depend4(new D());
c.depend5(new D());
}
}
interface Interface1{
void operation1();
}
interface Interface2{
void operation2();
void operation3();
}
interface Interface3{
void operation4();
void operation5();
}
class B implements Interface1,Interface2 {
@Override
public void operation1() {
System.out.println("B中实现了operation1");
}
@Override
public void operation2() {
System.out.println("B中实现了operation2");
}
@Override
public void operation3() {
System.out.println("B中实现了operation3");
}
}
class D implements Interface1,Interface3 {
@Override
public void operation1() {
System.out.println("D中实现了operation1");
}
@Override
public void operation4() {
System.out.println("D中实现了operation4");
}
@Override
public void operation5() {
System.out.println("D中实现了operation5");
}
}
//A类通过interface依赖B 但是只用到了1 2 3 方法
class A{
public void depend1(Interface1 interface1){
interface1.operation1();
}
public void depend2(Interface2 interface2){
interface2.operation2();
}
public void depend3(Interface2 interface2){
interface2.operation3();
}
}
//C类通过interface依赖D 但是只用到了1 4 5 方法
class C{
public void depend1(Interface1 interface1){
interface1.operation1();
}
public void depend4(Interface3 interface3){
interface3.operation4();
}
public void depend5(Interface3 interface3){
interface3.operation5();
}
}
3、依赖倒转原则
基本介绍
依赖倒转原则是指:
- 高层模块不应该依赖底层模块,二者都应该依赖其抽象
- 抽象不应该依赖于细节,细节应该依赖于抽象
- 依赖倒转的中心思想是面向接口编程
- 相对于细节的多变性抽象的东西要稳定的多,以抽象为基础搭建的架构要比以系列为基础的架构要稳定的多,在java中,抽象指的是接口或抽象类,细节就是具体的实现类
- 使用姐或抽象类的目录就是制定好规范,而不涉及任何具体的操作,把展现细节的任务交给他们的实现类来完成
应用实例
有一个Person类完成接收消息的功能
方案一
package com.slp.principle.inversion.v1;
public class DependecyInversion {
public static void main(String[] args) {
Person p=new Person();
p.receive(new Email());
}
}
/**
* 完成person接收信息的功能
* 方式1
* 1.比较简单 比较容易想到
* 2.如果我们获取的对象是微信、短信等,则需要新增类同时person类也要增加相应的犯法
* 3.解决思路:引入一个抽象的接IReceiver 这样person类与接口发生依赖,
* 因为email weixin都属于接收的对象他们各自实现接口即可
*/
class Person{
public void receive(Email email){
System.out.println(email.getInfo());
}
}
class Email{
public String getInfo(){
return "电子邮件信息:hello";
}
}
方案二
package com.slp.principle.inversion.v2;
public class DependecyInversion {
public static void main(String[] args) {
//客户端无需改变
Person p =new Person();
p.receive(new Email());
p.receive(new WEIXIN());
}
}
class Person{
public void receive(IReceiver receiver){
System.out.println(receiver.getInfo());
}
}
class Email implements IReceiver{
public String getInfo(){
return "电子邮件信息:hello";
}
}
interface IReceiver{
public String getInfo();
}
class WEIXIN implements IReceiver{
@Override
public String getInfo() {
return "微信消息:hello";
}
}
依赖关系传递的三种方式和应用案例
接口传递
package com.slp.principle.inversion.v3;
import javax.print.DocFlavor;
public class DependencyPass {
public static void main(String[] args) {
ChangHong changHong = new ChangHong();
OpenAndClose openAndClose = new OpenAndClose();
openAndClose.open(changHong);
}
}
//通过接口传递实现依赖
interface IOpenAndClose{
public void open(ITV tv);//抽象方法接收接口
}
interface ITV{
public void play();
}
class ChangHong implements ITV{
@Override
public void play() {
System.out.println("长虹电视机,打开");
}
}
//实现接口
class OpenAndClose implements IOpenAndClose{
@Override
public void open(ITV tv) {
tv.play();
}
}
构造方法传递
package com.slp.principle.inversion.v3;
import javax.print.DocFlavor;
public class DependencyPass {
public static void main(String[] args) {
ChangHong changHong = new ChangHong();
//OpenAndClose openAndClose = new OpenAndClose();
//openAndClose.open(changHong);
OpenAndClose openAndClose = new OpenAndClose(changHong);
openAndClose.open();
}
}
//方式二 通过构造方法依赖传递
interface IOpenAndClose{
public void open();//抽象方法
}
interface ITV{
public void play();
}
class OpenAndClose implements IOpenAndClose{
public ITV tv;
public OpenAndClose(ITV tv){
this.tv = tv;
}
@Override
public void open() {
tv.play();
}
}
class ChangHong implements ITV{
@Override
public void play() {
System.out.println("长虹电视机,打开");
}
}
setter方式传递
package com.slp.principle.inversion.v3;
import javax.print.DocFlavor;
public class DependencyPass {
public static void main(String[] args) {
ChangHong changHong = new ChangHong();
//OpenAndClose openAndClose = new OpenAndClose();
//openAndClose.open(changHong);
//OpenAndClose openAndClose = new OpenAndClose(changHong);
//openAndClose.open();
OpenAndClose openAndClose = new OpenAndClose();
openAndClose.setTv(changHong);
openAndClose.open();
}
}
//方式3 通过setter方式传递
interface IOpenAndClose{
public void open();//抽象方法
public void setTv(ITV tv);
}
interface ITV{
public void play();
}
class OpenAndClose implements IOpenAndClose{
private ITV tv;
@Override
public void open() {
tv.play();
}
public void setTv(ITV tv){
this.tv=tv;
}
}
class ChangHong implements ITV {
@Override
public void play() {
System.out.println("长虹电视机,打开");
}
}
注意事项和原则
- 底层模块进来都要有抽象类或接口,或者两者都有,程序稳定性更好
- 变量的变量类型尽量是抽象类或接口,这样我们的变量引用和实际对象间,就存在一个缓冲层,利于程序扩展和优化
- 继承时遵循里式替换原则
4、里氏替换原则
OO中的继承性的思考和说明
- 继承包含这样一层含义:父类中凡是已经实现好的方法,实际上是在设定规范和契约,虽然他不强制要求所有的子类都必须遵守这些契约,,但是如果子类对这些已经实现的方法任意修改,就会对整个继承体系造成破坏
- 继承在给程序设计带来便利的同时,也带来了弊端,比如使用继承会给程序带来侵入性,程序的可移植性降低,增加对象间的耦合性,如果一个类被其它的类所继承,则当这个类需要修改时,必须考虑到所有的子类,并且父类修改后,所有涉及到子类的功能都有可能产生故障
- 那么,在编程中,如何正确的使用继承?就是我们下面要说的里氏替换原则
基本介绍
- 如果对每个类型为T1的对象o1,都有类型为T2的对象o2,使得以T1定义的所有程序P在所有的对象o1都换成o2时,程序P的行为没有发生变化,那么类型T2是类型T1的子类型,换句话说,所有引用基类的地方必须能透明的使用其子类的对象
- 在继承时,遵循里氏替换原则,在子类中尽量不要重写父类的方法
- 里氏替换原则告诉我们,继承实际上让两个类耦合性增强了,在适当的情况下,可通过聚合、组合、依赖来解决问题
思考
package com.slp.principle.liskov.v1;
public class Liskov {
public static void main(String[] args) {
A a = new A();
a.fun1(11,3);
a.fun1(1,8);
B b =new B();
b.fun1(11,3);
b.fun1(1,8);//本意是做减法
}
}
class A{
public int fun1(int num1,int num2){
return num1-num2;
}
}
//B继承与A
//增加了一个新功能,完成两个数相加
class B extends A{
@Override
public int fun1(int num1, int num2) {
return num1+num2;
}
public int fun2(int a,int b){
return a-b;
}
}
解决办法
- 我们发现原来运行正常的减法功能发生了错误,原因就是累B无意间重写了父类的方法,造成原有的功能发生错误
- 通用的做法是原来的父类和子类都集成一个更通俗的基类,原有的继承关系去掉,采用依赖,聚合。组合的方式替换
package com.slp.principle.liskov.v2;
public class Liskov {
public static void main(String[] args) {
A a = new A();
a.fun1(11,3);
a.fun1(1,8);
//因为B不再继承A类,因此调用者不会再认为fun1是求减法了
B b =new B();
b.fun1(11,3);
b.fun1(1,8);//本意是做减法
//使用组合依然可以使用到A累的方法
System.out.println(b.fun3(11,3));
}
}
class Base{
//将更加基础的方法和成员写到Base类中
}
class A extends Base{
public int fun1(int num1,int num2){
return num1-num2;
}
}
//B继承与A
//增加了一个新功能,完成两个数相加
class B extends Base{
//如果B需要使用A的方法,使用组合的关系
private A a = new A();
public int fun1(int num1, int num2) {
return num1+num2;
}
public int fun2(int a,int b){
return a-b;
}
//假如我们仍然想使用A的方式
public int fun3(int a,int b){
return this.a.fun1(a,b);
}
}
5、开闭原则
基本介绍
- 最基础也是最重要的原则
- 对扩展开放,对修改关系。用抽象形成框架,用实现扩展细节
- 尽量使用扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化
- 编程中遵循其他原则,以及使用设计模式的目的就是遵循开闭原则
看示例
方案一
package com.slp.principle.ocp.v1;
/**
* @ClassName Ocp
* @Description 开闭原则修改前版本
* @Author sanglp
* @Date 2020/8/13 10:54
* @Version 1.0
**/
public class Ocp {
public static void main(String[] args) {
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawShape(new Rectangle());
graphicEditor.drawShape(new Circle());
graphicEditor.drawShape(new Triangle());
}
}
class Shape{
int m_type;
}
class GraphicEditor{
/**
* 接收shape对象,然后根据type来绘制不同的图形
* @param shape
*/
public void drawShape(Shape shape){
if(shape.m_type == 1){
drawRectangle(shape);
}else if(shape.m_type == 2){
drawCircle(shape);
}else if(shape.m_type ==3){
drawTriangle(shape);
}
}
//画矩形
public void drawRectangle(Shape r){
System.out.println("画一个大操场");
}
//画圆形
public void drawCircle(Shape r){
System.out.println("画一个大太阳");
}
//画三角形
public void drawTriangle(Shape r){
System.out.println("画一个大山峰");
}
}
class Rectangle extends Shape{
Rectangle(){
super.m_type=1;
}
}
class Circle extends Shape{
Circle(){
super.m_type=2;
}
}
class Triangle extends Shape{
Triangle(){
super.m_type=3;
}
}
优点:
- 比较好理解,简单容易操作
缺点:
- 违反了设计模式的ocp原则,即对扩展开发,对修改关闭,即当我们给类增加新功能的时候,尽量不修改代码,或者尽可能少修改代码
比如,我们要增加一个图形种类的话需要修改的地方很多:
- 增加一个类型继承shape类
- 增加一个绘制图形的方法
- 一个if判断的地方增加
改进思路
我们可以把Shape类做成抽象类,并提供一个抽象的draw方法,让子类去实现即可,这样我们有新的图形种类的时候,只需要让新的图形类继承shape,并实现draw方法即可,使用方的代码就不需要修改,这样子就满足了开闭原则
方案二
package com.slp.principle.ocp.v2;
/**
* @ClassName Ocp
* @Description 符合开闭原则的版本
* @Author sanglp
* @Date 2020/8/13 11:14
* @Version 1.0
**/
public class Ocp {
public static void main(String[] args) {
GraphicEditoe graphicEditoe = new GraphicEditoe();
graphicEditoe.drawShape(new Rectangle());
graphicEditoe.drawShape(new Circle());
graphicEditoe.drawShape(new Triangle());
}
}
abstract class Shape{
int m_type;
public abstract void draw();
}
/**
* 这是一个用于绘图的类【使用方】
*/
class GraphicEditoe{
//接收Shape,调用draw方法
public void drawShape(Shape s){
s.draw();
}
}
class Rectangle extends Shape{
Rectangle(){
super.m_type = 1;
}
@Override
public void draw() {
System.out.println("画个大操场");
}
}
class Circle extends Shape{
Circle(){
super.m_type=2;
}
@Override
public void draw() {
System.out.println("画个大太阳");
}
}
/**
* 如果需要新增一个三角形
*/
class Triangle extends Shape{
Triangle(){
super.m_type=2;
}
@Override
public void draw() {
System.out.println("画个大山峰");
}
}
6.迪米特法则
基本介绍
- 一个对象应该对其他对象保持最少的了解
- 类与类关系越密切,耦合度越大
- 迪米特法则又叫最少知道原则,即一个类对自己依赖的类知道的越少越好。也就是说,对于被依赖的类不管多么复杂,都尽量将逻辑封装在类的内部,对外部除了提供的public方法,不对外泄漏任何信息
- 迪米特法则还有一个更简单的定义:只与直接的朋友通信
- 直接的朋友:每个对象都会与其他对象有耦合关系,只要两个对象之间有耦合关系,我们就说这两个对象之间是朋友关系,耦合的方式很多,依赖、关联、组合、聚合等,其中,我们称出现成员变量,方法参数,方法返回值中的类为直接的朋友,而出现在局部变量中的类不是直接的朋友。也就是说,陌生的类最好不要以局部变量的形式出现在类的内部。
应用实例
加入i有一个学校,下属有各个学院和总部,现要求打印出学校总部员工ID和学院员工的id.
方案一
package com.slp.principle.demeter.v1;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName Demeter
* @Description 迪米特原则改造前版本
* @Author sanglp
* @Date 2020/8/13 14:26
* @Version 1.0
**/
public class Demeter {
public static void main(String[] args) {
SchoolManager schoolManager = new SchoolManager();
schoolManager.printAllEmployee(new CollegeManager());
}
}
//学校总部员工类
class Employee{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
class CollegeEmployee{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
//管理学院员工的管理类
class CollegeManager{
public List<CollegeEmployee> getAllEmployee(){
List<CollegeEmployee> list = new ArrayList<CollegeEmployee>();
for (int i = 0; i < 10; i++) {
CollegeEmployee emp = new CollegeEmployee();
emp.setId("学院员工id="+i);
list.add(emp);
}
return list;
}
}
//管理学校员工的管理类
class SchoolManager{
public List<Employee> getAllEmployee(){
List<Employee> list = new ArrayList<Employee>();
for (int i = 0; i < 10; i++) {
Employee emp = new Employee();
emp.setId("学院总部员工id="+i);
list.add(emp);
}
return list;
}
/**
* 该方法完成输出学校总部和学院员工信息id
* 分析问题:
* 1.这里的CollegeEmployee不是SchoolManager的直接朋友
* 2.CollegeEmployee是以局部变量方式出现在SchoolManager
* 3.违反了迪米特法则
* @param sub
*/
void printAllEmployee(CollegeManager sub){
List<CollegeEmployee> list1 = sub.getAllEmployee();
System.out.println("-----学院员工-----");
for(CollegeEmployee e:list1){
System.out.println(e.getId());
}
//获取到学校总部员工
List<Employee> list2 = this.getAllEmployee();
System.out.println("-----学校总部员工-----");
for(Employee e :list2){
System.out.println(e.getId());
}
}
}
改进思路
- 前面设计的问题在于SchoolManager中,CollegeEmployee类并不是SchoolManager类的直接朋友
方案二
package com.slp.principle.demeter.v2;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName Demeter
* @Description TODO
* @Author sanglp
* @Date 2020/8/13 17:04
* @Version 1.0
**/
public class Demeter {
}
//学校总部员工类
class Employee{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
class CollegeEmployee{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
//管理学院员工的管理类
class CollegeManager{
public List<CollegeEmployee> getAllEmployee(){
List<CollegeEmployee> list = new ArrayList<CollegeEmployee>();
for (int i = 0; i < 10; i++) {
CollegeEmployee emp = new CollegeEmployee();
emp.setId("学院员工id="+i);
list.add(emp);
}
return list;
}
//输出学院员工的信息
public void printEmployee(){
List<CollegeEmployee> list1 = getAllEmployee();
System.out.println("-------------学院员工-----------");
for(CollegeEmployee e :list1){
System.out.println(e.getId());
}
}
}
/**
* 分析:SchoolManager类的直接朋友类有哪些 Employee CollegeManager
* CollegeEmployee不是直接朋友 而是一个陌生类,这样违背了一个迪米特法则
*/
class SchoolManager{
public List<Employee> getAllEmployee(){
List<Employee> list = new ArrayList<Employee>();
for (int i = 0; i < 10; i++) {
Employee emp = new Employee();
emp.setId("学院总部员工id="+i);
list.add(emp);
}
return list;
}
void printAllEmployee(CollegeManager sub){
//1.将输出学院的员工方法,封装到CollegeManager
sub.printEmployee();
//获取到学校总部员工
List<Employee> list2 = this.getAllEmployee();
System.out.println("------------学校总部员工-----");
for(Employee e:list2){
System.out.println(e.getId());
}
}
}
注意事项
- 迪米特原则的核心思想是降低类之间的耦合
- 但是需要注意:由于每个类都减少了不必要的依赖,因此迪米特法则只是要求降低类间耦合关系,并不是要求完全没有依赖关系。
7.合成复用原则
基本介绍
尽量减少使用合成/聚合的方式,而不是使用继承
通常类的复用分为继承复用和合成复用两种,继承复用虽然有实现和易实现的优点,但是它也存在如下的缺点:
- 继承复用破坏了类的封装性。因为继承会将父类的实现细节暴露给子类,父类对子类是透明的,所以这种复用又称为“白箱”复用。
- 子类与父类的耦合度高。父类的实现的任何改变都会导致子类的实现发生变化,这不利于类的扩展与维护。
- 它限制了复用的灵活性。从父类继承而来的实现是静态的,在编译时已经定义,所以在运行时不可能发生变化。
所以我们可以通过将已有的对象纳入新对象中,作为新对象的成员对来来实现,新对象可以调用已有对象的功能,从而达到复用。