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