design模式Basicstutorial

Masterdesign模式 core concepts, classification and principles

查看tutoriallist

design模式Basicstutorial

design模式 is Software Developmentin针 for specificissues common, reusable solution. They are best practices summarized from experience, helping developers design more flexible, maintainable, and scalable software systems. 本tutorial将带你Understanddesign模式 basicconcepts, classification and coreprinciples.

what is design模式?

Design patterns are a set of repeatedly used, classified and summarized code design experiences that solve specific problems in specific environments. Design patterns are not ready-made code, but a way of thinking and method to solve problems. It describes under what circumstances how to construct code structure to solve specific design problems.

Value of Design Patterns

The value of design patterns lies in:

  • improving code reusability and maintainability
  • promoting communication and understanding among team members
  • providing verified solutions, reducing trial and error costs
  • helping developers design more flexible and scalable systems
  • serving asLearning面向objectdesignprinciples practical examples

Design Patterns Classification

Design patterns are usually divided into three main categories: creation型模式, structure型模式 and behavior型模式. 每class模式都 has 其specific 关注点 and 解决 issuesclass型.

1. Creational Patterns

Creational patterns focus on the object creation process, providing a way to hide creation logic when creating objects, making code more flexible and maintainable. Common creational patterns include:

  • singleton pattern (Singleton) : 确保一个class只 has 一个instance, 并providing一个全局访问点
  • factory pattern (Factory Method) : 定义一个creationobject interface, 但让子class决定要instance化 class is 哪一个
  • abstractionfactory pattern (Abstract Factory) : providing一个creation一系列相关 or 相互依赖object interface, 而无需指定它们具体 class
  • Builder Pattern : 将一个 complex object 构建 and 它 表示分离, 使得同样 构建过程可以creation不同 表示
  • Prototype Pattern : 用原型instance指定creationobject 种class, 并且through拷贝这个原型来creation new object

2. Structural Patterns

structure型模式关注classes and objects 组合, throughinheritance and 组合来implementation new functions, 使得system更加flexible and 可scale. Common structural patterns include:

  • adapter pattern (Adapter) : 将一个class interface转换成客户希望 另一个interface
  • decorator pattern (Decorator) : 动态地给一个object添加一些额 out 职责
  • Proxy Pattern : for otherobjectproviding一种proxy以控制 for 这个object 访问
  • Composite Pattern : 将object组合成tree形structure以表示"部分-整体" 层次structure
  • Facade Pattern : for 子systemin 一组interfaceproviding一个一致 界面
  • Bridge Pattern : 将abstraction部分 and 它 implementation部分分离, 使它们都可以独立地变化
  • Flyweight Pattern : 运用共享techniques has 效地support big 量细粒度 object

3. Behavioral Patterns

Behavioral patterns focus on communication and responsibility allocation between objects, defining interaction methods between objects, making systems more flexible and maintainable. Common behavioral patterns include:

  • observer pattern (Observer) : 定义object间 一种一 for many 依赖relationships, 当一个object status发生变化时, 所 has 依赖于它 object都得 to notification并被自动update
  • strategy pattern (Strategy) : 定义一系列 algorithms, 把它们一个个encapsulation起来, 并且使它们可相互replace
  • 模板method模式 (Template Method) : 定义一个operationin algorithms 骨架, 而将一些步骤latency to 子classin
  • Command Pattern : 将一个requestencapsulation for 一个object, from 而使你可用不同 request for 客户forparameter化
  • Iterator Pattern : providing一种method顺序访问一个aggregateobjectin各个元素, 而又不暴露该object in 部表示
  • State Pattern : 允许一个object in 其 in 部status改变时改变它 behavior
  • Visitor Pattern : 表示一个作用于某objectstructurein 各元素 operation
  • Mediator Pattern : 用一个in介object来encapsulation一系列 object交互
  • Memento Pattern : in 不破 bad encapsulation性 before 提 under , 捕获一个object in 部status, 并 in 该object之 out 保存这个status
  • Interpreter Pattern : 给定一个language, 定义它 文法 一种表示, 并定义一个解释器
  • Chain of Responsibility Pattern : for 解除request 发送者 and 接收者之间耦合, 而使 many 个object都 has 机会processing这个request

designprinciples

design模式基于一些core 面向objectdesignprinciples, 这些principles is design模式 Basics. Master这些principles for 于understanding and applicationdesign模式至关 important .

1. Single Responsibility Principle

A class should have only one reason to change, meaning a class should be responsible for only one responsibility.

// 违反单一职责principles 例子 class UserService { // 负责usermanagement public void addUser(String username, String password) {} // 负责log记录 public void logUserActivity(String userId, String activity) {} // 负责data持久化 public void saveUserToDatabase(User user) {} } // 遵循单一职责principles 例子 class UserService { public void addUser(String username, String password) {} } class Logger { public void logUserActivity(String userId, String activity) {} } class UserRepository { public void saveUserToDatabase(User user) {} }

2. Open-Closed Principle

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

// 违反开放-封闭principles 例子 class ShapeCalculator { public double calculateArea(Object shape) { if (shape instanceof Rectangle) { Rectangle rectangle = (Rectangle) shape; return rectangle.getWidth() * rectangle.getHeight(); } else if (shape instanceof Circle) { Circle circle = (Circle) shape; return Math.PI * circle.getRadius() * circle.getRadius(); } return 0; } } // 遵循开放-封闭principles 例子 interface Shape { double calculateArea(); } class Rectangle implements Shape { private double width; private double height; @Override public double calculateArea() { return width * height; } } class Circle implements Shape { private double radius; @Override public double calculateArea() { return Math.PI * radius * radius; } } class ShapeCalculator { public double calculateArea(Shape shape) { return shape.calculateArea(); } }

3. Liskov Substitution Principle

子class应该able toreplace掉它们 父class, 而不影响程序 正确性.

4. interface隔离principles (Interface Segregation Principle)

客户端不应该依赖它不using interface, 应该将庞 big interface拆分 for 更 small , 更具体 interface.

5. Dependency Inversion Principle

High-level modules should not depend on low-level modules; both should depend on abstractions; abstractions should not depend on details, details should depend on abstractions.

// 违反依赖倒置principles 例子 class EmailService { public void sendEmail(String message) { System.out.println("Sending email: " + message); } } class NotificationService { private EmailService emailService; public NotificationService() { this.emailService = new EmailService(); } public void notifyUser(String message) { emailService.sendEmail(message); } } // 遵循依赖倒置principles 例子 interface MessageService { void sendMessage(String message); } class EmailService implements MessageService { @Override public void sendMessage(String message) { System.out.println("Sending email: " + message); } } class SMSService implements MessageService { @Override public void sendMessage(String message) { System.out.println("Sending SMS: " + message); } } class NotificationService { private MessageService messageService; public NotificationService(MessageService messageService) { this.messageService = messageService; } public void notifyUser(String message) { messageService.sendMessage(message); } }

Design Pattern Usage Guidelines

When using design patterns, note the following:

  • Don't overuse design patterns; only use them when truly needed
  • understandingdesign模式 本质, 而不仅仅 is implementation细节
  • 根据具体circumstancesflexibleapplicationdesign模式, 不要生搬硬套
  • Combine design principles to understand and use design patterns
  • Standardize design pattern usage within the team

实践case: design模式 application场景

case: 电商system design

fake设你正 in design一个电商system, 需要考虑以 under functions:

  • usermanagement: register, login, 个人informationmanagement
  • 商品management: 商品classification, 商品详情, library存management
  • 订单management: creation订单, 订单statusmanagement, 支付
  • 物流management: 配送, 跟踪

in 这个systemin, 你可以application以 under design模式:

  • singleton pattern: 用于log记录, configurationmanagementetc.全局唯一 component
  • factory pattern: 用于creation不同class型 商品, 订单etc.object
  • strategy pattern: 用于不同 支付方式, 配送方式etc.
  • observer pattern: 用于订单status变化时notification相关component
  • decorator pattern: 用于商品促销, 折扣etc.动态添加 functions

互动练习

练习1: Design Pattern Classification

请将以 under design模式按照creation型, structure型 and behavior型forclassification:

  • singleton pattern
  • adapter pattern
  • observer pattern
  • factory pattern
  • decorator pattern
  • strategy pattern

练习2: designprinciplesapplication

请analysis以 under code违反了哪些designprinciples, 并给出improvementsolutions:

class OrderProcessor { public void processOrder(Order order) { // processing订单 validateOrder(order); calculatePrice(order); saveOrder(order); sendEmailNotification(order); } private void validateOrder(Order order) { // verification订单 } private void calculatePrice(Order order) { // 计算价格 } private void saveOrder(Order order) { // 保存订单 to datalibrary } private void sendEmailNotification(Order order) { // 发送emailnotification } }