7

设计模式基础入门_大鱼的技术博客_51CTO博客

 1 year ago
source link: https://blog.51cto.com/learningfish/5371261
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

设计模式基础

设计模式简介

软件工程中,设计模式(design pattern)是对软件中普遍存在(反复出现)的各种问题,所提出的解决方案,是由Erich Gamma、Richard Helm、Ralph Johnson 和 John Vlissides 四人在1990年代冲工程建筑领域引入计算机科学的

设计模式解决问题

  • 客户提出新功能 【使用设计模式软件具有更好的扩展性】
  • 原公司程序员离职,项目接手【使用设计模式的代码更具有可维护性(可读性和规范性)】

面向对象(oo) --> 功能模块 【设计模式 + 算法】 --> 框架【多种设计模式】–> 架构【服务器集群】

设计模式的目的

编写软件的过程中,程序面临着来自耦合性,内聚性以及可维护性,可扩展性,重用性等多方面的挑战,设计模式用为让程序(软件)具有更好:

  • 代码重用性
  • 使程序呈现高内聚、低耦合的特性

设计模式七大原则

  • 单一职责原则 (Single Responsibility Principle)
  • 开放-关闭原则 (Open-Closed Principle)
  • 里氏替换原则 (Liskov Substitution Principle)
  • 依赖倒转原则 (Dependence Inversion Principle)
  • 接口隔离原则 (Interface Segregation Principle)
  • 迪米特法则(Law Of Demeter)
  • 组合/聚合复用原则 (Composite/Aggregate Reuse Principle)

详情解析→  设计模式概念和七大原则

设计原则核心思想

  • 找出应用中可能需要变化之处,把它们独立出来,不要和哪些不需要变化的代码混在一起
  • 针对接口编程,而不是针对实现编程
  • 为了交互对象之间的松耦合设计而努力

UML类图

UML基本介绍

  • UML(Unified modeling language) (统一建模语言), 是一种用于软件系统分析和设计的语言工具,它用于帮助软件开发人员进行思考和记录思路的结果
  • UML本身是一套符号的规定,就像数学符号和化学符号一样,这些符号用于描述软件模型中的各个元素和他们之间的关系,比如类、接口、实现、泛化、依赖、组合、聚合等,如下图:
设计模式基础入门_java

依赖-dependency

public class PersonServiceBean {
    private PersonDao personDao;

    public void save(Person person) {

    }

    public IDCard getIDCard(Integer personId) {
        return null;
    }

    public void modify() {
        Department department = new Department();
    }
}
设计模式基础入门_java_02

泛化(继承)-Gerneralization

public abstract class DaoSupport {
    public void save(Object entity) {
    }

    public void delete(Object id) {
    }
}
设计模式基础入门_创建型模式_03
public class PersonServiceBean extends DaoSupport{
}

实现-Realization

public interface PersonService {
    public void delete(Integer id);
}
public class PersonServiceBean implements PersonService{
    @Override
    public void delete(Integer id) {

    }
}
设计模式基础入门_java_04

聚合-Aggregation

整体和部分可分割

public class Computer {

    private Mouse mouse;
    private Monitor monitor;

    public void setMouse(Mouse mouse) {
        this.mouse = mouse;
    }

    public void setMonitor(Monitor monitor) {
        this.monitor = monitor;
    }
}
设计模式基础入门_设计模式_05

组合-Composite

整体和部分不可分割

public class Computer {
    private Mouse mouse = new Mouse();
    private Monitor monitor = new Monitor();
}
设计模式基础入门_java_06

设计模式类型

设计模式可以分为三种类型
● 创建型模式:对象实例化的模式,创建型模式用于解耦对象的实例化过程。
● 结构型模式:把类或对象结合在一起形成一个更大的结构。
● 行为型模式:类和对象如何交互,及划分责任和算法。

类型 所包含设计模式
创建型模式 单例模式、抽象工厂模式、原型模式、建造者模式、工厂模式
结构型模式 适配器模式、桥接模式、装饰模式、组合模式、外观模式、享元模式、代理模式
行为型模式 模板方法模式、命令模式、访问者模式、迭代器模式、观察者模式、中介者模式、备忘录模式、解释器模式、状态模式、职责模式

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK