基于Java谈常用设计模式
设计模式是软件工程中的重要概念,它们提供了一种在软件设计和开发过程中解决常见问题的方法。在Java编程中,设计模式可以帮助开发人员编写更具可维护性、可扩展性和可重用性的代码。本博客将介绍一些常见的设计模式以及如何在Java中应用它们。
创建型设计模式
1. 单例模式 (Singleton)
单例模式确保一个类只有一个实例,并提供全局访问点。在Java中,可以使用以下方式实现单例模式:
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
2. 工厂模式 (Factory)
工厂模式用于创建对象,但将具体的实例化过程封装在工厂类中。这有助于隐藏对象创建的细节,并支持代码的扩展和维护。
public interface Product {
void create();
}
public class ConcreteProductA implements Product {
@Override
public void create() {
System.out.println("Creating Product A");
}
}
public class ConcreteProductB implements Product {
@Override
public void create() {
System.out.println("Creating Product B");
}
}
public class ProductFactory {
public static Product createProduct(String type) {
if ("A".equals(type)) {
return new ConcreteProductA();
} else if ("B".equals(type)) {
return new ConcreteProductB();
}
return null;
}
}
结构型设计模式
3. 适配器模式 (Adapter)
适配器模式允许将一个类的接口转换成客户端所期望的接口。这对于复用现有类的代码非常有用。
public interface Target {
void request();
}
public class Adaptee {
public void specificRequest() {
System.out.println("Adaptee's specific request");
}
}
public class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void request() {
adaptee.specificRequest();
}
}
4. 装饰器模式 (Decorator)
装饰器模式允许在不修改现有对象的情况下动态地扩展其功能。
public interface Coffee {
double cost();
String getDescription();
}
public class Espresso implements Coffee {
@Override
public double cost() {
return 2.0;
}
@Override
public String getDescription() {
return "Espresso";
}
}
public abstract class CoffeeDecorator implements Coffee {
protected Coffee coffee;
public CoffeeDecorator(Coffee coffee) {
this.coffee = coffee;
}
@Override
public double cost() {
return coffee.cost();
}
@Override
public String getDescription() {
return coffee.getDescription();
}
}
public class MilkDecorator extends CoffeeDecorator {
public MilkDecorator(Coffee coffee) {
super(coffee);
}
@Override
public double cost() {
return super.cost() + 1.0;
}
@Override
public String getDescription() {
return super.getDescription() + ", with Milk";
}
}
行为型设计模式
5. 观察者模式 (Observer)
观察者模式定义了一种一对多的依赖关系,当一个对象的状态发生变化时,所有依赖于它的对象都会得到通知并更新。
import java.util.ArrayList;
import java.util.List;
public interface Observer {
void update(String message);
}
public class ConcreteObserver implements Observer {
private String name;
public ConcreteObserver(String name) {
this.name = name;
}
@Override
public void update(String message) {
System.out.println(name + " received message: " + message);
}
}
public class Subject {
private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void notifyObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
6. 策略模式 (Strategy)
策略模式定义了一组算法,将每个算法封装起来,并使它们可以互换使用。这允许在运行时选择合适的算法。
public interface PaymentStrategy {
void pay(int amount);
}
public class CreditCardPayment implements PaymentStrategy {
private String cardNumber;
public CreditCardPayment(String cardNumber) {
this.cardNumber = cardNumber;
}
@Override
public void pay(int amount) {
System.out.println("Paid " + amount + " using credit card " + cardNumber);
}
}
public class PayPalPayment implements PaymentStrategy {
private String email;
public PayPalPayment(String email) {
this.email = email;
}
@Override
public void pay(int amount) {
System.out.println("Paid " + amount + " using PayPal account " + email);
}
}
总结
设计模式是面向对象编程的重要组成部分,它们提供了在不同情境下解决常见问题的方法。在Java中,设计模式有助于编写更具可维护性和可扩展性的代码。在本博客中,我们介绍了一些常见的设计模式,包括单例模式、工厂模式、适配器模式、装饰器模式、观察者模式和策略模式,并提供了相应的示例代码。