设计模式是在软件设计中针对常见问题的解决方案的可复用模板。这些模式提供了经过验证的设计原则和方法,能够帮助开发人员更加灵活、可扩展和可维护的构建软件系统。
以下是几种常见的设计模式:
工厂模式提供了一个创建对象的接口,但由子类决定实例化的具体类。它将对象的创建与使用分离,使得代码更加灵活、可扩展。
// 抽象产品类
interface Product {
void use();
}
// 具体产品类
class ConcreteProduct implements Product {
@Override
public void use() {
System.out.println("使用具体产品");
}
}
// 工厂类
class Factory {
public static Product createProduct() {
return new ConcreteProduct();
}
}
// 使用工厂创建产品
Product product = Factory.createProduct();
product.use();
单例模式确保一个类只有一个实例,并提供一个全局访问点。这在需要全局唯一对象或共享资源的场景下非常有用。
// 单例类
class Singleton {
private static Singleton instance;
private Singleton() {
// 私有构造函数
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public void showMessage() {
System.out.println("Hello, Singleton!");
}
}
// 使用单例类
Singleton singleton = Singleton.getInstance();
singleton.showMessage();
观察者模式定义了对象之间的一对多依赖关系,使得当一个对象改变状态时,其依赖对象都会收到通知并自动更新。
import java.util.ArrayList;
import java.util.List;
// 主题接口
interface Subject {
void attach(Observer observer);
void detach(Observer observer);
void notifyObservers();
}
// 具体主题类
class ConcreteSubject implements Subject {
private List observers = new ArrayList<>();
private String state;
@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(state);
}
}
public void setState(String state) {
this.state = state;
notifyObservers();
}
}
// 观察者接口
interface Observer {
void update(String state);
}
// 具体观察者类
class ConcreteObserver implements Observer {
private String observerState;
@Override
public void update(String state) {
observerState = state;
System.out.println("观察者收到新状态:" + observerState);
}
}
// 使用观察者模式
ConcreteSubject subject = new ConcreteSubject();
Observer observer1 = new ConcreteObserver();
Observer observer2 = new ConcreteObserver();
subject.attach(observer1);
subject.attach(observer2);
subject.setState("Hello, Observer!");
适配器模式用于将一个类的接口转换成客户端期望的另一个接口。它使得原本不兼容的类可以一起工作。
// 目标接口
interface Target {
void request();
}
// 被适配的类
class Adaptee {
void specificRequest() {
System.out.println("适配者的特殊请求");
}
}
// 适配器类
class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void request() {
adaptee.specificRequest();
}
}
// 使用适配器
Adaptee adaptee = new Adaptee();
Target target = new Adapter(adaptee);
target.request();
装饰器模式允许向现有对象添加新功能,同时又不改变其结构。它是通过创建包装对象,将新功能附加到对象上的一种灵活方式。
// 抽象组件
interface Component {
void operation();
}
// 具体组件
class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("执行具体操作");
}
}
// 抽象装饰器
abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
}
// 具体装饰器
class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addedBehavior();
}
private void addedBehavior() {
System.out.println("添加额外的行为");
}
}
// 使用装饰器
Component component = new ConcreteComponent();
Component decorator = new ConcreteDecorator(component);
decorator.operation();
策略模式定义了一系列的算法,并将每个算法封装在可相互替换的策略类中。通过使用不同的策略对象,可以在运行时改变对象的行为。
// 抽象策略
interface Strategy {
void execute();
}
// 具体策略A
class ConcreteStrategyA implements Strategy {
@Override
public void execute() {
System.out.println("执行策略A");
}
}
// 具体策略B
class ConcreteStrategyB implements Strategy {
@Override
public void execute() {
System.out.println("执行策略B");
}
}
// 环境类
class Context {
private Strategy strategy;
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void executeStrategy() {
if (strategy != null) {
strategy.execute();
}
}
}
// 使用策略模式
Context context = new Context();
Strategy strategyA = new ConcreteStrategyA();
Strategy strategyB = new ConcreteStrategyB();
context.setStrategy(strategyA);
context.executeStrategy();
context.setStrategy(strategyB);
context.executeStrategy();