java如何运用模式
Java设计模式的应用
Java设计模式是解决常见软件设计问题的可重用方案,分为创建型、结构型和行为型三大类。以下是一些常用设计模式及其在Java中的实现方式:
单例模式(Singleton)
确保一个类只有一个实例,并提供全局访问点。适用于配置管理、线程池等场景。
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
工厂模式(Factory)
定义一个创建对象的接口,让子类决定实例化哪个类。适用于需要根据不同条件创建不同对象的场景。
public interface Shape {
void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing Circle");
}
}
public class ShapeFactory {
public Shape getShape(String shapeType) {
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
}
return null;
}
}
观察者模式(Observer)
定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖它的对象都会得到通知并自动更新。适用于事件处理系统。
public interface Observer {
void update(String message);
}
public class ConcreteObserver implements Observer {
@Override
public void update(String message) {
System.out.println("Received: " + message);
}
}
public class Subject {
private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void notifyObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
策略模式(Strategy)
定义一系列算法,将每个算法封装起来,并使它们可以互相替换。适用于需要动态切换算法或行为的场景。
public interface PaymentStrategy {
void pay(int amount);
}
public class CreditCardPayment implements PaymentStrategy {
@Override
public void pay(int amount) {
System.out.println("Paying " + amount + " via Credit Card");
}
}
public class PaymentContext {
private PaymentStrategy strategy;
public void setStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}
public void executePayment(int amount) {
strategy.pay(amount);
}
}
装饰器模式(Decorator)
动态地给一个对象添加额外的职责,相比继承更加灵活。适用于需要扩展功能但不想修改原有代码的场景。
public interface Coffee {
double getCost();
String getDescription();
}
public class SimpleCoffee implements Coffee {
@Override
public double getCost() {
return 1.0;
}
@Override
public String getDescription() {
return "Simple coffee";
}
}
public class MilkDecorator implements Coffee {
private Coffee coffee;
public MilkDecorator(Coffee coffee) {
this.coffee = coffee;
}
@Override
public double getCost() {
return coffee.getCost() + 0.5;
}
@Override
public String getDescription() {
return coffee.getDescription() + ", milk";
}
}
适配器模式(Adapter)
将一个类的接口转换成客户希望的另一个接口,使原本不兼容的类可以一起工作。适用于整合遗留代码或第三方库。

public interface ModernPrinter {
void printDocument(String document);
}
public class LegacyPrinter {
public void print(String text) {
System.out.println("Legacy printer: " + text);
}
}
public class PrinterAdapter implements ModernPrinter {
private LegacyPrinter legacyPrinter;
public PrinterAdapter(LegacyPrinter legacyPrinter) {
this.legacyPrinter = legacyPrinter;
}
@Override
public void printDocument(String document) {
legacyPrinter.print(document);
}
}
在实际应用中,应根据具体需求选择合适的设计模式。设计模式不是银弹,过度使用可能导致代码复杂度增加。合理运用设计模式可以提高代码的可维护性、可扩展性和可重用性。






