在软件开发的旅程中,架构设计是确保项目成功的关键因素之一。设计模式是解决常见问题的经验总结,它们可以帮助开发者更高效地构建可维护、可扩展和可重用的软件系统。以下是10大经典设计模式,掌握它们将有助于你轻松应对复杂项目挑战。
1. 单例模式(Singleton)
描述:确保一个类只有一个实例,并提供一个全局访问点。
应用场景:当系统只需要一个实例来控制对资源的访问时,如数据库连接池。
代码示例:
public class DatabaseConnection {
private static DatabaseConnection instance;
private DatabaseConnection() {}
public static DatabaseConnection getInstance() {
if (instance == null) {
instance = new DatabaseConnection();
}
return instance;
}
}
2. 工厂模式(Factory Method)
描述:定义一个接口用于创建对象,但让子类决定实例化哪个类。
应用场景:当系统需要根据不同条件创建不同类的实例时。
代码示例:
public interface Shape {
void draw();
}
public class Circle implements Shape {
public void draw() {
System.out.println("Drawing Circle");
}
}
public class Rectangle implements Shape {
public void draw() {
System.out.println("Drawing Rectangle");
}
}
public class ShapeFactory {
public static Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
}
return null;
}
}
3. 抽象工厂模式(Abstract Factory)
描述:创建相关或依赖对象的家族,而不需要明确指定具体类。
应用场景:当系统需要创建一系列相关或相互依赖的对象时。
代码示例:
public interface Color {
void fill();
}
public class Red implements Color {
public void fill() {
System.out.println("Filling Red");
}
}
public class Green implements Color {
public void fill() {
System.out.println("Filling Green");
}
}
public class Blue implements Color {
public void fill() {
System.out.println("Filling Blue");
}
}
public interface Shape {
void draw();
}
public class Circle implements Shape {
private Color color;
public Circle(Color color) {
this.color = color;
}
public void draw() {
System.out.println("Drawing Circle");
color.fill();
}
}
public class Square implements Shape {
private Color color;
public Square(Color color) {
this.color = color;
}
public void draw() {
System.out.println("Drawing Square");
color.fill();
}
}
public abstract class Factory {
public abstract Color getColor(String color);
public abstract Shape getShape(String shape);
}
public class ColorFactory extends Factory {
public Color getColor(String color) {
if (color.equalsIgnoreCase("RED")) {
return new Red();
} else if (color.equalsIgnoreCase("GREEN")) {
return new Green();
} else if (color.equalsIgnoreCase("BLUE")) {
return new Blue();
}
return null;
}
public Shape getShape(String shape) {
if (shape.equalsIgnoreCase("CIRCLE")) {
return new Circle(getColor("RED"));
} else if (shape.equalsIgnoreCase("SQUARE")) {
return new Square(getColor("GREEN"));
}
return null;
}
}
4. 建造者模式(Builder)
描述:将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。
应用场景:当需要创建复杂对象,且对象的构造过程需要分步骤进行时。
代码示例:
public class Person {
private String name;
private int age;
private String address;
// 省略getter和setter方法
}
public class PersonBuilder {
private String name;
private int age;
private String address;
public PersonBuilder setName(String name) {
this.name = name;
return this;
}
public PersonBuilder setAge(int age) {
this.age = age;
return this;
}
public PersonBuilder setAddress(String address) {
this.address = address;
return this;
}
public Person build() {
Person person = new Person();
person.setName(name);
person.setAge(age);
person.setAddress(address);
return person;
}
}
5. 原型模式(Prototype)
描述:通过复制现有的实例来创建新的实例,而不是通过构造函数。
应用场景:当需要创建大量相似对象,且对象的创建过程非常耗时或复杂时。
代码示例:
public class Prototype implements Cloneable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
6. 适配器模式(Adapter)
描述:将一个类的接口转换成客户期望的另一个接口,使原本接口不兼容的类可以一起工作。
应用场景:当需要使用一个已经存在的类,但其接口不符合当前系统的需求时。
代码示例:
public interface Target {
void request();
}
public class Adaptee {
public void specificRequest() {
System.out.println("Specific Request");
}
}
public class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void request() {
adaptee.specificRequest();
}
}
7. 桥接模式(Bridge)
描述:将抽象部分与实现部分分离,使它们都可以独立地变化。
应用场景:当抽象和实现部分可以独立变化时,如图形用户界面(GUI)框架。
代码示例:
public abstract class Abstraction {
protected Implementation implementation;
public void setImplementation(Implementation implementation) {
this.implementation = implementation;
}
public abstract void operation();
}
public class RefinedAbstraction extends Abstraction {
@Override
public void operation() {
System.out.println("Refined Operation");
implementation.operationImpl();
}
}
public abstract class Implementation {
public abstract void operationImpl();
}
public class ConcreteImplementationA extends Implementation {
@Override
public void operationImpl() {
System.out.println("Concrete Implementation A");
}
}
public class ConcreteImplementationB extends Implementation {
@Override
public void operationImpl() {
System.out.println("Concrete Implementation B");
}
}
8. 组合模式(Composite)
描述:将对象组合成树形结构以表示“部分-整体”的层次结构。
应用场景:当需要表示具有部分-整体关系的层次结构时,如文件系统。
代码示例:
public abstract class Component {
public abstract void operation();
}
public class Leaf extends Component {
@Override
public void operation() {
System.out.println("Leaf operation");
}
}
public class Composite extends Component {
private List<Component> children = new ArrayList<>();
@Override
public void operation() {
for (Component child : children) {
child.operation();
}
}
public void add(Component child) {
children.add(child);
}
public void remove(Component child) {
children.remove(child);
}
}
9. 装饰者模式(Decorator)
描述:动态地给一个对象添加一些额外的职责,而不改变其接口。
应用场景:当需要给一个对象添加额外的功能,且这些功能可以动态添加或删除时。
代码示例:
public interface Component {
void operation();
}
public class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("Concrete Component operation");
}
}
public class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
}
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addedBehavior();
}
private void addedBehavior() {
System.out.println("Added behavior A");
}
}
public class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addedBehavior();
}
private void addedBehavior() {
System.out.println("Added behavior B");
}
}
10. 观察者模式(Observer)
描述:当一个对象的状态发生改变时,所有依赖于它的对象都将得到通知并自动更新。
应用场景:当需要实现对象间的一对多依赖关系时,如事件监听。
代码示例:
public interface Observer {
void update();
}
public class ConcreteObserver implements Observer {
@Override
public void update() {
System.out.println("Observer updated");
}
}
public interface Subject {
void attach(Observer observer);
void detach(Observer observer);
void notifyObservers();
}
public class ConcreteSubject implements Subject {
private List<Observer> observers = new ArrayList<>();
@Override
public void attach(Observer observer) {
observers.add(observer);
}
@Override
public void detach(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update();
}
}
}
通过掌握这10大设计模式,你将能够更好地应对复杂项目挑战,提高代码的可读性、可维护性和可扩展性。希望这篇文章能帮助你更好地理解这些设计模式,并在实际项目中灵活运用。