设计模式七大原则
一、单一职责原则
1. 基本介绍
对类来说的,即一个类应该只负责一项职责。如类A负责两个不同职责:职责1,职责2。当职责1需求变更而改变A时,可能造成职责2执行错误,所以需要将类A的粒度分解为A1,A2
2. 代码
方案1
public class SingleResponsibility01 {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
vehicle.run("摩托车");
vehicle.run("汽车");
vehicle.run("飞机1");
}
}
// 交通工具类
// 方案1
// 1. 在方案1的run方法中,违反了单一职责原则
// 2. 解决方案非常简单,工具交通工具的运行方式不同,分解成不同的类即可
class Vehicle {
public void run(String vehicle) {
System.out.println(vehicle + " 在公路上运行...");
}
}
方案2
public class SingleResponsibility02 {
public static void main(String[] args) {
RoadVehicle roadVehicle = new RoadVehicle();
roadVehicle.run("汽车");
AirVehicle airVehicle = new AirVehicle();
airVehicle.run("飞机");
}
}
// 方案2的分析
// 1. 遵守了单一职责原则
// 2. 但这样做的改动很大,即将类分解,同时修改客户端
// 3. 改进:直接修改Vehicle类,改动的代码会比较少==》方案3
class RoadVehicle {
public void run(String vehicle) {
System.out.println(vehicle + " 在公路上运行...");
}
}
class AirVehicle {
public void run(String vehicle) {
System.out.println(vehicle + " 在天空运行...");
}
}
class WaterVehicle {
public void run(String vehicle) {
System.out.println(vehicle + " 在水中运行...");
}
}
方案3
public class SingleResponsibility03 {
public static void main(String[] args) {
Vehicle2 vehicle2 = new Vehicle2();
vehicle2.runAir("飞机");
vehicle2.runWater("轮船");
vehicle2.run("汽车");
}
}
// 方案3的分析
// 1. 这种修改方式没有对原先的类做大的修改,只是增加了类
// 2. 这里虽然没有在类的级别上遵守单一职责原则,但在方法级别上遵守
class Vehicle2 {
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 + " 在水中运行...");
}
}
3. 小结
- 降低类的复杂度,一个类只负责一项职责。
- 提高类的可读性,可维护性
- 降低变更引起的风险
- 通常情况下,我们应当遵守单一职责原则,只有逻辑足够简单,才可以在代码级违反单一职责原则;只有类中方法数量足够少,可以在方法级别保持单一职责原则
二、接口隔离原则
1. 基本介绍
客户端不应该依赖它不需要的接口,即一个类对另一个类的依赖应该建立在最小的接口上
2. 代码
// 未改进
public class segregation01 {
public static void main(String[] args) {
}
}
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");
}
}
class A { // A类通过接口Interface1依赖(使用)B类,但只使用到1,2,3方法
public void depend1(Interface1 interface1) {
interface1.operation1();
}
public void depend2(Interface1 interface1) {
interface1.operation2();
}
public void depend3(Interface1 interface1) {
interface1.operation3();
}
}
class C { // B类通过接口Interface1依赖(使用)D类,但只使用到1,3,5方法
public void depend1(Interface1 interface1) {
interface1.operation1();
}
public void depend4(Interface1 interface1) {
interface1.operation4();
}
public void depend5(Interface1 interface1) {
interface1.operation5();
}
}
// 改进
public class segregation01 {
public static void main(String[] args) {
A a = new A();
B b = new B();
a.depend1(b);
a.depend2(b);
a.depend3(b);
C c = new C();
D d = new D();
c.depend1(d);
c.depend4(d);
c.depend5(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");
}
}
class A { // A类通过接口 Interface1,Interface2 依赖(使用)B类,但只使用到1,2,3方法
public void depend1(Interface1 interface1) {
interface1.operation1();
}
public void depend2(Interface2 interface2) {
interface2.operation2();
}
public void depend3(Interface2 interface2) {
interface2.operation3();
}
}
class C { // B类通过接口 Interface1,Interface13 依赖(使用)D类,但只使用到1,3,5方法
public void depend1(Interface1 interface1) {
interface1.operation1();
}
public void depend4(Interface3 interface3) {
interface3.operation4();
}
public void depend5(Interface3 interface3) {
interface3.operation5();
}
}
3. 小结
类A
通过接口Interface1
依赖类B
,类C
通过接口Interface1
依赖类D
,如果接口Interface1
对于类A
和类C
来说不是最小接口,那么类B
和类D
必须去实现他们不需要的方法- 将接口
Interface1
拆分为独立的几个接口,类A
和类C
分别与他们需要的接口建立依赖关系。也就是采用接口隔离原则 - 接口
Interface1
中出现的方法,根据实际情况拆分为三个接口
三、依赖倒转原则
1. 基本介绍
高层模块不应该依赖低层模块,二者都应该依赖其抽象
抽象不应该依赖细节,细节应该依赖抽象
依赖倒转(倒置)的中心思想是
面向接口编程
依赖倒转原则是基于这样的设计理念:相对于细节的多变性,抽象的东西要稳定的多。以抽象为基础搭建的架
构比以细节为基础的架构要稳定的多。在java中,抽象指的是接口或抽象类,细节就是具体的实现类
使用
接口或抽象类
的目的是制定好规范,而不涉及任何具体的操作,把展现细节的任务交给他们的实现类
去完成
2. 代码
方式1
public class DependInversion {
public static void main(String[] args) {
Person person = new Person();
person.receive(new Email());
}
}
class Email {
public String getInfo() {
return "电子邮件消息:Hello World";
}
}
// 完成Person接收消息的功能
// 方式1
// 1. 简单,比较容易想到
// 2. 如果我们获取的对象是 微信,短信等等,则要新增类,同时Person类也要添加相应的接收方法
// 3. 解决思路:引入一个抽象的接口 IReceiver,表示接收者,这样Person类与接口发生依赖
// 因为Email,微信等属于接收范围,他们各自实现IReceiver 接口就ok,这样就符合依赖倒置原则
class Person {
public void receive(Email email) {
System.out.println(email.getInfo());
}
}
方式2
public class DependInversion {
public static void main(String[] args) {
Person person = new Person();
person.receive(new Email());
person.receive(new WeiXin());
}
}
// 定义一个接口
interface IReceiver {
public String getInfo();
}
class Email implements IReceiver {
public String getInfo() {
return "电子邮件消息:Hello World";
}
}
// 增加微信
class WeiXin implements IReceiver {
public String getInfo() {
return "微信消息:OK";
}
}
// 方式2
class Person {
// 这里我们是对接口的一个依赖
public void receive(IReceiver iReceiver) {
System.out.println(iReceiver.getInfo());
}
}
依赖关系传递的三种方式:
- 接口传递
public class DependPass {
public static void main(String[] args) {
ATV atv = new ATV();
OpenAndClose openAndClose = new OpenAndClose();
openAndClose.open(atv);
}
}
// 方式1:通过接口传递依赖
// 开关接口
interface IOpenAndClose {
void open(ITV tv); // 抽象方法,接收接口
}
interface ITV { // ITV接口
void play();
}
// 实现类
class OpenAndClose implements IOpenAndClose {
@Override
public void open(ITV tv) {
tv.play();
}
}
- 构造方法传递
public class DependPass {
public static void main(String[] args) {
ATV atv = new ATV();
OpenAndClose openAndClose = new OpenAndClose(atv);
openAndClose.open();
}
}
// 方式2:通过构造方法依赖传递
interface IOpenAndClose {
void open(); // 抽象方法
}
interface ITV { // ITV接口
void play();
}
class ATV implements ITV {
@Override
public void play() {
System.out.println("打开ATV");
}
}
class OpenAndClose implements IOpenAndClose {
public ITV tv; // 属性
public OpenAndClose(ITV tv) {
this.tv = tv;
}
@Override
public void open() {
this.tv.play();
}
}
- setter方法传递
public class DependPass {
public static void main(String[] args) {
ATV atv = new ATV();
OpenAndClose openAndClose = new OpenAndClose();
openAndClose.setTV(atv);
openAndClose.open();
}
}
// 方式3:通过setter方法依赖传递
interface IOpenAndClose {
void open(); // 抽象方法
void setTV(ITV tv);
}
interface ITV { // ITV接口
void play();
}
class ATV implements ITV {
@Override
public void play() {
System.out.println("打开ATV");
}
}
class OpenAndClose implements IOpenAndClose {
public ITV tv; // 属性
@Override
public void setTV(ITV tv) {
this.tv = tv;
}
@Override
public void open() {
this.tv.play();
}
}
3. 小结
- 低层模块尽量都要有抽象类或接口,或者两者都有,程序稳定性更好
- 变量的声明类型尽量是抽象类或接口,这样我们的变量引用和实际对象间,就存在一个缓冲层,利于程序扩展和优化
- 继承时遵循里氏替换原则
四、里氏替换原则
1. 基本介绍
- 继承包含这样一层含义:父类中凡是已经实现好的方法,实际上是在设定规范和契约,虽然它不强制要求所有的子类必须遵循这些契约,但是如果子类对这些已经实现的方法任意修改,就会对整个继承体系造成破坏。
- 继承在给程序设计带来便利的同时,也带来了弊端。比如使用继承会给程序带来侵入性,程序的可移植性降低,增加对象间的耦合性,如果一个类被其他的类所继承,则当这个类需要修改时,必须考虑到所有的子类,并且父类修改后,所有涉及到子类的功能都有可能产生故障。
- 问题提出:在编程中,如何正确的使用继承?=>里氏替换原则。
- 里氏替换原则(Liskov Substitution Principle)在1988年,由麻省理工学院的以为姓里的女士提出的。
- 如果对每个类型为T1的对象ol,都有类型为T2的对象o2,使得以T1定义的所有程序Р在所有的对象ol都代换成o2时,程序P的行为没有发生变化,那么类型T2是类型T1的子类型。换句话说,所有引用基类的地方必须能透明地使用其子类的对象。
- 在使用继承时,遵循里氏替换原则,在子类中尽量不要重写父类的方法。
- 里氏替换原则告诉我们,继承实际上让两个类耦合性增强了,在适当的情况下,可以通过聚合,组合,依赖来解决问题。
2. 代码
public class Liskov01 {
public static void main(String[] args) {
A a = new A();
System.out.println("11-3=" + a.func1(11,3));
System.out.println("1-8=" + a.func1(1,8));
System.out.println("==============");
B b = new B();
System.out.println("11-3=" + b.func1(11,3));
System.out.println("1-8=" + b.func1(1,8));
System.out.println("11+3+9=" + b.func2(11,3));
}
}
class A {
public int func1(int num1, int num2) {
return num1 - num2;
}
}
class B extends A {
// 这里的重写可能是无意识的
@Override
public int func1(int num1, int num2) {
return num1 + num2;
}
public int func2(int a, int b) {
return func1(a, b) + 9;
}
}
改进
public class Liskov01 {
public static void main(String[] args) {
A a = new A();
System.out.println("11-3=" + a.func1(11,3));
System.out.println("1-8=" + a.func1(1,8));
System.out.println("==============");
B b = new B();
// 因为B类不再继承A类,因此调用者不会再使用func1求减法
// 调用完成的功能就会很明确
System.out.println("11+3=" + b.func1(11,3));
System.out.println("1+8=" + b.func1(1,8));
System.out.println("11+3+9=" + b.func2(11,3));
// 使用组合仍然可以使用到A类的方法
System.out.println("11-3=" + b.func3(11,3));
}
}
// 创建一个更加基础的基类
class Base {
// 把更加基础的方法和成员写到Base类
}
class A extends Base {
public int func1(int num1, int num2) {
return num1 - num2;
}
}
class B extends Base {
// 如果B需要使用A类的方法,这里使用组合
private A a = new A();
public int func1(int num1, int num2) {
return num1 + num2;
}
public int func2(int a, int b) {
return func1(a, b) + 9;
}
// 我们仍然想使用A的方法
public int func3(int a,int b) {
return this.a.func1(a,b);
}
}
3. 小结
- 我们发现原来运行正常的相减功能发生了错误。原因就是类B无意中重写了父类的方法,造成原有功能出现错误。在实际编程中,我们常常会通过重写父类的方法完成新的功能,这样写起来虽然简单,但整个继承体系的复用性会比较差。特别是运行多态比较频繁的时候。
- 通用的做法是:原来的父类和子类都继承一个
更通俗的基类
,原有的继承
关系去掉,采用依赖
,聚合
,组合
等关系代替。
五、开闭原则
1. 基本介绍
- 开闭原则(Open Closed Principle)是编程中
最基础
、最重要
的设计原则- 一个软件实体如类,模块和函数应该对扩展开放(
对提供方
),对修改关闭(对使用方
)。用抽象构建框架,用实现扩展细节。- 当软件需要变化时,尽量
通过扩展
软件实体的行为来实现变化,而不是通过修改
已有的代码来实现变化。- 编程中遵循其它原则,以及使用设计模式的目的就是遵循开闭原则。
2. 代码
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 GraphicEditor {
// 接收子类,来绘制不同的图形
public void drawShape(Shape shape) {
if (shape.m_type == 1) {
drawRectangle();
} else if (shape.m_type == 2) {
drawCircle();
} else if (shape.m_type == 3) {
drawTriangle();
}
}
public void drawRectangle() {
System.out.println("矩形");
}
public void drawCircle() {
System.out.println("圆形");
}
public void drawTriangle() {
System.out.println("三角形");
}
}
// 基类
class Shape {
int m_type;
}
class Rectangle extends Shape {
Rectangle() {
this.m_type = 1;
}
}
class Circle extends Shape {
Circle() {
this.m_type = 2;
}
}
// 新增三角形类
class Triangle extends Shape {
Triangle() {
this.m_type = 3;
}
}
改进
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());
graphicEditor.drawShape(new OtherGraphic());
}
}
// 这是一个用于绘图的类
class GraphicEditor {
// 接收子类,来绘制不同的图形
public void drawShape(Shape shape) {
shape.draw();
}
}
// 基类
abstract class Shape {
int m_type;
public abstract void draw();
}
class Rectangle extends Shape {
Rectangle() {
this.m_type = 1;
}
@Override
public void draw() {
System.out.println("矩形");
}
}
class Circle extends Shape {
Circle() {
this.m_type = 2;
}
@Override
public void draw() {
System.out.println("圆形");
}
}
// 新增三角形类
class Triangle extends Shape {
Triangle() {
this.m_type = 3;
}
@Override
public void draw() {
System.out.println("三角形");
}
}
// 新增其他图形
class OtherGraphic extends Shape {
@Override
public void draw() {
System.out.println("其他图形");
}
}
3. 小结
无
六、迪米特法则
1. 基本介绍
一个对象应该对其他对象保持最少的了解
类与类关系越密切,耦合度越大
迪米特法则(Demeter Principle)又叫
最少知道原则
,即一个类对自己依赖的类知道的越少越好。也就是说,对于被依赖的类不管多么复杂,都尽量将逻辑封装在类的内部。对外除了提供的public方法,不对外泄露任何信息迪米特法则还有个更简单的定义:只与直接的朋友通信
直接的朋友
:每个对象都会与其他对象有耦合关系,只要两个对象之间有耦合关系,我们就说这两个对象之间是朋友关系。耦合的方式很多,依赖,关联,组合,聚合等。其中,我们称出现成员变量,方法参数,方法返回值中的类为直接的朋友,而出现在局部变量中的类不是直接的朋友。也就是说,陌生的类最好不要以局部变量的形式出现在类的内部。
2. 代码
import java.util.ArrayList;
import java.util.List;
// 客户端
public class Demeter1 {
public static void main(String[] args) {
SchoolManager schoolManager = new SchoolManager();
schoolManager.printAllEmployee(new CollegeManager());
}
}
// 学校总部员工
class Employee {
private String id;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
// 学院员工
class CollegeEmployee {
private String id;
public void setId(String id) {
this.id = id;
}
public String getId() {
return 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;
}
}
// 学校管理类
// 分析 SchoolManager 类的之间朋友类有哪些:Employee、CollegeManager
// CollegeEmployee 不是之间朋友,违反了迪米特法则
class SchoolManager {
// 返回学校总部员工
public List<Employee> getAllEmployee() {
List<Employee> list = new ArrayList<Employee>();
for (int i = 0; i < 5; i++) {
Employee emp = new Employee();
emp.setId("学校总部员工id= " + i);
list.add(emp);
}
return list;
}
// 输出学校总部和学院员工信息方法
void printAllEmployee(CollegeManager sub) {
// 分析问题
// 1. 这里 CollegeEmployee 不是 SchoolManager 的之间朋友
// 2. CollegeEmployee 是以局部变量的形式出现的
// 3. 违反了迪米特法则
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());
}
}
}
改进
import java.util.ArrayList;
import java.util.List;
// 客户端
public class Demeter1 {
public static void main(String[] args) {
SchoolManager schoolManager = new SchoolManager();
schoolManager.printAllEmployee(new CollegeManager());
}
}
// 学校总部员工
class Employee {
private String id;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
// 学院员工
class CollegeEmployee {
private String id;
public void setId(String id) {
this.id = id;
}
public String getId() {
return 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 = this.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 < 5; 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());
}
}
}
3. 小结
-
迪米特法则的核心是降低类之间的
耦合
-
但是注意:由于每个类都减少了不必要的依赖,因此迪米特法则只是要求降低类间(对象间)耦合关系,并
不是要求
完全没有依赖关系
七、合成复用原则
1. 基本介绍
原则是尽量使用合成/聚合的方式,而不是使用继承