Design patterns are reusable solutions to common problems in software design. They represent best practices that can be applied to various situations in software development, particularly in object-oriented programming like Java.
public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
import java.util.ArrayList; import java.util.List; interface Observer { void update(String message); } class Subject { private List observers = new ArrayList(); public void addObserver(Observer observer) { observers.add(observer); } public void notifyObservers(String message) { for (Observer observer : observers) { observer.update(message); } } }
class Product { private String part1; private String part2; public void setPart1(String part1) { this.part1 = part1; } public void setPart2(String part2) { this.part2 = part2; } } class Builder { private Product product = new Product(); public Builder buildPart1(String part1) { product.setPart1(part1); return this; } public Builder buildPart2(String part2) { product.setPart2(part2); return this; } public Product build() { return product; } }
interface Shape { void draw(); } class Circle implements Shape { public void draw() { System.out.println("Drawing a Circle"); } } class Rectangle implements Shape { public void draw() { System.out.println("Drawing a Rectangle"); } } class ShapeFactory { public Shape getShape(String shapeType) { if (shapeType == null) return null; if (shapeType.equalsIgnoreCase("CIRCLE")) return new Circle(); if (shapeType.equalsIgnoreCase("RECTANGLE")) return new Rectangle(); return null; } }
The "Gang of Four" refers to the authors of the influential book titled "Design Patterns: Elements of Reusable Object-Oriented Software." The authors—Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides—introduced 23 classic design patterns that have become a foundation for software engineering.
Design patterns are essential tools in Java programming that help developers create robust and maintainable systems. Understanding their uses, advantages, and disadvantages is crucial for effective software design. The Gang of Four's contributions provide a solid foundation for applying these patterns effectively.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3