01 设计模式原则
设计模式
设计模式是对软件设计中普遍存在(反复出现)的各种问题,所提出的解决方案
设计模式分为三种类型,共 23 种
-
创建型模式:单例模式、抽象工厂模式、原型模式、建造者模式、工厂模式。
-
结构型模式:适配器模式、桥接模式、装饰模式、组合模式、外观模式、享元模式、代理模式。
-
行为型模式:模版方法模式、命令模式、访问者模式、迭代器模式、观察者模式、中介者模式、备忘录模式、解释器模式(Interpreter 模式)、状态模式、策略模式、职责链模式(责任链模式)。
注意:不同的书籍上对分类和名称略有差别
一、 设计模式的目的:
设计模式是为了让程序(软件),具有更好
- 代码重用性(即:相同功能的代码,不用多次编写)
- 可读性(即:编程规范性,便于其他程序员的阅读和理解)
- 可扩展性(即:当需要增加新的功能时,非常的方便)
- 可靠性(即:当我们在增加新的功能后,对原来的功能没有影响)
- 使程序程序高内聚,低耦合的特性
二、设计模式的七大原则
- 单一职责原则
- 接口隔离原则
- 依赖倒转原则
- 里氏替换原则
- 开闭原则ocp
- 迪米特法则
- 合成复用原则
2.1 单一职责原则
基本介绍:
对类来说的,即一个类应该只负责一项职责,如类A负责两个不同职责:职责1,职责2.当职责1需求变更而改变A时,可能造成职责2执行错误,所以需要将类A的粒度分解为A1,A2
public class SingleResponsibility1 {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
vehicle.run("摩托车");
vehicle.run("飞机");
}
}
class Vehicle{
//1.在这个方法里 违反了单一职责原则
//2.解决方案:根据交通工具运行方法不同,分解成不同类即可
public void run(String vehicle){
System.out.println(vehicle + "在公路上运行");
}
}
public class SingleResponsibility2 {
public static void main(String[] args) {
RoadVehicle roadVehicle = new RoadVehicle();
roadVehicle.run("车");
AirVehicle airVehicle = new AirVehicle();
airVehicle.run("飞机");
WaterVehicle waterVehicle = new WaterVehicle();
waterVehicle.run("船");
}
}
//方案2的分析
//1.遵守单一职责原则
//2.但是这样改动很大,将类分解,同时修改客户端
//2.改进:直接修改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+"在水上运行");
}
}
public class SingleResponsibility3 {
public static void main(String[] args) {
Vehicle2 vehicle2 = new Vehicle2();
vehicle2.run("车");
vehicle2.runAir("飞机");
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 + "在水上运行");
}
}
单一职责注意事项和细节
- 降低类的复杂度,一个类只负责一项职责
- 提高类的可读性,可维护性
- 降低变更引起的风险
- 通常情况下,我们应当遵守单一职责原则,只有逻辑足够简单,才可以在代码违反单一职责原则;只有类中方法数量足够少,可以在方法级别保持单一职责原则
2.2 接口隔离原则
基本介绍:
客户端不应该依赖它不需要的接口,即一个类对另一类的依赖应该建立在最小的接口上
类A通过Interface1 依赖类B,类C通过Interface1 依赖类D,如果接口Interface1 对于类A不是最小接口,那么类B和类D必须去实现它们不需要
的方法
public class Segregation1 {
}
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("B实现了operation5");
}
}
class A{//A类 通过接口Interface1 依赖(使用)B类,但是只会用到1,2,3方法
public void depend1(Interface1 i){
i.operation1();
}
public void depend2(Interface1 i){
i.operation2();
}
public void depend3(Interface1 i){
i.operation3();
}
}
class C{//C类 通过接口Interface1 依赖(使用)D类,但是只会用到1,4,5方法
public void depend1(Interface1 i){
i.operation1();
}
public void depend4(Interface1 i){
i.operation4();
}
public void depend5(Interface1 i){
i.operation5();
}
}
按隔离原则应当这样处理:
将Interface1 拆分成几个接口,类A和类C分别与它们需要的接口建立依赖关系,也就是隔离原则
根据实际情况,拆分成3个接口
public class Segregation1 {
public static void main(String[] args) {
A a = new A();
a.depend1(new B());//A类通过接口去依赖B类
a.depend2(new B());
C c = new C();
c.depend1(new D());
}
}
//接口1
interface Interface1{
void operation1();
}
//接口2
interface Interface2{
void operation2();
void operation3();
}
//接口3
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("B实现了operation5");
}
}
class A{//A类 通过接口Interface1 Interface2依赖(使用)B类,但是只会用到1,2,3方法
public void depend1(Interface1 i){
i.operation1();
}
public void depend2(Interface2 i){
i.operation2();
}
public void depend3(Interface2 i){
i.operation3();
}
}
class C{//C类 通过接口Interface1 依赖(使用)D类,但是只会用到1,4,5方法
public void depend1(Interface1 i){
i.operation1();
}
public void depend4(Interface3 i){
i.operation4();
}
public void depend5(Interface3 i){
i.operation5();
}
}
2.3 依赖倒转原则
- 高层模块不应该依赖底层模块,二者都应该依赖其抽象
- 抽象不应该依赖细节,细节应该依赖抽象
- 依赖倒转(倒置)的中心思想是面向接口抽象
- 依赖倒转原则是基于这样的设计理念:相对于细节的多变性,抽象的东西要稳定的多,以抽象为基础搭建的架构比以细节为基础的架构要稳定的多。在java中,抽象指的是接口或抽象类,细节就是具体的实现类
- 使用接口或抽象类的目的是定好规范,而不涉及任何具体的操作,把展现细节的任务交给他们的实现类去完成
创建一个Person类用来接收信息
public class DependencyInversion {
public static void main(String[] args) {
Person person = new Person();
person.receive(new Email());
}
}
class Email{
public String getInfo(){
return "电子邮件信息:hello";
}
}
//Person接收消息的功能
//方式1 分析
//1.简单 比较容易想到
//2.如果我们获取的对象是微信,短信等等,则新增类,同时Person也需要增加相应的方法
//3.引入一个抽象的接口 IReceiver 表示接收者,这样Person类与接口IReceiver发生依赖
//因为 Email ,weixin 等等属于接受的范围,各自实现IReceiver 接口就ok,这样我们就符合依赖倒转原则
class Person{
public void receive(Email email){
System.out.println(email.getInfo());
}
}
2.3.1 依赖关系传递的三种方式
- 接口传递
- 构造方法传递
- setter方式传递
//方式1:通过接口传递实现依赖
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();
}
}
//方式2 通过构造方法依赖传递
interface IOpenAndClose{
public void open();//抽象方式,接受接口
}
interface ITV{
public void play();
}
class ChangHong implements ITV{
@Override
public void play() {
System.out.println("打开电视");
}
}
class OpenAndClose implements IOpenAndClose{
public ITV tv;
public OpenAndClose(ITV tv){
this.tv = tv;
}
@Override
public void open() {
tv.play();
}
}
//方式3 通过setter方法传递
interface IOpenAndClose{
public void open();//抽象方式,接受接口
public void setTv();
}
interface ITV{
public void play();
}
class ChangHong implements ITV{
@Override
public void play() {
System.out.println("打开电视");
}
}
class OpenAndClose implements IOpenAndClose{
private ITV tv;
@Override
public void setTv() {
this.tv = tv;
}
@Override
public void open() {
tv.play();
}
}
依赖倒转原则的注意事项和细节
- 低层模块尽量都要有抽象类或接口,或者两者都有,程序稳定性更好
- 变量的声明类型尽量是抽象类或接口,这样我们的变量引用或实际对象间,就存在一个缓冲层,利于程序扩展和优化
- 继承时遵循里氏替换原则
2.4 里氏替换原则
- 所有引用基类的地方必须能透明地使用其子类地对象
- 在使用继承时,遵循里氏替换原则,在子类中尽量不要重写父类地方法
- 里氏替换原则告诉我们,继承实际上让两个耦合性增强了,在适当地情况下,可以通过聚合,组合,依赖来解决问题
public class Liskov {
public static void main(String[] args) {
B b = new B();
//B类不在继承A ,因此调用不会再func1是求减 法
}
}
//创建一个基础基类
class Base{
//更加基础地方法和成员
public int func1(int num1,int num2){
return num1 - num2;
}
}
class A extends Base{
public int func1(int a,int b){
return a-b;
}
}
class B extends Base{
private A a = new A();
//B类使用A类地方法,使用组合关系
public int func1(int a,int b){
return a+b;
}
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);
}
}
2.5 开闭原则
- 一个类、模块和函数应该对扩展开发(对提供方),对修改关闭(对使用方)。用抽象构建框架,用实现扩展细节
- 当软件需要变化时,尽量通过扩展软件实体地行为来实现变化,而不是通过修改已有代码来实现变化
- 编程中遵循其他原则,以及使用设计模式地目的就是遵循开闭原则
public class Ocp {
public static void main(String[] args) {
Graph graph = new Graph();
graph.drawShape(new Rectangle());
}
}
class Graph{
public void drawShape(Shape s){
s.draw();
}
}
abstract class Shape{
int m_type;
public abstract void draw();
}
class Rectangle extends Shape{
Rectangle(){
m_type = 2;
}
@Override
public void draw() {
System.out.println("绘制矩形");
}
}
2.6 迪米特法则
-
一个对象应该对其他对象保持最少的了解
-
类与类关系越密切,耦合度越大
-
迪米特法则又叫最少知道原则,即一个类对自己依赖的类知道的越少越好。对外除了提供的公共方法,不对外泄露任何信息
-
迪米特法则还有个更简单的定义:只与直接的朋友通信
-
直接的朋友:每个对象都会与其他对象有耦合关系,只要两个对象之间有耦合关系,我们就说这两个对象之间是朋友关系。(耦合的方式很多,依赖,关联,组合,聚合等。其中,我们称出现成员变量,方法参数,方法返回值中的类为直接的朋友,而出现在局部变量中的类不是直接的朋友。也就是说,陌生的类最好不要以局部变量的形式出现在类的内部。
public class Demeter1 {
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<>();
for (int i = 0; i < 10; i++) {
CollegeEmployee emp = new CollegeEmployee();
emp.setId("id=" +i);
list.add(emp);
}
return list;
}
}
class SchoolManager{
//返回学校总部的员工
List<CollegeEmployee> list = new ArrayList<>();
public List<Employee> getAllEmployee(){
List<Employee> list = new ArrayList<>();
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是以局部变量方式出现在 SchoolManager
//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());
}
}
}
public class Demeter1 {
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<>();
for (int i = 0; i < 10; i++) {
CollegeEmployee emp = new CollegeEmployee();
emp.setId("id=" +i);
list.add(emp);
}
return list;
}
//该方法完成输出学校员工信息
void printAllEmployee(){
//获取到学院员工
List<CollegeEmployee> list1 = getAllEmployee();
System.out.println("- --学院员工-----.-----");
for (CollegeEmployee e : list1) {
System.out.println(e.getId());
}
}
}
class SchoolManager{
//返回学校总部的员工
List<CollegeEmployee> list = new ArrayList<>();
public List<Employee> getAllEmployee(){
List<Employee> list = new ArrayList<>();
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.printAllEmployee();
//获取到学院员工
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());
}
}
}
迪米特法则注意事项和细节
- 迪米特法则的核心是降低类之间的耦合
- 注意:由于每个类都减少了不必要的依赖,因此迪米特法则只是要求降低类间(对象间)耦合关系,并不是要求完全没有依赖关系
2.7 合成复用原则
尽量使用合成/聚成的方式,而不是使用继承
设计原则核心思想:
- 找出应用中可能需要变化之处,把它们独立出来,不要和那些不需要变化的代码混在一起
- 针对接口编程,而不是针对实现编程
- 为了交互对象之间的松耦合设计而努力
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)