首页 > 编程语言 >java常见设计模式

java常见设计模式

时间:2024-09-15 17:12:46浏览次数:1  
标签:java String void 常见 class Shape new 设计模式 public

 

 Java 设计模式是经过验证的、用于解决常见软件设计问题的标准化解决方案。设计模式可以分为三大类:创建型模式结构型模式行为型模式

以下列出一些常见的设计模式,并附上每个模式的简单说明和 Java 示例。

 

1. 单例模式(Singleton Pattern) - 创建型模式

目的:

确保某个类在应用中只有一个实例,并提供一个全局访问点 。

示例:

public class Singleton {
    private static Singleton instance;

    private Singleton() {
        // 私有构造方法,防止外部实例化
    }

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

场景:

适用于需要全局共享的资源或数据,如配置文件读取类、数据库连接池等。


2. 工厂模式(Factory Pattern) - 创建型模式

目的:

定义一个用于创建对象的接口,但让子类决定要实例化的类是哪一个。工厂方法让类的实例化延迟到子类。

示例:

public interface Shape {
    void draw();
}

public class Circle implements Shape {
    public void draw() {
        System.out.println("Drawing a Circle");
    }
}

public class Square implements Shape {
    public void draw() {
        System.out.println("Drawing a Square");
    }
}

public class ShapeFactory {
    public Shape getShape(String shapeType) {
        if (shapeType.equalsIgnoreCase("CIRCLE")) {
            return new Circle();
        } else if (shapeType.equalsIgnoreCase("SQUARE")) {
            return new Square();
        }
        return null;
    }
}

// 使用工厂模式
ShapeFactory shapeFactory = new ShapeFactory();
Shape shape1 = shapeFactory.getShape("CIRCLE");
shape1.draw();  // 输出:Drawing a Circle

场景:

适用于在创建对象时不想暴露实例化逻辑的场合,或当具体类依赖于某些条件时。


3. 抽象工厂模式(Abstract Factory Pattern) - 创建型模式

目的:

提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们的具体类。

示例:

public interface Button {
    void paint();
}

public class WindowsButton implements Button {
    public void paint() {
        System.out.println("Rendering a button in Windows style");
    }
}

public class MacOSButton implements Button {
    public void paint() {
        System.out.println("Rendering a button in MacOS style");
    }
}

public interface GUIFactory {
    Button createButton();
}

public class WindowsFactory implements GUIFactory {
    public Button createButton() {
        return new WindowsButton();
    }
}

public class MacOSFactory implements GUIFactory {
    public Button createButton() {
        return new MacOSButton();
    }
}

// 客户端代码
public class Application {
    private Button button;
    
    public Application(GUIFactory factory) {
        button = factory.createButton();
    }
    
    public void paint() {
        button.paint();
    }
}

场景:

当系统需要与多个产品系列一起工作,但又希望能独立地创建具体产品时适用,如跨平台 UI 开发。


4. 建造者模式(Builder Pattern) - 创建型模式

目的:

将一个复杂对象的构建与其表示相分离,使得同样的构建过程可以创建不同的表示。

示例:

public class Meal {
    private String drink;
    private String mainCourse;
    private String side;

    // 生成器内部类
    public static class Builder {
        private String drink;
        private String mainCourse;
        private String side;

        public Builder drink(String drink) {
            this.drink = drink;
            return this;
        }

        public Builder mainCourse(String mainCourse) {
            this.mainCourse = mainCourse;
            return this;
        }

        public Builder side(String side) {
            this.side = side;
            return this;
        }

        public Meal build() {
            Meal meal = new Meal();
            meal.drink = this.drink;
            meal.mainCourse = this.mainCourse;
            meal.side = this.side;
            return meal;
        }
    }

    @Override
    public String toString() {
        return "Meal [drink=" + drink + ", mainCourse=" + mainCourse + ", side=" + side + "]";
    }
}

// 使用建造者模式
Meal meal = new Meal.Builder().drink("Cola").mainCourse("Burger").side("Fries").build();
System.out.println(meal);  // 输出:Meal [drink=Cola, mainCourse=Burger, side=Fries]

场景:

适用于构建过程复杂且需要多步骤构建的对象,如订单、计算机配置等。


5. 适配器模式(Adapter Pattern) - 结构型模式

目的:

将一个类的接口转换成客户希望的另外一个接口,使得原本接口不兼容的类可以一起工作。

示例:

public interface MediaPlayer {
    void play(String audioType, String fileName);
}

public class MP3Player implements MediaPlayer {
    public void play(String audioType, String fileName) {
        if (audioType.equalsIgnoreCase("mp3")) {
            System.out.println("Playing mp3 file: " + fileName);
        }
    }
}

public interface AdvancedMediaPlayer {
    void playVlc(String fileName);
    void playMp4(String fileName);
}

public class Mp4Player implements AdvancedMediaPlayer {
    public void playVlc(String fileName) {}
    public void playMp4(String fileName) {
        System.out.println("Playing mp4 file: " + fileName);
    }
}

public class MediaAdapter implements MediaPlayer {
    AdvancedMediaPlayer advancedMediaPlayer;

    public MediaAdapter(String audioType) {
        if (audioType.equalsIgnoreCase("mp4")) {
            advancedMediaPlayer = new Mp4Player();
        }
    }

    public void play(String audioType, String fileName) {
        if (audioType.equalsIgnoreCase("mp4")) {
            advancedMediaPlayer.playMp4(fileName);
        }
    }
}

// 使用适配器模式
MediaPlayer player = new MediaAdapter("mp4");
player.play("mp4", "movie.mp4");  // 输出:Playing mp4 file: movie.mp4

场景:

适用于现有类的接口和需要使用的类不兼容时,如将老旧系统适配到新系统。


6. 装饰器模式(Decorator Pattern) - 结构型模式

目的:

动态地给对象添加一些额外的职责,装饰器提供了比继承更灵活的功能扩展方式。

示例:

public interface Shape {
    void draw();
}

public class Circle implements Shape {
    public void draw() {
        System.out.println("Drawing a Circle");
    }
}

public abstract class ShapeDecorator implements Shape {
    protected Shape decoratedShape;

    public ShapeDecorator(Shape decoratedShape) {
        this.decoratedShape = decoratedShape;
    }

    public void draw() {
        decoratedShape.draw();
    }
}

public class RedShapeDecorator extends ShapeDecorator {
    public RedShapeDecorator(Shape decoratedShape) {
        super(decoratedShape);
    }

    @Override
    public void draw() {
        decoratedShape.draw();
        setRedBorder(decoratedShape);
    }

    private void setRedBorder(Shape decoratedShape) {
        System.out.println("Border Color: Red");
    }
}

// 使用装饰器模式
Shape circle = new Circle();
Shape redCircle = new RedShapeDecorator(circle);
redCircle.draw();  // 输出:Drawing a Circle, Border Color: Red

场景:

适用于需要动态扩展对象功能的场合,如在 GUI 系统中为控件添加额外功能。


7. 观察者模式(Observer Pattern) - 行为型模式

目的:

定义对象间的一对多依赖,当一个对象状态发生变化时,其所有依赖者都会自动收到通知并更新。

示例:

import java.util.ArrayList;
import java.util.List;

public class Subject {
    private List<Observer> observers = new ArrayList<>();
    private int state;

    public void attach(Observer observer) {
        observers.add(observer);
    }

    public void setState(int state) {
        this.state = state;
        notifyAllObservers();
    }

    public void notifyAllObservers() {
        for (Observer observer : observers) {
            observer.update();
        }
    }
}

public abstract class Observer {
    protected Subject subject;
    public abstract void update();
}

public class ConcreteObserver extends Observer {
    public ConcreteObserver(Subject subject) {
        this.subject = subject;
        this.subject.attach(this);
    }

    public void update() {
        System.out.println("State changed to: " + subject.getState());
    }
}

// 使用观察者模式
Subject subject = new Subject();
new ConcreteObserver(subject);
subject.setState(10);  // 输出:State changed to: 10

场景:

适用于需要自动通知多个对象的场合,如事件驱动系统、实时数据推送。


这些是 Java 中常见的设计模式,它们有助于提高代码的可维护性、可扩展性和可读性。根据具体的业务需求和场景选择合适的设计模式,是编写健壮代码的重要一环。

标签:java,String,void,常见,class,Shape,new,设计模式,public
From: https://www.cnblogs.com/Oct16/p/18414590

相关文章

  • 如何在Java中实现高效的可解释AI算法
    如何在Java中实现高效的可解释AI算法大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!可解释AI(ExplainableAI,XAI)旨在提供机器学习模型的透明度,使其决策过程和结果对用户可理解。随着AI应用的广泛普及,确保模型的可解释性变得尤为重要。本文将介绍......
  • 【开源免费】基于SpringBoot+Vue.JS蜗牛兼职平台(JAVA毕业设计)
    本文项目编号T034,文末自助获取源码\color{red}{T034,文末自助获取源码}......
  • 【开源免费】基于SpringBoot+Vue.JS校园美食分享平台(JAVA毕业设计)
    本文项目编号T033,文末自助获取源码\color{red}{T033,文末自助获取源码}......
  • JavaScript中if嵌套 assert
    摘要: 本文主要探讨在JavaScript中if嵌套的使用场景以及assert语句在代码调试与逻辑验证方面的作用。通过分析if嵌套的结构与常见用法,结合assert语句在确保程序正确性上的优势,阐述它们在JavaScript编程中的重要性与高效运用方式。一、引言在JavaScript开发中,控制结构......
  • JAVA基础之六-Stream(流)简介
    我在别的篇幅已经说过:流这个东西偶尔可以用用,但我个人最大的学习动力(目前)仅仅是为了有助于阅读spring越发繁复的源码 本文主要介绍Stream接口(包括主要的方法)和相关的几个主要接口:Predicate、Consumer、Supplier还有Collector接口,Collectors工具类。由于网上已经有太多的文章......
  • Java 中图片转换为 Base64
    importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importjava.util.Base64;publicclassImageToBase64Converter{publicstaticvoidmain(String[]args){//指定要转换的图片路径StringimagePath="path......
  • 【JAVA开源】基于Vue和SpringBoot的房产销售系统
    本文项目编号T028,文末自助获取源码\color{red}{T028,文末自助获取源码}......
  • 【JAVA开源】基于Vue和SpringBoot的在线视频教育平台
    本文项目编号T027,文末自助获取源码\color{red}{T027,文末自助获取源码}......
  • Java抽象类和接口的学习了解
    目录1.抽象类1.1抽象类概念1.2例子1.3 抽象类语法1.被abstract修饰的类--抽象类2.抽象类中被abstract修饰的方法--抽象方法,该方法不用给出具体的实现体3.当一个类中含有抽象方法时,该类必须要abstract修饰4.抽象类也是类,内部可以包含普通方法和属性,甚至构造方法......
  • [1018]基于JAVA的外贸服装智慧管理系统的设计与实现
    毕业设计(论文)开题报告表姓名学院专业班级题目基于JAVA的外贸服装智慧管理系统的设计与实现指导老师(一)选题的背景和意义背景部分:在全球经济一体化的大背景下,我国对外贸易行业持续繁荣发展,尤其是服装外贸领域,由于其更新迭代快、市场需求多样以及交易环节复杂等特点,对信......